diff --git a/.config/cargo-ci.toml b/.config/cargo-ci.toml index 956491323b..93a48332ff 100644 --- a/.config/cargo-ci.toml +++ b/.config/cargo-ci.toml @@ -29,3 +29,9 @@ opt-level = 1 [profile.dev.package.craft-cms] opt-level = 1 + +# The runtime under every screen test: each frame of a fixture runs its pass, layout, focus and access tree. At +# opt-level 2 a suite trial runs about 40 percent fewer instructions than at 0 (Table activation 19.8 G to 11.9 G); +# opt-level 1 gives about 30 percent. Every UI crate waits for its compile, which grows by about a minute. +[profile.dev.package.craft-ui-contract] +opt-level = 2 diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 63170f1214..5c802e799e 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -122,10 +122,12 @@ jobs: cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }} cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }} lint-cache: false - # The vendored crates are on the workspace `exclude` list, so unreached-rs has no module tree for them. + # The vendored crates are on the workspace `exclude` list and craft-pdf's read-only contract is a + # workspace of its own (pdf.yml tests it), so unreached-rs has no module tree for them. unreached-rs-allow: | **/fixtures/** vendor/** + crates/pdf/read-only-contract/** timeout-minutes: &timeout 120 # Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml). tools: &tools cargo-nextest@0.9.150 @@ -167,8 +169,8 @@ jobs: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings # A selection that reaches a replay-audit crate builds once in a `build` job, which writes # three nextest archives and then runs the doctests; three shard legs run them in parallel: - # every selected test outside the replay audit's crates, those crates (run plainly, then with the - # audit), and craft-image-codecs with default features. Any other selection + # every selected test outside the replay audit's crates and craft-draw, those crates (run plainly, + # then the audit crates with the audit), and craft-image-codecs with default features. Any other selection # (and every macOS and Windows leg) builds and runs in one leg. scripts/ci-workspace-tests.sh # holds every step. test-shards: ${{ needs.platforms.outputs.audit == 'true' && 3 || 0 }} diff --git a/AGENTS.md b/AGENTS.md index ff4606fd5f..2fd1513b85 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,7 +65,7 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119 Shared Rust libraries for the Craft Apps: a Cargo workspace (edition 2024, resolver 3) of crates under `crates/`. See `README.md` for layout and released versions. -- **New crates** go in `crates/`, named `craft-`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true`. +- **New crates** go in `crates/`, named `craft-`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true` (`crates/font-os-windows` is the one exception; see `unsafe` below). - **No app code.** A crate here is useful to more than one app and does not depend on any app. -- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, and no crate in `crates/` allows it, so no module here may use `unsafe`. The one exception is vendored upstream code in `vendor/hayro-syntax`. +- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, so no module here may use `unsafe`, with two exceptions: vendored upstream code in `vendor/hayro-syntax`, and `crates/font-os-windows`, because loading a font into the running Windows session needs `AddFontResourceW`, which the Windows crates offer only as an unsafe call. That crate copies the workspace lints with `unsafe_code = "deny"` instead of `[lints] workspace = true`, and allows `unsafe` only on the functions that make Win32 calls. - **Checks for the crates you changed:** `cargo fmt --check`, `cargo clippy -p --all-targets -- -D warnings`, `cargo test -p `. diff --git a/Cargo.lock b/Cargo.lock index 62dfc38e65..4b32db1727 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1804,6 +1804,7 @@ dependencies = [ "craft-flow", "craft-font-catalog", "craft-font-manager", + "craft-font-os-windows", "craft-font-store", "craft-font-subset", "craft-format", @@ -1901,6 +1902,7 @@ dependencies = [ "craft-scraft-format", "craft-settings", "craft-sf2", + "craft-shared-vec", "craft-sheet", "craft-shx", "craft-silhouette-studio", @@ -2039,6 +2041,7 @@ name = "craft-appkit" version = "0.1.0" dependencies = [ "block2 0.6.2", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", ] @@ -2271,6 +2274,7 @@ dependencies = [ "craft-ai-agents", "craft-atomic", "craft-flags", + "craft-platform", "dirs", "getrandom 0.3.4", "log", @@ -2409,6 +2413,7 @@ name = "craft-dialogs" version = "0.1.0" dependencies = [ "block2 0.6.2", + "craft-appkit", "craft-atomic", "craft-behavior", "craft-browse", @@ -2772,6 +2777,14 @@ dependencies = [ "skrifa 0.47.0", ] +[[package]] +name = "craft-font-os-windows" +version = "0.1.0" +dependencies = [ + "windows-registry", + "windows-sys 0.61.2", +] + [[package]] name = "craft-font-store" version = "0.1.0" @@ -2779,6 +2792,7 @@ dependencies = [ "cap-primitives", "craft-atomic", "craft-font-catalog", + "craft-font-os-windows", "flate2", "log", "ruzstd", @@ -4026,6 +4040,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-shared-vec" +version = "0.1.0" +dependencies = [ + "craft-shared-vec", + "proptest", + "serde", + "serde_json", +] + [[package]] name = "craft-sheet" version = "0.1.0" @@ -4145,6 +4169,7 @@ dependencies = [ name = "craft-suite-account" version = "0.1.0" dependencies = [ + "craft-platform", "dirs", "keyring", "keyring-core", @@ -5571,7 +5596,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "emath", @@ -5627,7 +5652,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -5662,7 +5687,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "accesskit", "ahash", @@ -5681,7 +5706,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -5700,7 +5725,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5720,7 +5745,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "egui", @@ -5733,7 +5758,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "eframe", "egui", @@ -5810,7 +5835,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", ] @@ -5883,7 +5908,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -5909,7 +5934,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[package]] name = "equator" @@ -15241,19 +15266,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" diff --git a/Cargo.toml b/Cargo.toml index cc40daf56d..f842c026e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ craft-ssip = { path = "crates/ssip" } craft-ber = { path = "crates/ber" } craft-proto = { path = "crates/proto" } craft-render-parity = { path = "crates/render-parity" } +craft-shared-vec = { path = "crates/shared-vec" } acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` @@ -123,6 +124,7 @@ craft-exr = { path = "crates/exr" } craft-flags = { path = "crates/flags" } craft-font-catalog = { path = "crates/font-catalog" } craft-font-manager = { path = "crates/font-manager" } +craft-font-os-windows = { path = "crates/font-os-windows" } craft-font-store = { path = "crates/font-store" } craft-gainmap = { path = "crates/gainmap" } craft-flow = { path = "crates/flow" } @@ -316,20 +318,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/README.md b/README.md index f1ded80ca2..7884f375af 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit and filters over the Google Fonts index, installed fonts by family, the font store interface, and (`ui` feature) `FontsPanel`, the whole interface as one panel for the launcher's Fonts tab and the standalone app. +- [`craft-font-os-windows`](crates/font-os-windows/src/lib.rs): the Win32 calls `craft-font-store` + needs on Windows to make a font available to every app of the user (the per-user font + registry, `AddFontResourceW`, `WM_FONTCHANGE`), behind a safe API. - [`craft-font-store`](crates/font-store/README.md): the suite's font store: the pinned Google Fonts and Noto indexes plus indexes the user adds (never curated), exact lookup by family and style or PostScript name, and installs from each source's URLs (jsDelivr, then raw GitHub) @@ -374,6 +377,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit revisions panel, presence, voting, cursor chat and join over the app's own transport (`ui` feature). - [`craft-settings`](crates/settings/README.md): `config.toml` settings storage for every app: platform folders, portable mode and overrides, atomic saves while running, backup, damaged-file recovery and schema migrations, plus remembered dialog options and preset folders (also on wasm32). Policy in [docs/settings-storage.md](docs/settings-storage.md). +- [`craft-shared-vec`](crates/shared-vec/README.md): an ordered, indexed list whose clones share storage, for document trees kept in an undo history: an edit copies the blocks on its path instead of the whole list, and `bytes_not_in` counts what keeping two versions costs. Reads and writes as a plain sequence with `serde`. - [`craft-sheet`](crates/sheet/README.md): spreadsheet vocabulary shared by `craft-xls`, `craft-xlsx` and `craft-ods`: cell positions and A1 text, cell values and error values, sheet-name quoting, Excel's built-in number formats and indexed colour palette. Not a file format; no dependencies. - [`craft-sf2`](crates/sf2/README.md): SoundFont 2 (`.sf2`) reader: the sample pool and, per preset, the key and velocity regions a note sounds, with tuning, loop points, pan, level and volume envelope resolved from the preset and instrument zones. Bounded on hostile input. From LoopCraft. - [`craft-silhouette-studio`](crates/silhouette-studio/src/lib.rs): bounded, fail-closed reader for Silhouette Studio `.studio` and `.studio3` documents: outlines, line colours and page size in millimetres. Protected designs are refused. @@ -476,7 +480,7 @@ architecture: [docs/craft-framework.md](docs/craft-framework.md). - [`craft-theme`](crates/theme/README.md) and [`craft-theme-store`](crates/theme-store/README.md): the token model, the built-in themes and the suite's theme selection ([docs/suite-themes.md](docs/suite-themes.md)). - [`craft-host`](crates/host/README.md): the services an app installs once and every feature reads. -- `craft-win32`: the Win32 calls that need `unsafe`, behind a safe API; the one crate that allows `unsafe`. +- `craft-win32`: the window-procedure and window-handle Win32 calls that need `unsafe`, behind a safe API. - Tools, not shipped in apps: `craft-ui-gallery` (the story viewer), `story-render` (one component's stories to PNG files), [`craft-design-lint`](crates/design-lint/README.md), `craft-ui-bench`, `craft-ui-test-kit`. diff --git a/crates/appkit/Cargo.toml b/crates/appkit/Cargo.toml index ad602e383a..5d451b3975 100644 --- a/crates/appkit/Cargo.toml +++ b/crates/appkit/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-appkit" -description = "The macOS menu-tracking observers that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." +description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." version.workspace = true edition.workspace = true license.workspace = true @@ -8,11 +8,12 @@ rust-version.workspace = true repository.workspace = true # `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through -# `NSNotificationCenter` with a block. +# `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action. [target.'cfg(target_os = "macos")'.dependencies] block2 = "0.6.2" -objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSMenu"] } -objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] } +objc2 = { version = "0.6.4", default-features = false, features = ["std"] } +objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] } +objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] } # The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's # `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one diff --git a/crates/appkit/src/lib.rs b/crates/appkit/src/lib.rs index 78dd786b15..70ed01f92d 100644 --- a/crates/appkit/src/lib.rs +++ b/crates/appkit/src/lib.rs @@ -1,5 +1,5 @@ -//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking. macOS -//! only; the crate is empty elsewhere. +//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the +//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere. //! //! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every //! block says why it is sound. @@ -14,6 +14,8 @@ use block2::RcBlock; use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification}; use objc2_foundation::{NSNotification, NSNotificationCenter}; +pub mod save_panel; + /// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)` /// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once /// for the process; a later call replaces nothing and does nothing. diff --git a/crates/appkit/src/save_panel.rs b/crates/appkit/src/save_panel.rs new file mode 100644 index 0000000000..979be8f96d --- /dev/null +++ b/crates/appkit/src/save_panel.rs @@ -0,0 +1,64 @@ +//! The Save panel calls that need `unsafe`: making a panel that may be nil, and a pop-up menu's action. + +use objc2::rc::Retained; +use objc2::runtime::AnyObject; +use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel}; +use objc2_app_kit::{NSPopUpButton, NSSavePanel}; +use objc2_foundation::{NSObject, NSObjectProtocol}; + +/// A new Save panel, or `None` when AppKit returns nil. `+[NSSavePanel savePanel]` returns nil on some systems +/// (storytold/vectorcraft#5980), and objc2's `NSSavePanel::savePanel` panics on it. +pub fn new_save_panel(mtm: MainThreadMarker) -> Option> { + // SAFETY: `-init` is the initializer of a bare panel, called once on the allocation. The result is typed as + // `Option`, so nil is `None`. + let panel: Option> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] }; + if panel.is_some() { + return panel; + } + // SAFETY: a class method that returns an autoreleased panel or nil, typed as `Option`. + unsafe { msg_send![NSSavePanel::class(), savePanel] } +} + +/// The closure a [`PopUpChoice`] calls. +pub struct Ivars { + on_choose: Box, +} + +define_class!( + // SAFETY: NSObject has no subclassing requirements, and the class implements no `Drop`. + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[ivars = Ivars] + #[name = "CraftPopUpChoice"] + /// The target of a pop-up menu's action; see [`on_choose`]. + pub struct PopUpChoice; + + // SAFETY: NSObjectProtocol has no additional requirements. + unsafe impl NSObjectProtocol for PopUpChoice {} + + impl PopUpChoice { + // SAFETY: NSControl's target-action sends the pop-up button as the one object argument. + #[unsafe(method(choose:))] + fn choose(&self, sender: &NSPopUpButton) { + if let Ok(index) = usize::try_from(sender.indexOfSelectedItem()) { + (self.ivars().on_choose)(index); + } + } + } +); + +/// Calls `on_choose` with the index of the item the user chooses in `popup`. A control does not retain its target, +/// so the caller keeps the returned object for as long as `popup` can send its action. +pub fn on_choose(mtm: MainThreadMarker, popup: &NSPopUpButton, on_choose: impl Fn(usize) + 'static) -> Retained { + let this = PopUpChoice::alloc(mtm).set_ivars(Ivars { on_choose: Box::new(on_choose) }); + // SAFETY: NSObject's designated initializer, called once on the allocated subclass. + let target: Retained = unsafe { msg_send![super(this), init] }; + let object: &AnyObject = ⌖ + // SAFETY: `choose:` takes the sender, the signature a control's action is sent with, and the caller keeps + // `target` alive while `popup` can send it (the documentation above). + unsafe { + popup.setTarget(Some(object)); + popup.setAction(Some(sel!(choose:))); + } + target +} diff --git a/crates/automation/README.md b/crates/automation/README.md index 2fdbf75be4..120e046f3e 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -14,7 +14,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch | `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | -| `synthetic` | `Click`, `Move`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `synthetic` | `Click`, `Move`, `Drag`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.drag` (a press, moves in even steps and the release, from one request), `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | | `access` | Named controls over the window's access tree (`ui` feature): `Target` (`{name, role?, within?, index?}`, found in reading order), `describe`, and `access_method`, which answers `ui.find` from the tree `ControlChannel::poll_input` has the host keep. | | `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. | | `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. | diff --git a/crates/automation/src/agents/link.rs b/crates/automation/src/agents/link.rs index 6296beea76..c240725742 100644 --- a/crates/automation/src/agents/link.rs +++ b/crates/automation/src/agents/link.rs @@ -16,7 +16,7 @@ use crate::security; use crate::server::{self, Listening}; /// How long after a failed start [`AgentLink::sync`] tries again with the same settings, so -/// freeing a taken port is enough. +/// freeing a taken port is enough. A refused token file is not tried again: see [`AgentLink::sync`]. pub const RETRY: Duration = Duration::from_secs(5); /// Why agents cannot connect, or what the app could not apply. `Display` is the English sentence @@ -123,6 +123,10 @@ pub struct AgentLink { applied: Option>, retry_at: Option, retry: Duration, + /// The token a failed start already read and checked, for its retries with the same settings; + /// cleared once a start succeeds or the settings change. On Windows the check starts `whoami` and PowerShell (`owner_only`), about 300 ms + /// on the UI thread, which every retry of a taken port would otherwise pay again. + checked_token: Option, status: AgentLinkStatus, } @@ -144,6 +148,7 @@ impl AgentLink { applied: None, retry_at: None, retry: RETRY, + checked_token: None, status: AgentLinkStatus::default(), } } @@ -166,7 +171,12 @@ impl AgentLink { /// Brings the server in line with `want` (`None`: agents may not connect): start it, restart it /// on another port, stop it, or keep it while other settings change. Does nothing while `want` - /// equals the last call's and no retry of a failed start is due. + /// equals the last call's and no retry of a failed start is due. A token file refused as it is + /// (open to others, a damaged token) is replaced by a new one (`fresh_token`). One that still + /// can't be used (a folder in its place, a folder that can't be written) schedules no retry: + /// that lasts until someone changes it, and on Windows each check blocks the UI thread for + /// about 300 ms (`owner_only` starts `whoami` and PowerShell), which a retry every [`RETRY`] + /// turned into a stall every few seconds (photocraft#17006). Changing the settings tries again. pub fn sync(&mut self, want: Option<&AgentSettings>, host: &WindowHost) -> LinkUpdate { let mut update = LinkUpdate::default(); if self.launch.is_some() { @@ -174,9 +184,15 @@ impl AgentLink { } let now = motion::now(); let retry_due = self.retry_at.is_some_and(|at| now >= at); - if self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want) && !retry_due { + let unchanged = self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want); + if unchanged && !retry_due { return update; } + // Only a retry with the same settings reuses the token its failed start checked: after a + // change (agents off and on again, another port) the file may hold another token by now. + if !unchanged { + self.checked_token = None; + } let before = (self.status.clone(), self.applied.clone().flatten()); self.applied = Some(want.cloned()); self.retry_at = None; @@ -218,6 +234,10 @@ impl AgentLink { update.requests = Some(requests); Ok(()) } + Err(problem @ LinkProblem::TokenFile(_)) => { + log::warn!("{problem}"); + Err(problem) + } Err(problem) => { log::warn!("{problem}"); self.retry_at = Some(motion::now() + self.retry); @@ -229,13 +249,21 @@ impl AgentLink { /// The token from the settings folder (created `0600` when missing), the server, then the /// connection file. Any failure leaves nothing running. - fn start(&self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver), LinkProblem> { + /// A retry of a failed start reuses the token that start checked ([`Self::checked_token`]). + /// The token file is the link's own, so one refused as it is gets a new token (see + /// [`fresh_token`]). + fn start(&mut self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver), LinkProblem> { let token_file = dir.join(TOKEN_FILE); - let token = security::server_token(None, Some(&token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()))?; + let token = match self.checked_token.clone() { + Some(token) => token, + None => fresh_token(&token_file)?, + }; + self.checked_token = Some(token.clone()); let (requests, server) = server::listen(port, token, host.clone()).map_err(|e| LinkProblem::Listen { port, error: e.to_string() })?; let running = Running { server, dir: dir.to_path_buf(), port_pref }; let connection = Connection::new(running.server.addr.port(), token_file, self.app.clone()); write_connection(dir, &connection).map_err(|e| LinkProblem::Publish(e.to_string()))?; + self.checked_token = None; Ok((running, requests)) } @@ -250,3 +278,22 @@ impl AgentLink { self.status.problem = Some(problem); } } + +/// The token in `token_file`, created when missing. A regular file the check refuses (one an +/// older app wrote with its folder's access list on Windows, open to Administrators, or a damaged +/// token) is replaced with a new token, once: the token is only this link's secret, and a client +/// reads the new one from the file. Kept, its refusal would keep agents out until someone deleted +/// the file. Anything else in the way (a folder, a link) is reported, not removed. +fn fresh_token(token_file: &Path) -> Result { + let read = || security::server_token(None, Some(token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string())); + let problem = match read() { + Ok(token) => return Ok(token), + Err(problem) => problem, + }; + if !std::fs::symlink_metadata(token_file).is_ok_and(|meta| meta.is_file()) { + return Err(problem); + } + log::warn!("{problem}; writing a new token file"); + std::fs::remove_file(token_file).map_err(|e| LinkProblem::TokenFile(format!("{}: {e}", token_file.display())))?; + read() +} diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs index b1c005dadf..2290c7c08f 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -5,8 +5,9 @@ //! (`engine.execute`, `ui.inspect`, `ui.set`, `ui.dialog.*`, `ui.screenshot`, …) and hands the //! [`Reply`] to [`ControlChannel::settle`]. The channel replies at once, after the queued //! injected input has been processed ([`Reply::AfterInput`], so a following `ui.inspect` sees -//! the effect), when a background job ends ([`Reply::AfterJob`]), or when a screenshot completes -//! ([`Reply::Screenshot`], through [`crate::screenshot::Captures`]). +//! the effect), when a background job ends ([`Reply::AfterJob`]), when the app answers a dialog's +//! held OK ([`Reply::AfterHeldOk`]), or when a screenshot completes ([`Reply::Screenshot`], through +//! [`crate::screenshot::Captures`]). //! //! Deadlines: a request still queued when its [`REPLY_DEADLINE`] passes is dropped before dispatch //! and the transport replies [`expired_error`] (safe to re-send); one that was dispatched and gave @@ -15,6 +16,7 @@ use std::sync::mpsc::{Receiver, Sender}; +use craft_ui::dialog::{DialogHost, DialogId, HeldOk}; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use serde_json::{Value, json}; @@ -133,6 +135,19 @@ pub enum Reply { /// A `ui.accessTree`: hold the reply until the window's settled access tree can be read /// ([`ControlChannel::poll_access_trees`]). AccessTree, + /// A `ui.dialog.confirm` that filed the held OK of a dialog for the app: hold the reply until the + /// app answers it ([`ControlChannel::poll_held`]). + #[non_exhaustive] + AfterHeldOk { + /// The dialog whose OK is held. + dialog: DialogId, + /// Which open of the dialog ([`DialogHost::open_serial`]): a later open of the same dialog + /// is not the one the request confirmed. + open: u64, + /// The app's refusal of the dialog's previous OK, when this confirm filed OK again after it: + /// the earlier confirms still held for this open are answered with it. + refused: Option, + }, } impl Reply { @@ -174,6 +189,7 @@ pub struct ControlChannel { input_waiters: Vec>, job_waiters: Vec<(JobId, Sender)>, tree_waiters: Vec>, + held_waiters: Vec<(DialogId, u64, Sender)>, /// The screenshot queue; the app calls its `issue` and `drain` from its UI and logic phases. pub captures: Captures, } @@ -181,7 +197,14 @@ pub struct ControlChannel { impl ControlChannel { /// Attach a transport's receiver (TCP, stdin, tests). pub fn new(rx: Receiver) -> Self { - Self { rx, input_waiters: Vec::new(), job_waiters: Vec::new(), tree_waiters: Vec::new(), captures: Captures::default() } + Self { + rx, + input_waiters: Vec::new(), + job_waiters: Vec::new(), + tree_waiters: Vec::new(), + held_waiters: Vec::new(), + captures: Captures::default(), + } } /// The next request to run, claimed through [`Dispatch::start`]. Expired or abandoned @@ -200,8 +223,16 @@ impl ControlChannel { /// Reply now, or park the reply on input, a job or a screenshot. `settle_ms` is the /// screenshot settle delay ([`crate::screenshot::settle_ms`] of the animation time); - /// `document` the identity a screenshot is attributed to. + /// `document` the identity a screenshot is attributed to. A screenshot is admitted at + /// [`motion::now`]; [`Self::settle_at`] takes the time instead. pub fn settle(&mut self, req: ControlRequest, outcome: Reply, document: Option, settle_ms: f64) { + self.settle_at(req, outcome, document, settle_ms, motion::now()); + } + + /// [`Self::settle`] with a screenshot admitted at `now`: its settle delay and its + /// [`crate::screenshot::DEADLINE`] count from `now`, on the clock the app passes to + /// [`Captures::issue`] and [`Captures::drain`]. + pub fn settle_at(&mut self, req: ControlRequest, outcome: Reply, document: Option, settle_ms: f64, now: Instant) { let reply = req.reply; match outcome { Reply::Done(v) => { @@ -210,9 +241,21 @@ impl ControlChannel { Reply::AfterInput => self.input_waiters.push(reply), Reply::AfterJob(job) => self.job_waiters.push((job, reply)), Reply::AccessTree => self.tree_waiters.push(reply), + Reply::AfterHeldOk { dialog, open, refused } => { + if let Some(reason) = refused { + self.held_waiters.retain(|(earlier, earlier_open, tx)| { + let answered = (*earlier, *earlier_open) == (dialog, open); + if answered { + let _ = tx.send(json!({"ok": false, "error": reason})); + } + !answered + }); + } + self.held_waiters.push((dialog, open, reply)); + } Reply::Screenshot { token, path, region, viewport } => { let request = ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms }; - if let Err((reply, e)) = self.captures.admit(request, motion::now()) { + if let Err((reply, e)) = self.captures.admit(request, now) { let _ = reply.send(json!({"ok": false, "error": e})); } } @@ -291,6 +334,29 @@ impl ControlChannel { } } + /// Answers the held `ui.dialog.confirm` requests ([`Reply::AfterHeldOk`]) from `host`: success + /// once the app accepted the dialog's held OK; once it refused it, an error whose text is the + /// refusal's reason, English for a reason given as a `Word`; an error once the dialog closed + /// while it waited, also when the same dialog opened again since. A request stays held while + /// the app has not answered. Call it in every pass after the app answered the held OKs it + /// answers in that pass and before the pass runs the host ([`DialogHost::run`]), which closes a + /// dialog the app accepted; calling it more than once in a pass is harmless. + pub fn poll_held(&mut self, host: &DialogHost) { + self.held_waiters.retain(|(dialog, open, reply)| { + let answer = match host.held_state(*dialog) { + _ if host.open_serial(*dialog) != Some(*open) => { + json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"}) + } + Some(HeldOk::Waiting) => return true, + Some(HeldOk::Accepted) => json!({"ok": true, "result": null}), + Some(HeldOk::Refused(reason)) => json!({"ok": false, "error": reason.as_str()}), + _ => json!({"ok": false, "error": "the app refused OK"}), + }; + let _ = reply.send(answer); + false + }); + } + /// Drops the host's queued input and the step in flight, and fails every /// [`Reply::AfterInput`] waiter with `input cancelled: {reason}`, also when only waiters /// remain (their input was already consumed). True when anything was pending or waiting. @@ -331,6 +397,6 @@ impl ControlChannel { /// Waiters of every kind, for `ui.inspect`'s `pending` count and tests. pub fn waiting(&self) -> usize { - self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.captures.pending() + self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.held_waiters.len() + self.captures.pending() } } diff --git a/crates/automation/src/dialogs.rs b/crates/automation/src/dialogs.rs index 398c917c57..749626cc61 100644 --- a/crates/automation/src/dialogs.rs +++ b/crates/automation/src/dialogs.rs @@ -1,7 +1,8 @@ //! `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` on an app's [`DialogHost`], for every dialog type. //! -//! The app's method table hands these methods to [`dialog_method`] and lists [`inspect`] under `ui.inspect`'s -//! `dialogs`. A dialog is named by the `id` `inspect` lists, or `"top"` for the top one; its fields are its +//! The app's method table hands these methods to [`dialog_method`], or to [`dialog_reply`] for a reply that waits +//! for the app's answer to a held OK, and lists [`inspect`] under `ui.inspect`'s `dialogs`. A dialog is named by the +//! `id` `inspect` lists, or `"top"` for the top one; its fields are its //! [`StackDialog::json_fields`](craft_ui::dialog::StackDialog::json_fields). Opening a dialog (`ui.dialog.open`) and //! running the command its answer is for stay the app's: an answer waits for the app's `DialogHost::take` as a //! click's would. @@ -10,6 +11,7 @@ use craft_ui::dialog::{DialogHost, DialogId, HeldOk, StandardPrompt}; use egui::Context; use serde_json::{Value, json}; +use crate::control::Reply; use crate::protocol::Params; /// The most `fields` one `ui.dialog.set` call takes. @@ -36,7 +38,8 @@ pub fn inspect(host: &DialogHost) -> Value { /// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]); `{dialog, fields: [{field, /// value?}]}` sets a list of at most [`MAX_DIALOG_FIELDS`], all or none ([`DialogHost::set_json_fields`]). /// - `ui.dialog.confirm {dialog, choice?}` answers OK, as the default button would, after setting the `choice` field -/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it. +/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it; +/// a second confirm while that answer waits is refused. /// - `ui.dialog.cancel {dialog}` closes the dialog as Escape would: a standard prompt with a button for its Escape /// answer gives that answer, with its tag; any other dialog closes with its children with Cancel. pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option> { @@ -49,6 +52,26 @@ pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: Some(run(host, ctx, method, params, fields)) } +/// [`dialog_method`] as the [`Reply`] the app hands to [`ControlChannel::settle`](crate::ControlChannel::settle): a +/// `ui.dialog.confirm` that files a dialog's held OK for the app replies once the app answers it +/// ([`Reply::AfterHeldOk`], answered by [`ControlChannel::poll_held`](crate::ControlChannel::poll_held)), so a refusal +/// reaches the caller as the reply's error, in its reason's English text. Every other call replies at once. +pub fn dialog_reply(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option { + // The dialog is named before the call: a confirm that closes it may leave another dialog on top. + let named = dialog_id(host, params).ok(); + // A refusal this confirm replaces still answers the confirms it refused. + let refused = match named.and_then(|id| host.held_state(id)) { + Some(HeldOk::Refused(reason)) => Some(reason.as_str().to_owned()), + _ => None, + }; + let result = dialog_method(host, ctx, method, params)?; + let held = named.filter(|&id| method == "ui.dialog.confirm" && result.is_ok() && host.held_state(id) == Some(HeldOk::Waiting)); + Some(match held.and_then(|id| Some((id, host.open_serial(id)?))) { + Some((dialog, open)) => Reply::AfterHeldOk { dialog, open, refused }, + None => Reply::from_result(result), + }) +} + fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, fields: &[&str]) -> Result { let params = Params(params).only(None, fields)?; let read = Params(¶ms); @@ -67,6 +90,10 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field } }, "ui.dialog.confirm" => { + // A second OK while the first waits files nothing, as the disabled button shows. + if host.held_state(id) == Some(HeldOk::Waiting) { + return Err("the dialog's OK waits for the app's answer to an earlier OK".to_owned()); + } if let Some(choice) = params.get("choice") { host.set_json_field(ctx, id, "choice", choice.clone())?; } diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 259d2f3cb2..8e75f07ecd 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -8,8 +8,11 @@ //! idle for [`IO_TIMEOUT`] is closed. Tokens are 64 hex characters in either case, kept //! lower-cased by the server and compared in constant time with hex letters folded. None of this depends on the transport: the TCP server and a test channel share it. +#[cfg(not(windows))] use std::fs::OpenOptions; -use std::io::{BufRead, Write}; +use std::io::BufRead; +#[cfg(not(windows))] +use std::io::Write; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; @@ -319,30 +322,34 @@ fn read_token_file(path: &Path) -> Result { Ok(token) } -fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { +/// Create the token file `path` holding `token` and a newline. An error keeps the kind of the one +/// that caused it, with the path in its message. +fn create_token_file(path: &Path, token: &str) -> std::io::Result<()> { + let at = |p: &Path, e: std::io::Error| std::io::Error::new(e.kind(), format!("{}: {e}", p.display())); if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { - std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(format!("{}: {e}", parent.display())))?; + std::fs::create_dir_all(parent).map_err(|e| at(parent, e))?; } - let mut options = OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; - // On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token - // is written, and a file that cannot be restricted is removed rather than left for the token to go into later. + // On Windows the file is created with an access list of its user and SYSTEM only, so it never has its folder's + // access list, and the token is written through the handle that created it. #[cfg(windows)] { use craft_platform::owner_only; - if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) { - drop(file); - let _ = std::fs::remove_file(path); - return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display()))); + owner_only::current_user_sid() + .and_then(|me| owner_only::create_private_file(path, &me, format!("{token}\n").as_bytes())) + .map_err(|e| std::io::Error::new(e.kind(), format!("{}: cannot create the control token file for its owner only: {e}", path.display()))) + } + #[cfg(not(windows))] + { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); } + let mut file = options.open(path).map_err(|e| at(path, e))?; + writeln!(file, "{token}").map_err(|e| at(path, e)) } - writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) } /// The server's token, lower-cased. Both given is @@ -355,8 +362,19 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { /// file can be reached by others: ; restrict it to its owner`), and its trimmed content is /// validated. A missing one is created with a generated token (parent directories created, /// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a -/// newline); losing that create race to another process reads the winner's file instead. +/// newline); losing that create race to another process reads the winner's file instead. On +/// Windows a create that does not finish in time fails (`I/O: : cannot create the control +/// token file for its owner only: `), and a file it left at the path is not read as a winner's. pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result { + server_token_with(supplied, token_file, create_token_file) +} + +/// [`server_token`], with `create` making a missing token file. +fn server_token_with( + supplied: Option<&str>, + token_file: Option<&Path>, + create: impl FnOnce(&Path, &str) -> std::io::Result<()>, +) -> Result { if supplied.is_some() && token_file.is_some() { return Err(token_conflict()); } @@ -370,11 +388,11 @@ pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result }; match read_token_file(path) { Ok(existing) => Ok(existing.to_ascii_lowercase()), - Err(AutomationError::Io(_)) if !path.exists() => match create_token_file(path, &token) { + Err(AutomationError::Io(_)) if !path.exists() => match create(path, &token) { Ok(()) => Ok(token), - // Another process won the create-new race. - Err(AutomationError::Io(_)) if path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()), - Err(e) => Err(e), + // Another process won the create-new race. A file left by a create that ran out of time is this one's. + Err(e) if e.kind() != std::io::ErrorKind::TimedOut && path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()), + Err(e) => Err(AutomationError::Io(e.to_string())), }, Err(e) => Err(e), } diff --git a/crates/automation/src/security_tests.rs b/crates/automation/src/security_tests.rs index b5ba980c95..2716fc24c2 100644 --- a/crates/automation/src/security_tests.rs +++ b/crates/automation/src/security_tests.rs @@ -141,6 +141,12 @@ fn server_token_sources_and_validation() { use std::os::unix::fs::PermissionsExt; assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600); } + #[cfg(windows)] + { + use craft_platform::owner_only; + let sddl = owner_only::sddl_of(&file).unwrap(); + assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}"); + } assert_eq!(server_token(None, Some(&file)).unwrap(), created); // An existing file's content is trimmed and lower-cased. @@ -163,3 +169,25 @@ fn server_token_sources_and_validation() { "bridge mode needs --control-token, --control-token-file, PHOTOCRAFT_CONTROL_TOKEN, or PHOTOCRAFT_CONTROL_TOKEN_FILE" ); } + +// A token file create that runs out of time fails with its own error, even when it left a file at +// the path: that file is not read as another process's. A create that another process beat to the +// path reads that process's token. +#[trial] +fn a_token_file_create_that_runs_out_of_time_is_an_error() { + let dir = scratch_dir("token-limit"); + let file = dir.join("token"); + let late = |p: &Path, _: &str| { + std::fs::write(p, "partial").unwrap(); + Err(std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{}: powershell.exe did not finish within 10 s and was ended", p.display()))) + }; + let err = server_token_with(None, Some(&file), late).unwrap_err().to_string(); + assert!(err.starts_with("I/O: ") && err.ends_with("did not finish within 10 s and was ended"), "{err}"); + std::fs::remove_file(&file).unwrap(); + let beaten = |p: &Path, _: &str| { + create_token_file(p, TOKEN).unwrap(); + Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists")) + }; + assert_eq!(server_token_with(None, Some(&file), beaten).unwrap(), TOKEN); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index bea9c8d5a5..31481f4cb1 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -1,5 +1,5 @@ //! Synthetic pointer, keyboard, input-method, file-drop and access-tree input: `ui.click`, `ui.focus`, `ui.move`, -//! `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`. +//! `ui.drag`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`. //! //! This module reads and validates the protocol's parameters; the window host queues the input //! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`], @@ -12,7 +12,8 @@ //! withdraws a step queued for a document or focus that changed before the pass consumed it. //! //! Held input: `hold: true` on `ui.click` leaves its last press down and on `ui.key` its key, until `ui.release`; a -//! `ui.move` while a button is held drags. Each request names the modifiers held during it; a move or wheel leaves +//! `ui.move` while a button is held drags. `ui.drag` is the whole gesture in one request: a press, moves in even steps +//! and the release, queued together, so its reply waits for the release. Each request names the modifiers held during it; a move or wheel leaves //! them held (a hover with modifiers across a screenshot), a click or key that holds nothing lets them go. //! //! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application @@ -22,8 +23,7 @@ //! //! A node of the access tree (`id` or `label`, [`NodeTarget`]) is clicked or focused through the node's own action //! instead of a point: [`crate::access::resolve`] finds it in the window's kept tree when the request arrives, so a -//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. There is no `ui.drag`: a -//! drag is `ui.click {hold}`, `ui.move` and `ui.release`. +//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. use std::path::PathBuf; @@ -43,6 +43,12 @@ pub const MAX_CLICKS: u64 = 256; /// display, yet small enough that egui's pointer delta between two such points stays finite. pub const MAX_SCREEN_POINT: f64 = 1e6; +/// Most moves one `ui.drag` may ask for (`steps`). +pub const MAX_DRAG_STEPS: u64 = 200; + +/// The moves a `ui.drag` makes when its request names no `steps`. +pub const DRAG_STEPS: u64 = 12; + /// The longest hover rest one `ui.move` may ask for (`rest`, seconds). pub const MAX_REST: f64 = 10.0; @@ -302,6 +308,71 @@ impl Move { } } +/// A validated `ui.drag`: a press at one point, moves in even steps to another with the button down, and the release +/// there. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Drag { + /// Where the button goes down. + pub from: At, + /// Where the button comes up. + pub to: At, + /// The button pressed. + pub button: PointerButton, + /// Moves from `from` to `to`; the last one lands on `to`. + pub steps: u64, + /// Modifiers held from the press to the release. + pub mods: Mods, +} + +impl Drag { + /// `{from, to, button?, steps?, modifiers…}`, no other fields. `from` and `to` are each a point object + /// `{x?, y?, coordinates?, page?, control?}` in its own space, as `ui.click` reads its point; a missing one is + /// ``"missing `from`"``, and the errors inside one name it (``"from.x must be a finite number"``). `button` + /// defaults to `left`. `steps` is an unsigned integer from 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`]; + /// outside that range is ``"`steps` must be between 1 and 200 (got {steps})"``. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?; + let p = Params(&p); + let point = |name: &str| -> Result { + let Some(point) = p.0.get(name) else { return Err(format!("missing `{name}`")) }; + let point = Params(point).only(Some(name), &POINT)?; + At::from_params(&Params(&point)).map_err(|error| format!("{name}.{error}")) + }; + let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS); + if !(1..=MAX_DRAG_STEPS).contains(&steps) { + return Err(format!("`steps` must be between 1 and {MAX_DRAG_STEPS} (got {steps})")); + } + Ok(Self { + from: point("from")?, + to: point("to")?, + button: button(&p)?.unwrap_or(PointerButton::Primary), + steps, + mods: p.modifiers(&KEY_MODIFIERS)?, + }) + } + + /// Queues a move to `from` and a press there, `steps` moves in even steps to `to` with the button held, and the + /// release at `to`, in `viewport`; the modifiers are then let go unless other input stays held, as after a click. + /// Both points are placed before anything is queued (a control point against the access tree the host kept for + /// `viewport`), so a point that cannot be placed leaves no press down. When the host withdraws the rest of the + /// gesture after its press ran, the button stays down until `ui.release`, as any held input does. + pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { + let (from, to) = (self.from.place(host, viewport, map)?, self.to.place(host, viewport, map)?); + let steps = u16::try_from(self.steps).unwrap_or(u16::MAX); + host.inject_click(viewport, from, self.button, 1, self.mods, true); + for step in 1..=steps { + let at = if step == steps { to } else { from.lerp(to, f32::from(step) / f32::from(steps)) }; + host.inject_move(viewport, at, self.mods, 0.0); + } + host.inject_release(viewport, Some(to), Released::Button(self.button)); + // A click of no presses at the pointer's place queues no event: it only lets the modifiers go when nothing + // stays held. + host.inject_click(viewport, to, self.button, 0, self.mods, false); + Ok(()) + } +} + /// The most notches one `ui.wheel` turn in lines may ask for, either way. pub const MAX_NOTCHES: f32 = 100.0; @@ -429,6 +500,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V "ui.focus" => Focus::from_params(params).and_then(|focus| focus.inject(host, viewport)), "ui.drop" => drop_files(params, host, viewport, map), "ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)), + "ui.drag" => Drag::from_params(params).and_then(|drag| drag.inject(host, viewport, map)), "ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)), "ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)), "ui.release" => Release::from_params(params).and_then(|release| release.inject(host, viewport, map)), diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs index 7ca7bb5f0c..6cca4325a2 100644 --- a/crates/automation/tests/it/agents.rs +++ b/crates/automation/tests/it/agents.rs @@ -308,6 +308,96 @@ fn a_token_file_that_cannot_be_written_keeps_agents_out() { TcpListener::bind(("127.0.0.1", port)).expect("the port was let go"); } +/// A refused token file is not tried again with the same settings: a retry can't succeed until someone changes the +/// file, and on Windows each check starts `whoami` and PowerShell on the UI thread, about 300 ms, which a retry every +/// few seconds turned into a stall that often (photocraft#17006). Changing the settings tries again. +#[trial] +fn a_refused_token_file_is_not_retried_until_the_settings_change() { + let dir = temp_dir("link-token-no-retry"); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let wanted = free_port(); + assert!(link.sync(Some(&on(u32::from(wanted))), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + + // The file is fixed, but the same settings don't look at it again. + std::fs::remove_dir(dir.path().join(TOKEN_FILE)).unwrap(); + let same = link.sync(Some(&on(u32::from(wanted))), &host); + assert!(same.requests.is_none() && !same.changed, "no retry with the same settings"); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + + let changed = link.sync(Some(&on(0)), &host); + assert!(changed.requests.is_some(), "a settings change tries again"); + assert_eq!(link.status().problem, None); +} + +/// A token file the check refuses as it is (here a damaged token; on Windows also one an older app wrote with its +/// folder's access list, open to Administrators) is the link's own: it is replaced with a new token, so agents can +/// connect instead of staying out until someone deletes the file (photocraft#17006). +#[trial] +fn a_refused_token_file_is_replaced_with_a_new_token() { + let dir = temp_dir("link-token-refresh"); + let file = dir.path().join(TOKEN_FILE); + std::fs::write(&file, "not a token\n").unwrap(); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x"); + assert!(link.sync(Some(&on(0)), &host).requests.is_some(), "{:?}", link.status()); + assert_eq!(link.status().problem, None); + let token = std::fs::read_to_string(&file).unwrap(); + assert_ne!(token.trim(), "not a token"); + assert_eq!(token.trim().len(), 64, "a new token: {token:?}"); + assert_eq!(read_connection(dir.path()).unwrap().expect("published").port, link.status().port.expect("listening")); +} + +/// A retry of a taken port reuses the token its first try checked instead of reading the token file again (on Windows +/// that check is about 300 ms on the UI thread, photocraft#17006); a start that succeeded reads it afresh next time. +#[trial] +fn a_taken_port_retry_reuses_the_checked_token() { + let dir = temp_dir("link-token-reuse"); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = u32::from(taken.local_addr().unwrap().port()); + assert!(link.sync(Some(&on(port)), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status()); + + // Reading the file now fails, so a retry that read it would report a token file problem. + std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap(); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + drop(taken); + let retried = link.sync(Some(&on(port)), &host); + assert!(retried.requests.is_some(), "{:?}", link.status()); + assert_eq!(link.status().problem, None); + + // Once a start succeeded, the next one reads the file again. + let moved = link.sync(Some(&on(0)), &host); + assert!(moved.requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); +} + +/// The checked token is kept only for retries with the same settings: turning agents off and on again reads the token +/// file again, so a server never listens with a token the file no longer holds. +#[trial] +fn a_settings_change_reads_the_token_file_again() { + let dir = temp_dir("link-token-settings"); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = u32::from(taken.local_addr().unwrap().port()); + assert!(link.sync(Some(&on(port)), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status()); + + assert!(!link.sync(None, &host).stopped, "nothing was running"); + // While agents are off the token file changes; here it can't be read at all, which the next start must report. + std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap(); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + drop(taken); + let back = link.sync(Some(&on(port)), &host); + assert!(back.requests.is_none(), "started with the token the file no longer holds"); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); +} + /// Dropping the link stops its server and removes its connection file. #[trial] fn dropping_the_link_removes_its_connection_file() { diff --git a/crates/automation/tests/it/dialogs.rs b/crates/automation/tests/it/dialogs.rs index ad6986f096..b15b926dcd 100644 --- a/crates/automation/tests/it/dialogs.rs +++ b/crates/automation/tests/it/dialogs.rs @@ -1,9 +1,13 @@ //! `ui.dialog.*` on typed dialogs through one generic path. -use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, inspect}; +use std::sync::mpsc::{Receiver, channel}; + +use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse}; +use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, dialog_reply, inspect}; use craft_ui::contract::{Bind, SaveKey}; -use craft_ui::dialog::{DialogHost, DialogResult, PromptChoice, PromptKind, StandardPrompt}; +use craft_ui::dialog::{DialogHost, DialogId, DialogResult, PromptChoice, PromptKind, StandardPrompt}; use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::runtime::env::{Label, Word}; use craft_ui::testing::trial; use egui::Context; use serde_json::{Value, json}; @@ -124,6 +128,91 @@ fn param_dialog_automation_follows_its_rows() { assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom"))); } +const TAKEN: Word = Word::keyed("craft_automation.nameTaken", "A preset with that name exists"); + +/// The open parameter dialog `id` names. +fn held(host: &mut DialogHost, id: DialogId) -> &mut HostedParamDialog { + host.get_dyn_mut(id).and_then(|dialog| dialog.downcast_mut::()).expect("the held dialog is open") +} + +/// A `ui.dialog.confirm` that files a held OK replies with the app's answer: nothing while the app has not answered, +/// an error with the refusal's English text once it refuses, success once it accepts, and an error when the dialog +/// closes first, also when it opened again since. A second confirm while the answer waits is refused, and one after a +/// refusal no poll has read answers the earlier confirm with it. A dialog without a held OK replies at once. +#[trial] +fn a_confirm_of_a_held_ok_replies_with_the_apps_answer() { + let ctx = Context::default(); + let mut host = DialogHost::new(); + let (_requests, rx) = channel(); + let mut control = ControlChannel::new(rx); + let dialog = |ctx: &Context, held: bool| { + let dialog = HostedParamDialog::new(ctx, "blur", DialogFields::new(), |fields| { + ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1}"#)).values(Bind::bound(fields)) + }); + if held { dialog.held_ok() } else { dialog } + }; + let confirm = |host: &mut DialogHost, control: &mut ControlChannel, id: DialogId| -> Receiver { + let (request, reply) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": id.value()})); + let outcome = dialog_reply(host, &ctx, &request.method, &request.params).expect("a ui.dialog method"); + control.settle(request, outcome, None, 0.0); + reply + }; + + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + control.poll_held(&host); + assert!(reply.try_recv().is_err(), "the reply waits for the app's answer"); + assert_eq!(control.waiting(), 1); + let again = confirm(&mut host, &mut control, id); + assert!(again.try_recv().is_ok_and(|reply| reply["ok"] == false), "a second OK while the first waits is refused"); + assert_eq!(control.waiting(), 1); + assert!(held(&mut host, id).take_ok().is_some(), "OK filed the answer for the app"); + held(&mut host, id).answer_ok(Err(Label::from(TAKEN))); + control.poll_held(&host); + assert_eq!(reply.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"}))); + assert_eq!(control.waiting(), 0); + + // A confirm after a refusal no poll has read yet answers the earlier confirm with that refusal. + let first = confirm(&mut host, &mut control, id); + assert!(held(&mut host, id).take_ok().is_some(), "OK files the answer again after a refusal"); + held(&mut host, id).answer_ok(Err(Label::from(TAKEN))); + let reply = confirm(&mut host, &mut control, id); + assert_eq!(first.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"}))); + assert_eq!(control.waiting(), 1); + assert!(held(&mut host, id).take_ok().is_some()); + held(&mut host, id).answer_ok(Ok(())); + control.poll_held(&host); + assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null}))); + assert!(host.confirm_by_id(&ctx, id), "the accepted dialog closes"); + assert!(matches!(host.take_keyed::(), Some((DialogResult::Ok(_), _)))); + + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + assert!(host.cancel_by_id(&ctx, id)); + control.poll_held(&host); + let closed = reply.try_recv().expect("a closed dialog answers the held confirm"); + assert_eq!(closed["ok"], false); + assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}"); + host.take_keyed::(); + + // The same dialog opened again is a new open: its answer is not the closed one's. + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + assert!(host.cancel_by_id(&ctx, id)); + assert_eq!(host.open(dialog(&ctx, true)), id, "a reopened dialog has the same id"); + assert_eq!(control.waiting(), 1); + control.poll_held(&host); + let closed = reply.try_recv().expect("the closed open's confirm is answered"); + assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}"); + assert!(host.cancel_by_id(&ctx, id)); + host.take_keyed::(); + + let id = host.open(dialog(&ctx, false)); + let reply = confirm(&mut host, &mut control, id); + assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null})), "a dialog without a held OK replies at once"); + assert_eq!(control.waiting(), 0); +} + /// A `fields` list sets every field or none: a refused field in the middle leaves the dialog as it was and gives that /// refusal; a list over the limit, an item without a string `field` and `field` beside `fields` are refused unread. #[trial] diff --git a/crates/automation/tests/it/screenshot.rs b/crates/automation/tests/it/screenshot.rs index e9f06c409e..28a0ac8f35 100644 --- a/crates/automation/tests/it/screenshot.rs +++ b/crates/automation/tests/it/screenshot.rs @@ -248,6 +248,34 @@ fn a_request_past_its_deadline_times_out() { } } +/// A screenshot settled at a given time counts its settle delay and its deadline from that time, on the clock the app +/// also passes to `issue` and `drain`, not from the wall clock. +#[trial] +fn a_screenshot_settled_at_a_time_counts_from_that_time() { + use craft_automation::control::{ControlChannel, ControlRequest, Reply}; + use craft_automation::screenshot::ScreenshotParams; + use serde_json::json; + + let ctx = Context::default(); + // An app clock ahead of the wall clock. + let arrived = motion::now() + Duration::from_secs(60); + let (_transport, requests) = channel(); + let mut control = ControlChannel::new(requests); + control.captures.note_geometry(ViewportId::ROOT, geometry(800.0, 600.0)); + let (request, rx) = ControlRequest::new("ui.screenshot", json!({})); + let params = ScreenshotParams::from_params(&json!({})).expect("no params"); + control.settle_at(request, Reply::screenshot(1, params, ViewportId::ROOT), None, 500.0, arrived); + assert!(rx.try_recv().is_err(), "the reply waits for the capture"); + + let (finished, callbacks) = settle_and_issue(&mut control.captures, &ctx, arrived + Duration::from_millis(400), None); + assert!(finished.is_empty(), "inside its deadline: {:?}", finished.iter().map(error).collect::>()); + assert!(callbacks.is_empty(), "not issued inside its settle delay"); + assert!(control.captures.drain(arrived + DEADLINE - Duration::from_millis(1), None).is_empty(), "inside its deadline"); + let finished = control.captures.drain(arrived + DEADLINE, None); + assert_eq!(finished.len(), 1); + assert!(error(&finished[0]).contains("timed out"), "{}", error(&finished[0])); +} + /// Cancelling releases the budget at once; an image that arrives afterwards is dropped. #[trial] fn cancellation_releases_the_budget_and_drops_a_late_image() { diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index ee2c484f6c..dc3ca5efb6 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -1,12 +1,12 @@ -//! Synthetic input through the window host: held presses and keys, modifiers, the wheel, Caps Lock, hover rest, +//! Synthetic input through the window host: held presses and keys, drags, modifiers, the wheel, Caps Lock, hover rest, //! document coordinates and input-method compositions, as the passes see them, and the params refused before //! anything is queued. use std::cell::{Cell, RefCell}; use std::rc::Rc; -use craft_automation::access::NO_TREE; -use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; +use craft_automation::access::{NO_CONTROL, NO_TREE}; +use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_DRAG_STEPS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; @@ -123,6 +123,52 @@ fn a_held_press_stays_down_until_its_release() { assert!(!rig.now().primary_down, "a click without hold releases"); } +/// `ui.drag` presses at `from`, moves to `to` in `steps` even steps with the button down, releases at `to` with its +/// modifiers held throughout, then lets them go. Each point is in its own space: `to` here is a document point. +#[trial] +fn a_drag_presses_moves_in_steps_and_releases_at_its_end() { + let mut rig = Rig::new(); + rig.fx.settle(); + rig.take(); + let to = map(0, pos2(220.0, 40.0)).expect("the test map places every point"); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 20}, "to": {"x": 220, "y": 40, "coordinates": "document"}, "steps": 4, "shift": true})); + let after = rig.now(); + let events: Vec = rig.take().into_iter().flat_map(|pass| pass.events).collect(); + let buttons: Vec<(Pos2, bool, bool)> = events + .iter() + .filter_map(|event| match event { + Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } => Some((*pos, *pressed, modifiers.shift)), + _ => None, + }) + .collect(); + assert_eq!(buttons, vec![(pos2(10.0, 20.0), true, true), (to, false, true)], "one press at `from`, one release at `to`, both with Shift"); + let held = events.iter().skip_while(|event| !matches!(event, Event::PointerButton { pressed: true, .. })); + let moves: Vec = held + .take_while(|event| !matches!(event, Event::PointerButton { pressed: false, .. })) + .filter_map(|event| match event { + Event::PointerMoved(at) => Some(*at), + _ => None, + }) + .collect(); + assert_eq!(moves.len(), 4, "one move per step while the button is down: {moves:?}"); + assert!(moves.windows(2).all(|pair| pair[1].x > pair[0].x), "each step goes further towards `to`: {moves:?}"); + assert_eq!(moves.last(), Some(&to), "the last step lands on `to`"); + assert!(!after.primary_down && !after.shift, "the drag leaves no button or modifier held"); +} + +/// A drag keeps its modifiers held after its release while other input stays down, as a click does. +#[trial] +fn a_drag_keeps_its_modifiers_while_a_held_key_stays_down() { + let mut rig = Rig::new(); + rig.send("ui.key", json!({"key": "Space", "hold": true})); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 60, "y": 10}, "steps": 2, "shift": true})); + let after = rig.now(); + assert!(after.space_down && !after.primary_down, "the key stays down and the drag's button is up"); + assert!(after.shift, "the modifiers stay with the held key"); + rig.send("ui.release", json!({})); + assert!(!rig.now().space_down && !rig.now().shift, "the release lets everything go"); +} + /// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go. #[trial] fn a_move_keeps_its_modifiers_and_a_click_lets_them_go() { @@ -292,6 +338,25 @@ fn document_points_need_a_canvas() { assert_eq!(screen, Some(Ok(()))); } +/// A drag whose end cannot be placed is refused whole: its press at a screen point is not queued either. That holds +/// for a document end without a canvas and for a control end that names no control of the window. +#[trial] +fn a_drag_with_an_end_it_cannot_place_queues_no_press() { + let mut rig = Rig::new(); + rig.fx.settle(); + let (host, ctx) = (rig.host(), rig.fx.ctx().clone()); + let none = |_: usize, _: Pos2| None; + let params = json!({"from": {"x": 1, "y": 1}, "to": {"x": 5, "y": 5, "coordinates": "document"}}); + assert_eq!(input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &none), Some(Err(NO_DOCUMENT.to_owned()))); + assert!(host.injected_idle()); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused drag queued nothing"); + let params = json!({"from": {"x": 1, "y": 1}, "to": {"control": {"name": "Save"}, "x": 4}}); + let answer = input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &map); + assert!(matches!(&answer, Some(Err(error)) if error.starts_with(NO_CONTROL)), "{answer:?}"); + assert!(host.injected_idle()); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the drag to an unplaced control queued nothing"); +} + /// A step handed to the input whose pass has not run is withdrawn when the focus moved, and when the application /// withdraws the input because its document changed: the integration's preserved copy leaves the input, no key /// stays down, and the waiters fail with `TARGET_CHANGED`. @@ -358,6 +423,14 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.move", json!({"x": 10, "y": 10, "rest": "long"})), ("ui.move", json!({"x": 10, "y": 10, "coordinates": "page"})), ("ui.move", json!({"x": 10, "y": -far})), + ("ui.drag", json!({"from": {"x": 10}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20, "nudge": 1}})), + ("ui.drag", json!({"from": {"x": 10}, "to": [20, 20]})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": far}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": 0})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": MAX_DRAG_STEPS + 1})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "x": 5})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"control": {"name": "Save"}, "coordinates": "document"}})), ("ui.key", json!({"key": "A", "hold": true, "nudge": 1})), ("ui.key", json!({"key": 5})), ("ui.key", json!({"key": "NoSuchKey", "hold": true})), diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index 14a752fe9e..298e6419aa 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -41,8 +41,8 @@ pub struct Workspace

{ /// goes back. #[serde(default)] hidden: Vec<(P, Location

)>, - /// Floating panels with the docked location each one left, so Dock Panel can return it. Saved with the - /// workspace. + /// Floating panels with the docked location each one left, so Dock Panel can return it; a closed panel that + /// floats records the place it would reopen at. Saved with the workspace. #[serde(default, skip_serializing_if = "Vec::is_empty")] floated: Vec<(P, Location

)>, /// Counts the replacements of this live workspace. Not saved, and not part of equality. @@ -264,6 +264,16 @@ impl Workspace

{ Action::Open { panel, .. } if proposed.hidden.iter().any(|(p, _)| p == panel) => proposed.reopen(panel, &policy)?, _ => false, }; + // Floating a hidden panel records the docked place it would reopen at, without reopening it there. A panel + // that would reopen in a floating window has no docked place. + let hidden_place = match &action { + Action::Float { panel, .. } if !proposed.layout.contains(panel) && proposed.hidden.iter().any(|(p, _)| p == panel) => proposed + .restored(panel, &policy) + .filter(|restored| !floats(&restored.layout, panel)) + .and_then(|restored| restored.layout.location(panel).ok()) + .map(|location| (panel.clone(), location)), + _ => None, + }; if !reopened { // SetNative records where the window system has a floating window, so a lock // does not refuse it. @@ -278,6 +288,12 @@ impl Workspace

{ proposed.hidden.push((panel, location)); } proposed.track_floated(&before); + if let Some((panel, location)) = hidden_place + && floats(&proposed.layout, &panel) + && !proposed.floated.iter().any(|(p, _)| p == &panel) + { + proposed.floated.push((panel, location)); + } all_closed.extend(closed); } let visible: HashSet

= proposed.layout.panels().into_iter().cloned().collect(); diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 4814a0078d..4b8355d7cf 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -1,6 +1,7 @@ //! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and //! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens -//! items that have a short form, then drops command items and titles from the end. All of them read no egui types. +//! items that have a short form, in the order their host ranks, and drops command items and titles from the end. +//! All of them read no egui types. /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] @@ -230,19 +231,39 @@ pub struct FitItem { pub keep: FitKeep, /// The extent of the item's shorter form, if it has one. pub short: Option, + /// The rank of the item's short form: lower ranks shorten first, and equal ranks shorten the last item first. + pub short_order: u16, + /// Whether the item keeps its full form until no more free items can leave. + pub short_late: bool, } impl FitItem { /// An item `extent` long in `section`. pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self { - FitItem { extent, section, keep, short: None } + FitItem { extent, section, keep, short: None, short_order: 0, short_late: false } } - /// The item with a shorter form `extent` long, which it takes before any free item leaves. + /// The item with a shorter form `extent` long, which it takes before any free item leaves unless it is late. + /// An item marked [`FitItem::short_late`] takes that form only after no free item is left to leave. pub const fn short(mut self, extent: f32) -> Self { self.short = Some(extent); self } + + /// The item with its short form ranked `order`: lower ranks shorten first, and the last item of a rank first. + /// Every item ranks 0 by default. + pub const fn short_order(mut self, order: u16) -> Self { + self.short_order = order; + self + } + + /// The item takes its short form only after every free item that can leave has left. + /// The other items go to the overflow menu before this one shortens. A free item with a late short form leaves + /// in its turn instead. + pub const fn short_late(mut self) -> Self { + self.short_late = true; + self + } } /// Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order. @@ -277,11 +298,13 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) } /// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. -/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last -/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then -/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long, -/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are -/// never listed as short. Negative and non-finite lengths count as zero. +/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, lowest +/// [`FitItem::short_order`] first and the last item of a rank first, until the run fits (listed in [`Fit::short`]); a +/// `Pinned` item shortens as a `Free` one does. Only then does the last `Free` item leave, one at a time, until the +/// rest and an overflow control `overflow_extent` long, set off by `gap`, fit. When no `Free` item is left to go, the +/// items marked [`FitItem::short_late`] take their short forms in the same order; items that left do not come back. +/// `Pinned` items stay even when they alone are longer than `available`. Items that leave are never listed as short. +/// Negative and non-finite lengths count as zero. pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit { let (available, gap, section_gap, overflow_extent) = (item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent)); @@ -302,19 +325,27 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, // The shadow run holds each item at the extent it takes: shortened items at their `short` extent. let mut run: Vec = items.to_vec(); let mut short = vec![false; items.len()]; - while !fits(&run, &shown) { - let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else { - break; - }; - short[last] = true; - if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) { - item.extent = extent; + // Takes the short forms of the shown items with this `late` mark, lowest rank first and the last item of a rank + // first (`min_by_key` keeps the first minimum, which is the last index in a reversed scan), until the run fits. + let shorten = |late: bool, run: &mut [FitItem], short: &mut [bool], shown: &[bool]| { + while !fits(run, shown) { + let next = (0..items.len()) + .rev() + .filter(|&at| shown[at] && !short[at] && items[at].short.is_some() && items[at].short_late == late) + .min_by_key(|&at| items[at].short_order); + let Some(next) = next else { break }; + short[next] = true; + if let (Some(item), Some(extent)) = (run.get_mut(next), items[next].short) { + item.extent = extent; + } } - } + }; + shorten(false, &mut run, &mut short, &shown); while !fits(&run, &shown) { let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break }; shown[last] = false; } + shorten(true, &mut run, &mut short, &shown); let (kept, left): (Vec, Vec) = (0..items.len()).partition(|&at| shown[at]); let short = kept.iter().copied().filter(|&at| short[at]).collect(); Fit { shown: kept, overflow: left, short } diff --git a/crates/behavior/src/grid.rs b/crates/behavior/src/grid.rs index bd782a0e9c..103a97fcf0 100644 --- a/crates/behavior/src/grid.rs +++ b/crates/behavior/src/grid.rs @@ -85,15 +85,12 @@ pub struct GridCursor { impl GridCursor { /// A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A /// column is never narrower than its least in `last`: a `Content` column starts there, and a `Fill` column's share - /// does not go below it. + /// does not go below it. A `Fill` column raised to its least takes the difference from the other `Fill` columns. pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self { let least = |i: usize| last.least.get(i).copied().unwrap_or(0.0); let content: Vec = (0..columns.len()).map(|i| last.columns.get(i).copied().unwrap_or(0.0).max(least(i))).collect(); - let widths = resolve_columns(columns, &content, flow.rect().width(), gap.x) - .into_iter() - .enumerate() - .map(|(i, width)| if matches!(columns[i], ColumnWidth::Fill { .. }) { width.max(least(i)) } else { width }) - .collect(); + let mut widths = resolve_columns(columns, &content, flow.rect().width(), gap.x); + keep_fill_least(columns, &mut widths, least); let fills = columns.iter().map(|kind| matches!(kind, ColumnWidth::Fill { .. })).collect(); GridCursor { flow, @@ -266,6 +263,44 @@ impl GridCursor { } } +/// Shares the room the `Fill` columns of `widths` hold among them again so that none is narrower than its `least`: a +/// column whose share by weight is below its least takes its least, and the columns left share the rest by weight. +/// The fill columns together take more than their room only when their least widths do not fit in it. +fn keep_fill_least(columns: &[ColumnWidth], widths: &mut [f32], least: impl Fn(usize) -> f32) { + let fills: Vec<(usize, f32)> = columns + .iter() + .enumerate() + .filter_map(|(i, column)| if let ColumnWidth::Fill { weight } = column { Some((i, *weight)) } else { None }) + .collect(); + let room: f32 = fills.iter().map(|(i, _)| widths[*i]).sum(); + if !room.is_finite() { + // Room with no bound leaves every share above its least. + for (i, _) in &fills { + widths[*i] = widths[*i].max(least(*i)); + } + return; + } + let mut raised = vec![false; columns.len()]; + loop { + let left = room - fills.iter().filter(|(i, _)| raised[*i]).map(|(i, _)| least(*i)).sum::(); + let weights: f32 = fills.iter().filter(|(i, _)| !raised[*i]).map(|(_, weight)| weight).sum(); + let share = |weight: f32| if weights > 0.0 { left.max(0.0) * weight / weights } else { 0.0 }; + let mut more = false; + for (i, weight) in &fills { + if !raised[*i] && share(*weight) < least(*i) { + raised[*i] = true; + more = true; + } + } + if !more { + for (i, weight) in &fills { + widths[*i] = if raised[*i] { least(*i) } else { share(*weight).max(least(*i)) }; + } + return; + } + } +} + /// `columns` with each `Fill` column as a `Content` column. fn as_content(columns: &[ColumnWidth]) -> Vec { columns.iter().map(|kind| if matches!(kind, ColumnWidth::Fill { .. }) { ColumnWidth::Content } else { *kind }).collect() @@ -288,4 +323,43 @@ mod tests { cursor.cell(Vec2::new(150.0, 100.0)); assert_eq!(cursor.room(), Vec2::new(200.0, 100.0), "the content cell may take what the fill column holds"); } + + /// The widths of one row of `columns` placed by `last`, read from the cells. + fn row_widths(columns: &[ColumnWidth], last: &GridMeasure) -> Vec { + let mut cursor = GridCursor::new(flow(false), columns, Vec2::ZERO, last); + columns.iter().map(|_| cursor.cell(Vec2::new(10.0, 10.0)).width()).collect() + } + + #[test] + fn a_fill_column_raised_to_its_least_takes_the_difference_from_the_other_fill_columns() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(2.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let fitting = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]); + let shares = row_widths(&columns, &fitting); + let raised = row_widths(&columns, &fitting.clone().with_least(vec![120.0, 0.0, 0.0, 0.0])); + assert!(shares[0] < 120.0, "the first column's share is below its least"); + assert!(raised[0] >= 120.0, "the first column keeps its least"); + assert!(raised[1] < shares[1] && raised[2] < shares[2], "the other fill columns narrow"); + assert_eq!(raised[1], 2.0 * raised[2], "the other fill columns keep their weights"); + assert_eq!(raised[3], shares[3], "the content column keeps its width"); + assert_eq!(raised.iter().sum::(), 300.0, "the row fills the grid and no more"); + } + + #[test] + fn fill_columns_whose_least_widths_do_not_fit_take_their_least_widths() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]).with_least(vec![200.0, 70.0, 0.0, 0.0]); + let widths = row_widths(&columns, &last); + assert!(widths[0] >= 200.0 && widths[1] >= 70.0, "each fill column keeps its least"); + assert_eq!(widths[2], 0.0, "the fill column with no least gives up its room"); + assert_eq!(widths.iter().sum::(), 330.0, "the row is as wide as the least widths and no wider"); + } + + #[test] + fn fill_columns_whose_shares_cover_their_least_widths_keep_their_shares() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]); + let shares = row_widths(&columns, &last); + let kept = row_widths(&columns, &last.clone().with_least(vec![50.0, 50.0, 50.0, 0.0])); + assert_eq!(kept, shares); + } } diff --git a/crates/behavior/src/quantity.rs b/crates/behavior/src/quantity.rs index 0aae495027..495b781c6d 100644 --- a/crates/behavior/src/quantity.rs +++ b/crates/behavior/src/quantity.rs @@ -18,9 +18,10 @@ fn is_unit_char(c: char) -> bool { } /// Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can -/// tell it from a number or an operator. +/// tell it from a number or an operator, or one `/` followed by them (`/in`, a count per inch). pub fn is_unit_spelling(spelling: &str) -> bool { - !spelling.is_empty() && spelling.chars().all(is_unit_char) + let letters = spelling.strip_prefix('/').unwrap_or(spelling); + !letters.is_empty() && letters.chars().all(is_unit_char) } /// A unit spelling and the factor that turns its quantity into the base unit. @@ -41,7 +42,9 @@ struct Unit { /// (`3cm*50%` is 1.5 cm), whatever `%` means elsewhere. Text that starts with `+`, `*` or `/` is relative: it /// applies to the start value (`+5` adds 5, `*2` doubles). A leading `-` is a negative number. A unit is the longest /// registered spelling at the start of the letters after a number, so `2inx3` is `2in` times 3 and `2px` stays a -/// quantity when `px` is registered. A group separator counts only before exactly three digits. +/// quantity when `px` is registered. A registered spelling that starts with `/` (`/in`) is a unit when the letters after +/// the `/` start it, so `40/in` is 40 of it; any other `/` divides (`80/2`). A group separator counts only before +/// exactly three digits. #[derive(Clone, Debug, PartialEq)] pub struct Reader { decimal: char, @@ -213,8 +216,9 @@ impl Parse<'_> { } } - /// A number and the longest registered unit spelling at the start of the letters after it. Letters that start no - /// unit stay unread: a product sign (`2x3`) takes them, and anything else leaves the text unread, which refuses it. + /// A number and the longest registered unit spelling at the start of the letters after it, or after a `/` when a + /// registered spelling starts with `/`. Letters that start no unit stay unread: a product sign (`2x3`) takes them, + /// and anything else leaves the text unread, which refuses it. A `/` that starts no unit is left to divide. fn quantity(&mut self, scaled: bool) -> Result { let number = self.number()?; self.tag = None; @@ -223,8 +227,11 @@ impl Parse<'_> { return Ok(number / 100.0); } let reader = self.reader; - let run: Vec = self.chars[self.at..].iter().copied().take_while(|c| is_unit_char(*c)).collect(); - let unit = (1..=run.len()).rev().find_map(|len| { + let after = &self.chars[self.at..]; + let slash = usize::from(after.first() == Some(&'/')); + let letters = after[slash..].iter().take_while(|c| is_unit_char(**c)).count(); + let run = &after[..slash + letters]; + let unit = (1 + slash..=run.len()).rev().find_map(|len| { let lowered = run[..len].iter().collect::().to_lowercase(); reader.units.iter().find(|unit| unit.spelling == lowered).map(|unit| (len, unit)) }); @@ -326,6 +333,20 @@ mod tests { near(&percent, "2%", 14.0); assert_eq!(percent.read("*50%", Some(4.0)), Ok(2.0), "a relative share"); + let per_inch = Reader::new().unit_tagged("/in", 1.0, 0); + assert!(is_unit_spelling("/in") && !is_unit_spelling("/") && !is_unit_spelling("in/") && !is_unit_spelling("//in")); + for text in ["40/in", "40 /in", "40/IN", "80/2", "80/2/in"] { + near(&per_inch, text, 40.0); + } + assert_eq!(per_inch.read_tagged("40/in", None), Ok((40.0, Some(0))), "the spelling names its unit"); + assert_eq!(per_inch.read("*2", Some(20.0)), Ok(40.0), "a relative product"); + assert_eq!(per_inch.read("/2", Some(80.0)), Ok(40.0), "a leading / still divides the start value"); + for bad in ["", "/in", "40/inch", "40/"] { + assert_eq!(per_inch.read(bad, Some(1.0)), Err(NotAValue), "{bad:?} is not a value"); + } + near(&lengths, "144/2in", 1.0); + assert_eq!(lengths.read("144/in", None), Err(NotAValue), "without a /in spelling, /in is a division with no number"); + let german = Reader::new().decimal(',').group('.'); near(&german, "1.234,5", 1234.5); near(&german, "1.234.567", 1_234_567.0); diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index 1d25354fdc..b6eea87da1 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -241,6 +241,35 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { assert!(workspace.floated().is_empty(), "closing drops the record"); } +/// A closed panel that floats by itself records the place it would reopen at, as opening it first records, and its old +/// group keeps its front tab; docking it then returns it to that group at its old index. +#[test] +fn a_closed_panel_that_floats_keeps_its_docked_place_and_its_old_group_keeps_its_front_tab() { + let float = Action::float(2, rect(10.0, 10.0, 200.0, 200.0)); + let mut opened = Workspace::new(docked()); + opened.apply(Action::close(2), false, allow).unwrap(); + opened.apply_all([Action::open(2, None), float.clone()], false, allow).unwrap(); + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(2), false, allow).unwrap(); + workspace.apply(float, false, allow).unwrap(); + let layout = workspace.layout(); + assert!(matches!(layout.place(&2), Some(PanelPlace::Floating { .. }))); + assert_eq!(group_members(layout, 3), [3]); + assert_eq!(front(layout, 3), 3, "the old group keeps its front tab"); + assert_eq!(workspace.floated(), opened.floated(), "the record matches the one opening it first gives"); + + let [(_, location)] = workspace.floated() else { panic!("one record: {:?}", workspace.floated()) }; + let back = Action::move_beside(2, location.anchor.unwrap(), location.placement.clone()); + workspace.apply(back, false, allow).unwrap(); + assert_eq!(end_dock(workspace.layout())[0].groups[0].panels, [2, 3], "Dock Panel returns it to its old index"); + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(6), false, allow).unwrap(); + workspace.apply(Action::float(6, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); + assert!(workspace.floated().is_empty(), "a panel closed from a floating window has no docked place"); +} + /// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6]. fn columns() -> Layout { let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]); diff --git a/crates/behavior/tests/fit.rs b/crates/behavior/tests/fit.rs index 08cd377125..d1110a4a8a 100644 --- a/crates/behavior/tests/fit.rs +++ b/crates/behavior/tests/fit.rs @@ -64,6 +64,37 @@ fn short_items_shorten_from_the_end_before_any_item_leaves() { assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}"); } +/// Guards the host's order of short forms: a lower `short_order` shortens first wherever its item sits, and a +/// `short_late` item keeps its full form until every free item has gone to the menu, then shortens in rank order. +#[test] +fn short_forms_follow_their_rank_and_late_ones_wait_for_the_free_items() { + let item = |extent| FitItem::new(extent, 0, FitKeep::Free); + let ranked = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0).short_order(1)]; + let fit = fit_items(&ranked, 120.0, 0.0, 0.0, 10.0); + assert_eq!(fit.short, [0], "the lower rank shortens before the later item: {fit:?}"); + assert!(fit.overflow.is_empty(), "{fit:?}"); + + // Two free items in one section, then two pinned ones that shorten only late, the first ranked before the second. + let pinned = |extent| FitItem::new(extent, 1, FitKeep::Pinned).short(20.0).short_late(); + let bar = [item(40.0), item(40.0), pinned(60.0), pinned(60.0).short_order(1)]; + let at = |available| fit_items(&bar, available, 0.0, 0.0, 10.0); + + let roomy = at(180.0); + assert_eq!(roomy.overflow, [1], "a free item leaves before any late item shortens: {roomy:?}"); + assert!(roomy.short.is_empty(), "{roomy:?}"); + + let tight = at(130.0); + assert_eq!(tight.overflow, [0, 1], "every free item leaves first: {tight:?}"); + assert!(tight.short.is_empty(), "{tight:?}"); + + let narrow = at(100.0); + assert_eq!(narrow.short, [2], "then the lower-ranked late item shortens: {narrow:?}"); + assert_eq!(narrow.overflow, [0, 1], "items that left stay in the menu: {narrow:?}"); + + let narrowest = at(50.0); + assert_eq!(narrowest.short, [2, 3], "then the next rank: {narrowest:?}"); +} + #[test] fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() { let natural = [80.0, 90.0, 85.0, 95.0, 70.0]; diff --git a/crates/color-ui/src/ui/harmony.rs b/crates/color-ui/src/ui/harmony.rs index a153276ada..254d30f628 100644 --- a/crates/color-ui/src/ui/harmony.rs +++ b/crates/color-ui/src/ui/harmony.rs @@ -522,7 +522,7 @@ impl<'a> HarmonyPanel<'a> { Variation::WarmCool => (&words.cool, &words.warm), Variation::VividMuted => (&words.muted, &words.vivid), }; - Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| { + Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| { Text::new(left.clone()).show(ui); Text::new(right.clone()).show(ui); }); diff --git a/crates/color-ui/src/ui/paint_chip.rs b/crates/color-ui/src/ui/paint_chip.rs index 28de7cc7b1..64213ce9a8 100644 --- a/crates/color-ui/src/ui/paint_chip.rs +++ b/crates/color-ui/src/ui/paint_chip.rs @@ -15,7 +15,7 @@ use craft_cms::convert::CmykConverter; use craft_keymap::Mods; use craft_theme::Srgba; use craft_ui::buttons::{Button, PopupMark}; -use craft_ui::choice::{ChoiceWords, RING_SHARE, Segmented, Swatch, SwatchStyle, paint_ring}; +use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchStyle, paint_ring, ring_band}; use craft_ui::contract::{ Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Meta as _, Outcome, Overlay, OverlayUi, Overlays as _, Pages, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, @@ -372,7 +372,7 @@ pub(crate) fn paint_well(ui: &mut PaintUi<'_>, cx: &Cx<'_, impl craft_ui::contra if style.ring { let ground = ui.with_style(cx.resolved.variant, |scope| SurfaceStyle { edge: SurfaceEdge::None, shadow: None, ..scope.surface(cx.env.surface()) }); - ui.draw().surface_styled(well.shrink(well.width() * RING_SHARE), &ground); + ui.draw().surface_styled(well.shrink(ring_band(well)), &ground); } else { ui.draw().stroke(&shape, StrokeWidth::Thin, style.edge); } diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 90c92271b2..d79e86cf93 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -448,7 +448,7 @@ pub struct ColorPanel<'a> { wells: Option<([PairWell; 2], Bind<'a, Well>)>, edited: Option>, shown: Option, - recent: &'a [Srgba], + recent: Option<&'a [Srgba]>, recent_setup: Option, gamut: Option>, } @@ -471,7 +471,7 @@ struct Inputs<'a> { wells: Option<&'a [PairWell; 2]>, edited: Option<&'a Option>, shown: &'a ColorPanelShown, - recent: &'a [Srgba], + recent: Option<&'a [Srgba]>, recent_setup: Option<&'a RecentSetup>, } @@ -488,7 +488,7 @@ impl<'a> ColorPanel<'a> { wells: None, edited: None, shown: None, - recent: &[], + recent: None, recent_setup: None, gamut: None, } @@ -541,9 +541,10 @@ impl<'a> ColorPanel<'a> { self } - /// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. + /// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. The FillStroke layout shows the captioned row + /// for a host that gives them, an empty list included; without them it shows no row. pub fn recent(mut self, colors: &'a [Srgba]) -> Self { - self.recent = colors; + self.recent = Some(colors); self } diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index a3ff66c160..183844b574 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -6,10 +6,11 @@ use craft_behavior::{EditEvent, Mixed}; use craft_theme::Srgba; use craft_ui::choice::{Swatch, SwatchSpacing}; use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; -use craft_ui::display::Text; +use craft_ui::display::{Shade, Text}; use craft_ui::form::{Field, FieldGroup}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::runtime::env::Label; +use craft_ui::style::TypeRole; use craft_ui::text::{HexField, TextField}; use egui::Ui; @@ -131,8 +132,8 @@ impl Body<'_> { } } - /// The Spectrum ramp (grey in Grayscale) with a tooltip naming the shown mode. A Cmd or Ctrl click recolours and - /// picks nothing; a Shift click moves to the next mode. + /// The Spectrum ramp (gray in Grayscale) with a tooltip naming the shown mode, at least as tall as its square end + /// boxes. A Cmd or Ctrl click recolors and picks nothing; a Shift click moves to the next mode. fn spectrum(&mut self, ui: &mut Ui) { let mode = self.shown_mode(); let kind = if mode == ColorPanelMode::GrayscaleSlider { RampKind::Grayscale } else { RampKind::Spectrum }; @@ -145,6 +146,7 @@ impl Body<'_> { .gamut(gamut) .gamut_revision(revision) .web_safe(self.now.web_safe_ramp) + .square_boxes(true) .sizing(Sizing::Fill) .show(ui); self.ramp_events(ramp.edit.events); @@ -154,14 +156,19 @@ impl Body<'_> { } } - /// The Recent Colors as a spaced palette; a pick sets the colour. + /// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list + /// is empty, where the first applied color will go. // PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and // `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip). fn recent(&mut self, ui: &mut Ui) { - if self.inputs.recent.is_empty() { + let Some(recent) = self.inputs.recent else { + return; + }; + Text::new(self.words.recent_colors.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui); + if recent.is_empty() { return; } - let swatches: Vec<(Label, Srgba)> = self.inputs.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); + let swatches: Vec<(Label, Srgba)> = recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); let mut current = self.color(); let mut palette = SwatchPalette::new(self.words.recent_colors.clone(), Bind::bound(&mut current), &swatches).spacing(SwatchSpacing::Spaced); if let Some(setup) = self.inputs.recent_setup { diff --git a/crates/color-ui/src/ui/ramp.rs b/crates/color-ui/src/ui/ramp.rs index 2a01579348..e541695543 100644 --- a/crates/color-ui/src/ui/ramp.rs +++ b/crates/color-ui/src/ui/ramp.rs @@ -6,8 +6,8 @@ use craft_cms::convert::CmykConverter; use craft_theme::{Hsb, Srgba}; use craft_ui::canvas::context_click; use craft_ui::contract::{ - Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, Name, Outcome, PaintUi, PartsCx, - Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, + Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi, + PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, }; use craft_ui::primitives::{Marker, PaintShape, StrokeWidth}; use craft_ui::runtime::commands::FireSource; @@ -240,6 +240,11 @@ pub struct ColorRamp<'a> { /// Whether the white and black boxes follow the bar; on by default. #[prop] boxes: bool, + /// Whether the ramp is at least as tall as its two end boxes stacked, each as tall as it is wide, in place of a + /// color band; off by default. A ramp that takes the room under other rows keeps this height in a host sized by + /// its content and in a short one. + #[prop] + square_boxes: bool, /// The ramp's kind as the host names it ("RGB Spectrum"), the bar's accessible value. #[prop(into)] kind_name: Option

{ }, /// Auto-Collapse Iconic Panels was chosen in a column menu. The host flips its preference and passes it back. ToggleAutoCollapse, - /// The area opened, switched or closed its flyout: an icon click, Escape, a press outside, or the focus - /// leaving it under Auto-Collapse. A host that binds the flyout takes it as the request when its binding is given. + /// The area opened, switched or closed its flyout: an icon click, Escape, or a press outside or the focus leaving + /// it under Auto-Collapse. A host that binds the flyout takes it as the request when its binding is given. FlyoutChanged { /// The panel now in the flyout; `None` when it closed. panel: Option

, diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index 7377e39240..68b78461b2 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -326,8 +326,9 @@ pub struct FloatingGroup<'a> { files_at: Option, } -/// Starts the window-unit drag: a move by the title row when the flag is set, else a drag the window took over. -type StartDrag<'a> = Box FnOnce(&'b mut Cx<'c, FloatingGroup<'a>>, bool) + 'a>; +/// Starts the window-unit drag of a window of the given size: a move by the title row when the flag is set, else a +/// drag the window took over. +type StartDrag<'a> = Box FnOnce(&'b mut Cx<'c, FloatingGroup<'a>>, bool, Vec2) + 'a>; type TakeDrop<'a> = Box FnMut(&'b mut Cx<'c, FloatingGroup<'a>>) + 'a>; @@ -387,8 +388,7 @@ impl<'a> FloatingGroup<'a> { #[must_use] pub fn window_of(mut self, anchor: P) -> Self { let active = PanelKey::of(&anchor); - let size = self.rect.size(); - self.start_drag = Some(Box::new(move |cx, title_row| start_window_drag(cx, anchor, active, size, title_row))); + self.start_drag = Some(Box::new(move |cx, title_row, size| start_window_drag(cx, anchor, active, size, title_row))); self } @@ -451,8 +451,8 @@ impl<'a> FloatingGroup<'a> { /// A minimized group, and one with `Sizing::Content`, is placed by its position and width; its height is its /// content's, which is the chrome alone while minimized. fn mount(&self) -> Mount { - // The frame's limits are the body's with the chrome on top. - let frame = self.limits.around(Vec2::new(0.0, self.chrome)); + let frame = self.frame_limits(); + let rect = self.within_limits(); // A collapsed column's width stays within its own bounds, a minimized one's within the panels' limits. let widths = self.column.map(|column| match column.collapsed { Some(_) => column.widths, @@ -475,7 +475,7 @@ impl<'a> FloatingGroup<'a> { let width = self.rect.width().max(frame.min.x).min(frame.max.map_or(f32::INFINITY, |max| max.x)); overlay.placed_at(self.rect.min).size_limits(SizeLimits { min: Vec2::new(width, frame.min.y), max: frame.max }) } else { - overlay.placed(self.rect).size_limits(frame) + overlay.placed(rect).size_limits(frame) }; if let Some(bounds) = self.bounds { overlay = overlay.bounds(bounds); @@ -496,7 +496,21 @@ impl<'a> FloatingGroup<'a> { /// Where the group shows while its column's content fixes its height ([`WindowColumn::shown`]). `None` while the /// rect gives the height. fn held_rect(&self) -> Option { - self.column?.shown(self.rect, self.chrome, self.rtl) + let column = self.column?; + // A collapsed column's width is its own; an expanded one shows at the rect's width within the panels' limits. + let rect = if column.collapsed.is_some() { self.rect } else { self.within_limits() }; + column.shown(rect, self.chrome, self.rtl) + } + + /// The window's size limits: the body's with the chrome on top. + fn frame_limits(&self) -> SizeLimits { + self.limits.around(Vec2::new(0.0, self.chrome)) + } + + /// The rect at its place, its size within [`Self::frame_limits`]: a rect placed or restored outside the panels' + /// limits shows at the nearest size within them, as an OS window's placed rect does. + fn within_limits(&self) -> Rect { + Rect::from_min_size(self.rect.min, self.frame_limits().clamp(self.rect.size())) } /// The double arrow's square at the end of the title row the window keeps to. @@ -564,7 +578,10 @@ impl Component for FloatingGroup<'_> { if self.moving && let Some(start) = self.start_drag.take() { - start(&mut cx, !self.continued); + // A window its column's content sizes keeps the rect's size; any other keeps it within the panels' limits. + let fitted = self.column.is_some_and(|column| column.fitted.is_some()); + let size = if fitted { self.rect.size() } else { self.within_limits().size() }; + start(&mut cx, !self.continued, size); } if let Some(opener) = self.menu_opener { Popup::toggle(opener, &mut cx); diff --git a/crates/ui-panels/src/docking/flyout.rs b/crates/ui-panels/src/docking/flyout.rs index af380bbe65..a74de05d1c 100644 --- a/crates/ui-panels/src/docking/flyout.rs +++ b/crates/ui-panels/src/docking/flyout.rs @@ -51,8 +51,11 @@ impl Outcome for FlyoutOutput { /// A popup beside an iconic column, on the side of the canvas, whose top left the caller places. Escape closes it; with /// Auto-Collapse Iconic Panels a press outside it and the focus leaving it close it too. Its body is measured at the -/// flyout's width first: the flyout is as tall as the body measures within the room below its top, and at least its -/// `size`'s height, and the body then shows in the rect that takes. +/// flyout's width first: the flyout is as tall as the body measures, at most the height of `within`, and at least its +/// `size`'s height, and the body then shows in the rect that takes. A flyout that fits below its top stays there; one +/// taller than the room below its top moves up by what it overflows and no further, its bottom on `within`'s (the +/// layer's keep rule moves it the least distance into its bounds), and only one taller than `within` starts at +/// `within`'s top and scrolls. /// /// The user resizes it by its top and bottom edges, the edge away from the column and the two corners there; the /// column side stays. The flyout keeps no rect of its own: each step comes back in [`FlyoutShown::placed`] and the @@ -140,8 +143,9 @@ impl Flyout { } }; let size = self.size; - // A body measures no taller than the room below the top, inside the bounds. - let room = (self.within.bottom() - top_left.y).max(size.y); + // A body measures no taller than the bounds: a flyout that does not fit below its top moves up by its overflow + // alone, so only a body taller than the bounds is limited to them. + let room = self.within.height().max(size.y); let overlay = self.overlay(top_left, ui.is_rtl()); self.props = self.props.mount(Mount::Layer(overlay)); let shown = ui.show_container(popup, self, |ui, cx| { diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 29c277e8ac..a4426dbcdb 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -221,6 +221,15 @@ const GRIP: PartKey = PartKey::new("grip"); fn grip_width(tokens: &Tokens) -> f32 { tokens.size.icon.lg + 2.0 * tokens.space.pad.regular } + +/// The least the drag band narrows to in a header too narrow for it and the shown tab: an icon's room. +fn grip_least(tokens: &Tokens) -> f32 { + tokens.size.icon.lg +} + +/// How many of the shown tab's first letters the header keeps room for before the drag band narrows, as many as a +/// shrunk panel tab shows. +const SHOWN_TAB_LETTERS: usize = 3; /// The panel menu button at the header's end edge. pub(super) const MENU: PartKey = PartKey::new("panel_menu"); /// Where the group menu hangs while a context request on a tab holds it open: the request's point. @@ -492,6 +501,34 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup< IconButton::new(self.panel_menu_icon.clone()).size(ControlSize::Sm).popup(PopupKind::Menu).label(name) } + /// The room the panel menu button takes past the drag band, with the gap before it; none when it does not show. + fn menu_room(&self, cx: &MeasureCx<'_, Self>) -> f32 { + if self.shows_menu_button() { cx.tokens.space.gap.item + cx.face(self.menu_face(cx.words::().panel_menu.clone())).x } else { 0.0 } + } + + /// The least room the strip takes to show the shown tab's first letters: the tab as the strip builds it (icon, + /// count, mark and close button) with only those letters of its title, and beside other tabs the overflow + /// button, which is as wide as the tab is high. + fn shown_tab_least(&self, cx: &MeasureCx<'_, Self>) -> f32 { + let panels = self.panels.as_slice(); + let tabs = strip_tabs(panels, self.closable); + let shown = shown_tab(panels, self.active); + let Some(tab) = tabs.iter().find(|tab| tab.key == shown) else { return 0.0 }; + let letters: String = tab.title.as_str().chars().take(SHOWN_TAB_LETTERS).collect(); + let marked = tab_marks(cx.ui.ctx(), panels).iter().any(|(key, _)| *key == shown); + let mut face = Tab::new(letters).kind(TabKind::Panel).panel_look(self.tab_look).closable(tab.closes).marked(marked); + if let Some(count) = tab.count { + face = face.detail(cx.env.format().integer(u64::try_from(count).unwrap_or(u64::MAX))); + } + match tab.swatch { + Some(Some(color)) => face = face.icon(IconSpec::swatch(color)), + Some(None) => face = face.icon(IconSpec::empty_swatch()), + None => {} + } + let size = cx.face(face); + if tabs.len() > 1 { size.x + size.y } else { size.x } + } + /// Starts a drag of the whole group: its drop region shows the group's name. fn start_drag(&mut self, cx: &mut Cx<'_, Self>) { start_group_drag(cx, DragUnit::Group(self.anchor.clone()), self.active, Some(self.size), Some(cx.label())); @@ -520,12 +557,14 @@ impl Component for let Some(slot) = cx.header_slot(HeaderEdge::End) else { return }; let words = cx.words::(); let flow = craft_behavior::Flow::new(slot, cx.flow.is_rtl()); - let (band, rest) = flow.take_start(grip_width(cx.tokens)); + // The band takes what the slot leaves past the panel menu button, which a narrowed header takes from the band. + let width = (slot.width() - self.menu_room(cx)).clamp(0.0, grip_width(cx.tokens)); + let (band, rest) = flow.take_start(width); let sense = if self.movable { Sense::CLICK | Sense::DRAG | Sense::FOCUS } else { Sense::CLICK | Sense::FOCUS }; let _ = cx.header_part(HeaderEdge::End, GRIP, band).sense(sense).focusable(); if self.shows_menu_button() { // An icon button is square: its side is the slot's room past the band and the gap. - let side = (slot.width() - grip_width(cx.tokens) - cx.tokens.space.gap.item).max(0.0); + let side = (slot.width() - width - cx.tokens.space.gap.item).max(0.0); let end = rest.take_end(side).0; let height = side.min(slot.height()); let top = if self.tab_look == PanelTabLook::Plain { slot.top() } else { slot.center().y - height / 2.0 }; @@ -680,15 +719,12 @@ impl Container for Some(self.open.reborrow()) } - /// The drag band, then the panel menu button when it shows, at the header's end edge. + /// The drag band, then the panel menu button when it shows, at the header's end edge. In a header too narrow for + /// them and the shown tab's least room, the band narrows to an icon's room, so the shown tab stays visible. fn header_parts(&self, cx: &MeasureCx<'_, Self>) -> HeaderParts { - let band = grip_width(cx.tokens); - let button = if self.shows_menu_button() { - cx.tokens.space.gap.item + cx.face(self.menu_face(cx.words::().panel_menu.clone())).x - } else { - 0.0 - }; - HeaderParts::NONE.end(band + button) + let button = self.menu_room(cx); + let parts = HeaderParts::NONE.end(grip_width(cx.tokens) + button); + if self.titled { parts } else { parts.end_narrows(grip_least(cx.tokens) + button, self.shown_tab_least(cx)) } } fn footer(&mut self, ui: &mut Ui, _: &mut BodyCx<'_>) { diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index f33dc4557b..0dd8fb824f 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -208,7 +208,8 @@ pub struct IconicColumnStyle { /// icon groups, the top and bottom of the stack and each icon group's cells, which join its tabs. The flyout shows /// its group through the `view` of [`show_flyouts`](IconicColumn::show_flyouts), with the opened panel active, as tall as the view measures the /// group within the room and at least the height of its panels' default heights; a group the user sized keeps that -/// size. The flyout's top is level with its group's icons, shifted by the group's `flyout_offset`, inside `within`. +/// size. The flyout's top is level with its group's icons, shifted by the group's `flyout_offset`, inside `within`; +/// a flyout taller than the room below that top moves up by what it overflows and no further. /// The user resizes it by its top and bottom edges and the edge away from the column; each step comes back in /// [`IconicColumnOutput::flyout`], which the host keeps in the group (`flyout_width`, `height`, `flyout_offset`). /// diff --git a/crates/ui-panels/src/docking/iconic/trials.rs b/crates/ui-panels/src/docking/iconic/trials.rs index aaa36e197e..a511f7bb6e 100644 --- a/crates/ui-panels/src/docking/iconic/trials.rs +++ b/crates/ui-panels/src/docking/iconic/trials.rs @@ -422,6 +422,112 @@ fn a_flyout_with_an_offset_in_a_short_viewport_stays_inside_and_resizes_its_widt } } +/// The names of the panels of the tall-body trials, which set no heights. +const TALL: [&str; 8] = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"]; +/// What the body of a flyout in the tall-body trial measures. +const TALL_BODY: f32 = 300.0; +/// The room below the last group's icon in the short-window trial. +const ROOM_BELOW: f32 = 200.0; +/// How much shorter than that room the body of the flyout that fits measures, and how much taller the one that does not. +const OVERFLOW: f32 = 40.0; + +/// What [`tall_flyouts`] returns: the fixture, the panel whose flyout is open (the trial sets it) and the rect the open +/// flyout's body showed in, last pass. +type TallFlyouts = (Fixture, Rc>>, Rc>>); + +/// A column of the [`TALL`] panels, each in a group of its own, on the left window edge; its flyouts stay inside the +/// bounds `within` holds and their bodies measure the height `body` holds. Returns the fixture, the panel whose flyout +/// is open (the trial sets it) and the rect the open flyout's body showed in, last pass. +fn tall_flyouts(within: &Rc>, body: &Rc>) -> TallFlyouts { + let (open, shown) = (Rc::new(Cell::new(None)), Rc::new(Cell::new(None))); + let (bounds, measures, now, seen) = (Rc::clone(within), Rc::clone(body), Rc::clone(&open), Rc::clone(&shown)); + let mut column = Column::new((0..TALL.len() as u8).map(|panel| Group::new(vec![panel], 0)).collect()); + column.iconic = true; + let mut fixture = Fixture::new(move |ui| { + let current = now.get(); + let mut opened = current; + IconicColumn::new("Panels", global("iconic column", "tall flyouts"), &column, Bind::bound(&mut opened), &|panel: &u8| { + PanelSpec::new(TALL[usize::from(*panel) % TALL.len()]) + }) + .edge(DockEdge::Start) + .opens(Side::End) + .within(bounds.get()) + .show_flyouts_at(ui, Rect::from_min_size(Pos2::ZERO, Vec2::new(RAIL, SCREEN.y)), |group, at, ui, _| { + match at { + GroupAt::Measure(_) => return Some(measures.get()), + GroupAt::Show(rect) => { + if group.active_panel().is_some_and(|panel| Some(*panel) == current) { + seen.set(Some(rect)); + } + Panel::new("Flyout").show_at(ui, rect, |_, _| ()); + } + } + None + }); + now.set(opened); + }); + fixture.room(SCREEN).settle(); + (fixture, open, shown) +} + +/// Closes the open flyout of [`tall_flyouts`] and opens the last group's. +fn reopen_last(fixture: &mut Fixture, open: &Cell>) { + open.set(None); + fixture.settle(); + open.set(Some(TALL.len() as u8 - 1)); + fixture.settle(); +} + +/// A flyout whose body measures taller than the room below its group's icons moves up to stay inside the bounds, as +/// tall as the body (or as the bounds when those are shorter): it is not cut to the room below its top with the rest +/// of its body laid out below the bounds. The panels set no heights, so the group's height does not give the room. +#[trial] +fn a_flyout_taller_than_the_room_below_its_icons_moves_up_inside_the_bounds() { + let (within, body) = (Rc::new(Cell::new(screen())), Rc::new(Cell::new(TALL_BODY))); + let (mut fixture, open, shown) = tall_flyouts(&within, &body); + let last = TALL[TALL.len() - 1]; + let icon = fixture.by_label(last).expect("the last group's icon").rect; + for height in [icon.bottom() + 8.0, 200.0] { + // The bounds end just below the last icon, or are shorter than the body. + let bounds = Rect::from_min_size(Pos2::ZERO, Vec2::new(SCREEN.x, height)); + within.set(bounds); + reopen_last(&mut fixture, &open); + let rect = shown.get().expect("the last group's flyout is open"); + let wanted = TALL_BODY.min(bounds.height()); + assert!(bounds.bottom() - icon.top() < TALL_BODY, "the bounds leave less room below the icon than the body takes: {icon:?} in {bounds:?}"); + assert!(bounds.contains_rect(rect), "{height}: the flyout {rect:?} stays inside {bounds:?}"); + assert!(rect.height() > wanted || near(rect.height(), wanted), "{height}: the flyout {rect:?} takes the body's height {wanted}"); + assert!(rect.top() < icon.top(), "{height}: the flyout {rect:?} moves up from its icon {icon:?}"); + } +} + +/// On a short window a flyout whose body fits below its group's icons keeps its top at the icons, and one whose body +/// is taller than the room below them moves up only by what it overflows, its bottom on the bounds' bottom: neither +/// takes the whole height of the bounds over the column's other icons. +#[trial] +fn a_flyout_on_a_short_window_moves_up_only_by_its_overflow() { + let (within, body) = (Rc::new(Cell::new(screen())), Rc::new(Cell::new(TALL_BODY))); + let (mut fixture, open, shown) = tall_flyouts(&within, &body); + let icon = fixture.by_label(TALL[TALL.len() - 1]).expect("the last group's icon").rect; + let bounds = Rect::from_min_size(Pos2::ZERO, Vec2::new(SCREEN.x, icon.top() + ROOM_BELOW)); + within.set(bounds); + let sizes = StyleCx::with_root(fixture.ctx(), DockSizes::style); + let least = sizes.strip + sizes.least; + assert!(icon.top() - OVERFLOW > bounds.top(), "the bounds leave room above the icon for the taller flyout to move up: {icon:?}"); + for over in [-OVERFLOW, OVERFLOW] { + let height = ROOM_BELOW + over; + assert!(height > least, "{over}: the body {height} measures taller than the flyout's least height {least}"); + body.set(height); + reopen_last(&mut fixture, &open); + let rect = shown.get().expect("the last group's flyout is open"); + // A body that fits stays at the icon's top; a taller one moves up by its overflow alone. + let top = icon.top() - over.max(0.0); + assert!(near(rect.height(), height), "{over}: the flyout {rect:?} takes its body's height {height}"); + assert!(near(rect.top(), top), "{over}: the flyout {rect:?} has its top at {top}, below the icon {icon:?} or up by its overflow"); + assert!(bounds.contains_rect(rect), "{over}: the flyout {rect:?} stays inside {bounds:?}"); + } +} + /// Each icon group's grip strip has its own room at the group's top: across the group, below the bar or the group /// before it and above the group's first icon, overlapping no icon. A drag that starts on a grip moves its whole /// group, as a drag on an icon moves its panel. @@ -717,7 +823,7 @@ fn icon_groups_apart_by_a_rule_show_one_level_rule_between_them() { let band = |group: u64| fixture.part_rect(id, GRIP.at(group)).expect("each group keeps a grip band"); let (first, last, next) = (cell(0), cell(1), cell(2)); let (top, lower) = (band(0), band(1)); - assert!(first.top() < gripped_first.top() - 0.5, "the first icon {first:?} stands higher than under a grip strip {gripped_first:?}"); + assert!(first.top() < gripped_first.top(), "the first icon {first:?} stands higher than under a grip strip {gripped_first:?}"); for (group, band) in [top, lower].into_iter().enumerate() { assert!(grip_ticks(&shapes, band).is_none(), "group {group}: the band shows no marks"); } @@ -733,7 +839,7 @@ fn icon_groups_apart_by_a_rule_show_one_level_rule_between_them() { let between: Vec<_> = level.iter().filter(|(a, _, _)| a.y > last.bottom() && a.y < next.top()).collect(); let [(a, b, ink)] = between.as_slice() else { panic!("one rule between the groups: {level:?}") }; let middle = (last.bottom() + next.top()) / 2.0; - assert!((a.y - middle).abs() <= 0.5, "the rule {a:?} lies in the middle of the room from {last:?} to {next:?}"); + assert!(near(a.y, middle), "the rule {a:?} lies in the middle of the room from {last:?} to {next:?}"); let (left, right) = (a.x.min(b.x), a.x.max(b.x)); let span = right - left; assert!(left > 0.0 && right < RAIL && span > RAIL - span, "the rule reaches across the column, short of its sides: {a:?} to {b:?}"); diff --git a/crates/ui-panels/src/docking/native.rs b/crates/ui-panels/src/docking/native.rs index caf6d5b1ef..2af9145811 100644 --- a/crates/ui-panels/src/docking/native.rs +++ b/crates/ui-panels/src/docking/native.rs @@ -9,10 +9,10 @@ use super::{DockConfig, FloatingGroupOutput, PanelSpec}; use crate::runtime::windows::{WindowAction, WindowHost, WindowSpec}; -use crate::runtime::{drag, overlay}; -use craft_behavior::GesturePhase; +use crate::runtime::{drag, overlay, pointer}; use craft_behavior::dock::{Action, Floating}; use craft_behavior::placement::{Defaults, monitor_of, place}; +use craft_behavior::{Buttons, GesturePhase}; use craft_host::target::WindowKind; use egui::{Context, Pos2, Rect, Vec2, ViewportId}; @@ -29,6 +29,8 @@ pub struct Opening { pub rect: Rect, /// The OS window to open, or `None` where the group shows in the app window. pub spec: Option, + /// The group shows in the app window until the drag that moves it there ends, and in an OS window after. + pub waits: bool, } /// Whether the groups of panels with `specs` open OS windows: the dock's `config` turns them on, the platform opens @@ -53,9 +55,11 @@ pub fn pixels_per_point(ctx: &Context, viewport: ViewportId) -> Option { } /// The window a group of panels with `specs` opens: a document window when any panel is a document, else a tool -/// window (a palette level, no taskbar entry). +/// window (a palette level, no taskbar entry). An Escape nothing in it takes is the Cancel of the window the dock is in. pub fn spec_for(specs: &[PanelSpec]) -> WindowSpec { - if specs.iter().any(|spec| spec.window_kind == WindowKind::Document) { WindowSpec::document() } else { WindowSpec::tool() } + let document = specs.iter().any(|spec| spec.window_kind == WindowKind::Document); + let spec = if document { WindowSpec::document() } else { WindowSpec::tool() }; + spec.hands_on_cancel(true) } /// The rect in the main window's points of `desktop`, a rect in desktop points: where a window at `desktop` would sit @@ -87,17 +91,38 @@ pub fn restore

(ctx: &Context, window: &Floating

) -> Rect { /// at its own rect. `specs` are its panels' specs; `group` is the id of the group that shows it. A window that opens /// opens at its [`restore`]d rect; an open window stays at the placement the dock model recorded for it, so the /// monitor fit of `restore` never sends back a place the user gave it. +/// +/// A window opens no OS window while a drag moves it in the app window: the OS gives an OS window no press that went +/// down in another window, so the drag would end. `continues` says that the window takes over the held press in this +/// pass (`DockArea::continue_move`), which a window never placed on the desktop does in the app window. #[doc(hidden)] -pub fn opening

(ctx: &Context, config: &DockConfig, window: &Floating

, specs: &[PanelSpec], group: egui::Id) -> Opening { +pub fn opening

(ctx: &Context, config: &DockConfig, window: &Floating

, specs: &[PanelSpec], group: egui::Id, continues: bool) -> Opening { + let layer = Opening { rect: window.rect, spec: None, waits: false }; if !allowed(ctx, config, specs) { - return Opening { rect: window.rect, spec: None }; + return layer; } let open = WindowHost::of(ctx).viewport_of(group).is_some(); + if !open { + let takes_over = continues && window.native.is_none() && pointer::frame(ctx).buttons.contains(Buttons::PRIMARY); + if takes_over || pointer::pressed_part(ctx, group).is_some() || drag::sourced_by(ctx, group) { + return Opening { waits: true, ..layer }; + } + } let recorded = window.native.as_ref().filter(|_| open).and_then(|native| { let at = native.position()?; Some(Rect::from_min_size(Pos2::from(at), Vec2::from(native.normal.size))) }); - Opening { rect: recorded.unwrap_or_else(|| restore(ctx, window)), spec: Some(spec_for(specs)) } + Opening { rect: recorded.unwrap_or_else(|| restore(ctx, window)), spec: Some(spec_for(specs)), waits: false } +} + +/// Asks for the pass in which a group that waits to open its OS window ([`Opening::waits`]) opens it: the next one once +/// the press that moved it has ended, or the one after a target in another window had its chance to take the drop. +#[doc(hidden)] +pub fn waited(ctx: &Context, opening: &Opening, output: &FloatingGroupOutput) { + let ended = output.placed.is_some_and(|change| matches!(change.phase, GesturePhase::Commit | GesturePhase::Cancel)); + if opening.waits && (ended || pointer::pressed_part(ctx, output.response.id).is_none()) { + crate::runtime::frame::request_repaint(ctx); + } } /// The action that records where the OS put the native window `window`, shown in `viewport`: its placement, as an diff --git a/crates/ui-panels/src/rails/drawer.rs b/crates/ui-panels/src/rails/drawer.rs index dd2b1fd3c8..82960abf7c 100644 --- a/crates/ui-panels/src/rails/drawer.rs +++ b/crates/ui-panels/src/rails/drawer.rs @@ -440,7 +440,9 @@ impl ToolbarDrawer<'_, T> { if let Some(run) = run_of(&groups[group].slots, tool) { row = row.run(run); } - if let Some(icon) = &command.icon { + if let Some(icon) = &groups[group].tools[tool].icon { + row = row.icon(icon.clone()); + } else if let Some(icon) = &command.icon { row = row.icon(IconSpec::svg(IconId::from(icon.clone()))); } if on_toolbar(toolbar, &groups[group].tools[tool].id, grouped_tools_drag) { diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index b96af1e160..deca16fdbc 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -11,10 +11,10 @@ use crate::contract::{ use crate::display::TargetMark; use crate::layout_components::Row; use crate::menu::{self, Menu, MenuItem}; -use crate::primitives::{PaintShape, StrokeWidth}; +use crate::primitives::{IconSpec, PaintShape, StrokeWidth}; use crate::runtime::commands::{CommandRef, FireSource, ResolvedCommand}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, GlyphRole, StyleColor, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, GlyphRole, StyleColor, StyleCx}; use craft_behavior::overlay::{Align, Side}; use craft_behavior::{CursorIcon, HitLevel, HitPriority, IconId, Metrics, PartKey, PointerButton, PressPhase, Sense, Value}; use egui::{Pos2, Rect, Response, Vec2}; @@ -30,12 +30,16 @@ const MARK: PartKey = PartKey::new("mark"); const BAR: PartKey = PartKey::new("bar"); /// The style of a flyout button: it paints through its face, so it holds no look of its own besides its side, the rail -/// button's, and the size of the corner mark's press area, which is the size and the inset of the mark the face paints. -#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] +/// button's, its focus ring, and the size of the corner mark's press area, which is the size and the inset of the mark +/// the face paints. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct FlyoutButtonStyle { #[style(metrics)] metrics: Metrics, + /// The ring the button shows while it has keyboard focus: a face paints none. + #[style(focus)] + focus: FocusLook, /// The side of the corner mark, which is also its inset from the face's corner. mark: f32, /// The button's glyph role, which its face shows the icon in. @@ -200,7 +204,11 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> { /// enabled state, marked dot). /// The button itself runs the command, so the face only wears it, and the button's selected state with it. fn face(&self, laid: &Laid, selected: bool, glyphs: GlyphRole) -> IconButton<'static> { - let icon = self.lead(laid).and_then(|resolved| resolved.icon.clone()).map_or_else(|| IconId::new("more"), IconId::from); + // The shown tool's own icon, when it has one and the face stands for it, else its command's. + let own = if self.click.is_none() { self.tools.get(laid.shown).and_then(|tool| tool.icon.clone()) } else { None }; + let icon = own.unwrap_or_else(|| { + IconSpec::svg(self.lead(laid).and_then(|resolved| resolved.icon.clone()).map_or_else(|| IconId::new("more"), IconId::from)) + }); let command = self.click.clone().or_else(|| self.tools.get(laid.shown).map(|tool| tool.command.clone())); let face = match command { Some(command) => IconButton::command(icon, command), @@ -235,7 +243,12 @@ impl Component for FlyoutButton<'_, T> { fn style(cx: &StyleCx<'_>, _: FlyoutButtonStyleKey) -> FlyoutButtonStyle { let side = cx.env::().button(cx.tokens); - FlyoutButtonStyle { metrics: Metrics::new().min_size(Vec2::splat(side)), mark: cx.tokens.space.gap.tight, glyphs: cx.glyph_role() } + FlyoutButtonStyle { + metrics: Metrics::new().min_size(Vec2::splat(side)), + focus: cx.focus_look(), + mark: cx.tokens.space.gap.tight, + glyphs: cx.glyph_role(), + } } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { @@ -381,7 +394,10 @@ impl Component for FlyoutButton<'_, T> { let rows = Menu::inline(name.clone()).show(ui, |ui, _| { let mut ran = None; for (at, tool) in tools.iter().enumerate() { - let item = MenuItem::command(tool.command.clone()).radio_mark(tool.id == *shown); + let mut item = MenuItem::command(tool.command.clone()).radio_mark(tool.id == *shown); + if let Some(icon) = &tool.icon { + item = item.icon(icon.clone()); + } let row = match tips.filter(|tips| tips.has(&tool.id)) { Some(tips) => item.show_with_tip(ui, |ui| tips.show(&tool.id, ui)), None => item.show(ui), @@ -428,11 +444,11 @@ impl Component for FlyoutButton<'_, T> { if let Some(hint) = resolved.and_then(|resolved| resolved.hint.as_ref()) { access.description(hint.as_ref().to_owned()); } - // The face covers the whole button, so the button's own node is the face's node. + // The face covers the whole button, so the button's own node is the face's node. The corner mark is the + // pointer's and has no node: the button's node reports the flyout open or closed and serves Expand and Collapse. access.node(FACE, Role::None); if self.has_flyout() { access.has_popup(PopupKind::Menu); - access.node(MARK, Role::BUTTON).name = Name::Text(name.unwrap_or_default()); } } diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index ecd19c1854..54d207493a 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -130,7 +130,8 @@ type FooterFn<'a> = Box; /// and the slots fill the rows in reading order. The control padding surrounds the buttons; a slot that ends a group /// leaves `space.gap.inline` after its row; slots within a group sit `space.gap.tight` apart. The Edit Toolbar button /// follows the last slot; the host's footer stays in view under the slots, which scroll when the room is short under -/// an overlay bar in the end padding that shows only under the pointer (`Scroll::overlay`), and its +/// an overlay bar in the end padding that shows only under the pointer (`Scroll::overlay`), or at rest too with +/// [`bar_at_rest`](ToolRail::bar_at_rest), and its /// buttons show the rail's glyphs. The rail is exactly as tall as its rows and footer at the width it gets /// ([`measure_rail`](ToolRail::measure_rail)). The buttons are one roving group: arrow keys move between them by the /// grid. While the toolbar is edited the buttons are dragged and the rail takes drops, and reports the drop in the @@ -245,6 +246,14 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { self } + /// The overlay bar of a rail too short for its rows also shows while the pointer is away from the rail + /// ([`Scroll::at_rest`]). + #[must_use] + pub fn bar_at_rest(mut self) -> Self { + self.props = std::mem::take(&mut self.props).scroll(Scroll::vertical().overlay().at_rest()); + self + } + /// The cells the rail lays out: its visible slots and the Edit Toolbar button. fn cells(&self) -> usize { visible_slots(self.slots, hidden_in(self.hidden)).len() + usize::from(self.edit_toolbar.is_some()) diff --git a/crates/ui-panels/src/rails/tool/data.rs b/crates/ui-panels/src/rails/tool/data.rs index 77904e6ca3..cb0a1ed593 100644 --- a/crates/ui-panels/src/rails/tool/data.rs +++ b/crates/ui-panels/src/rails/tool/data.rs @@ -1,5 +1,6 @@ //! The data of a tool rail: tools, slots and the tool each slot showed last. +use crate::primitives::IconSpec; use crate::runtime::commands::CommandRef; use crate::runtime::env::Label; use egui::Ui; @@ -8,7 +9,7 @@ use egui::Ui; pub type SlotId = u32; /// One tool of a slot. A tool is a command: the command gives the label, the icon, the chord and the enabled state, -/// and picking the tool runs it. +/// and picking the tool runs it. An [`icon`](RailTool::icon) of the tool's own replaces the command's. #[derive(Clone, Debug, PartialEq, crate::contract::MemoProps, crate::contract::PlainData)] #[non_exhaustive] pub struct RailTool { @@ -16,12 +17,24 @@ pub struct RailTool { pub id: T, /// The command the tool runs. pub command: CommandRef, + /// The icon the tool shows in place of its command's: the app's own artwork, a value glyph, where the icon sets + /// have none. + #[plain_data(assume = "an icon is a value: an SVG name, a colour or a 'static glyph compared by address, never written through")] + pub icon: Option>, } impl RailTool { - /// A tool reported as `id` that runs `command`. + /// A tool reported as `id` that runs `command`, showing its command's icon. pub fn new(id: T, command: impl Into) -> Self { - RailTool { id, command: command.into() } + RailTool { id, command: command.into(), icon: None } + } + + /// Shows `icon` for the tool, on its rail button, its flyout row and its drawer row, in place of its command's + /// icon: an app's own tool artwork (`IconSpec::glyph`). + #[must_use] + pub fn icon(mut self, icon: impl Into>) -> Self { + self.icon = Some(icon.into()); + self } } diff --git a/crates/ui-panels/src/rails/tool/trials.rs b/crates/ui-panels/src/rails/tool/trials.rs index a5067f8bdb..b252d8373e 100644 --- a/crates/ui-panels/src/rails/tool/trials.rs +++ b/crates/ui-panels/src/rails/tool/trials.rs @@ -156,6 +156,32 @@ fn in_a_short_room_the_rows_scroll_above_the_footer_that_stays_in_view() { } } +/// A rail too short for its rows shows its bar in the end padding beside the buttons while the pointer is away only +/// with `bar_at_rest`. +#[trial] +fn a_short_rail_shows_its_bar_at_rest_only_with_bar_at_rest() { + let grid = DockGrid::rail(LABELS.len()).resolved(&DockSizes::of(Fixture::new(|_| {}).ctx())); + for at_rest in [false, true] { + let (slots, last) = (Tracked::new(slots()), Tracked::new(LastUsed::default())); + let mut fixture = Fixture::new(move |ui| { + let rail = ToolRail::new("Tools", &slots, &0, &last); + let rail = if at_rest { rail.bar_at_rest() } else { rail }; + rail.show_rail(ui, |ui, _| { + Button::new("Foot").show(ui); + }); + }); + fixture.room(Vec2::new(grid.width(1), 100.0)).settle(); + let (rail, first, foot) = (rect(&fixture, "Tools"), rect(&fixture, "Move"), rect(&fixture, "Foot")); + assert!(rect(&fixture, "Clone Stamp").bottom() > foot.top(), "at rest {at_rest}: the rows do not fit the room"); + let band = Rect::from_x_y_ranges(first.right()..=rail.right(), rail.top()..=foot.top()); + fixture.frame(vec![moved(rail.right_bottom() + Vec2::splat(200.0))]); + fixture.settle(); + let shapes = fixture.frame_shapes(); + let paints = shapes.iter().map(egui::Shape::visual_bounding_rect).any(|b| b.is_positive() && band.expand(0.5).contains_rect(b)); + assert_eq!(paints, at_rest, "at rest {at_rest}: a bar shows in the end padding with the pointer away: {band:?}"); + } +} + /// The tool rail's buttons are larger than a lone icon button's and rest in a quieter ink than they show under the /// pointer. #[trial] @@ -476,3 +502,55 @@ fn idle_key_bytes(count: u8) -> usize { fn a_tool_rails_idle_key_bytes_do_not_grow_with_its_slots() { assert_eq!(idle_key_bytes(10), idle_key_bytes(100), "the key follows revisions, not the slots, the hidden or the remembered tools"); } + +/// A tool's own icon replaces its command's: the app's glyph paints the rail button that shows the tool and the tool's +/// row in the flyout, and a tool without one keeps its command's icon. +#[trial] +fn a_tools_own_icon_paints_its_button_and_its_flyout_row() { + use crate::primitives::{Glyph, IconSpec}; + use crate::style::UiTokens; + + // An app's tool artwork: one ellipse across its rect, a shape nothing else on the rail paints, so the frame's + // shapes say where the glyph painted. + #[derive(crate::contract::MemoProps)] + struct Artwork; + impl Glyph for Artwork { + fn paint(&self, painter: &egui::Painter, _: &UiTokens, rect: Rect, color: egui::Color32, _: bool) { + painter.add(egui::Shape::ellipse_filled(rect.center(), rect.size() / 2.0, color)); + } + } + // Where the glyph painted in the fixture's next frame. A frame that replays a memoized view repeats its shapes, so + // the shapes of one frame show every place the glyph is on screen. + let painted = |fixture: &mut Fixture| -> Vec { + fixture + .frame_shapes() + .iter() + .filter_map(|shape| match shape { + egui::Shape::Ellipse(ellipse) => Some(Rect::from_center_size(ellipse.center, ellipse.radius * 2.0)), + _ => None, + }) + .collect() + }; + + let mut group = tools(&[1, 2]); + group[0] = group[0].clone().icon(IconSpec::glyph(&Artwork)); + let (slots, last) = (Tracked::new(vec![ToolSlot::new(0, group)]), Tracked::new(LastUsed::default())); + let mut fixture = Fixture::new(move |ui| { + ToolRail::new("Tools", &slots, &1, &last).show_rail(ui, |_, _| {}); + }); + fixture.room(Vec2::new(200.0, 400.0)).settle(); + let button = rect(&fixture, "Brush"); + let face = painted(&mut fixture); + assert!(!face.is_empty() && face.iter().all(|at| button.contains_rect(*at)), "the glyph paints the Brush button: {face:?} in {button:?}"); + + // With the flyout open the glyph paints the Brush row too, and the Pencil row keeps its command's icon. + fixture.frame(vec![secondary(button.center(), true), secondary(button.center(), false)]); + fixture.settle(); + let pencil = rect(&fixture, "Pencil"); + let shown = painted(&mut fixture); + assert!( + shown.iter().any(|at| !button.intersects(*at) && !pencil.contains(at.center())), + "the open flyout's Brush row paints the glyph too: {shown:?}, button {button:?}, Pencil row {pencil:?}" + ); + assert!(shown.iter().all(|at| !pencil.contains_rect(*at)), "the Pencil row keeps its command's icon: {shown:?} in {pencil:?}"); +} diff --git a/crates/ui-panels/tests/it/dialogs.rs b/crates/ui-panels/tests/it/dialogs.rs index 453dc081e4..1cc1369190 100644 --- a/crates/ui-panels/tests/it/dialogs.rs +++ b/crates/ui-panels/tests/it/dialogs.rs @@ -3,12 +3,13 @@ use craft_behavior::{Metrics, MotionMode, PartKey, Sense}; use craft_host::target::{Os, WindowChrome}; use craft_quit::{CloseAnswer, CloseScope}; -use craft_ui::contract::overlay::{Dismiss, Outside}; +use craft_ui::contract::overlay::{Dismiss, OpenFilter, Outside, any_open}; use craft_ui::contract::{Bind, Common, Component, Cx, MeasureCx, PartsCx, Props as _, Role, Show as _, ShowContainer as _}; use craft_ui::dialog::stories::hosted; use craft_ui::dialog::{ - Alert, ChildDialog, Dialog, DialogHost, DialogId, DialogResult, DialogStack, HostedAlert, JobAnswer, JobProgress, PromptChoice, PromptKind, - RecoveredDocument, RecoveryAnswer, RecoveryChoice, RecoveryDialog, StackDialog, StandardPrompt, StartupStage, UnsavedChangesDialog, dialog_id, + Alert, ChildDialog, Dialog, DialogHost, DialogId, DialogResult, DialogStack, HostedAlert, JobAnswer, JobProgress, Prompt, PromptChoice, + PromptKind, RecoveredDocument, RecoveryAnswer, RecoveryChoice, RecoveryDialog, StackDialog, StandardPrompt, StartupStage, UnsavedChangesDialog, + dialog_id, }; use craft_ui::display::Text; use craft_ui::popover::Popover; @@ -302,6 +303,32 @@ fn a_prompt_without_a_default_answer_opens_with_no_button_focused() { assert_eq!(answered.get(), Some(JobAnswer::Cancel)); } +/// A job window is not a dialog that asks: an app that draws it only while no such dialog is open draws it in every +/// pass, and the window still counts as a modal layer. A prompt with an answer counts as asking. +#[trial] +fn a_job_window_is_a_modal_layer_that_asks_nothing() { + let (passes, drawn) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0))); + let (all, shown) = (Rc::clone(&passes), Rc::clone(&drawn)); + let mut fixture = Fixture::new(move |ui| { + all.set(all.get() + 1); + if !any_open(ui.ctx(), OpenFilter::Asks) { + JobProgress::new("Exporting", "Page 1 of 3").show(ui); + shown.set(shown.get() + 1); + } + }); + fixture.idle(6); + assert_eq!(drawn.get(), passes.get(), "the window is drawn in every pass"); + assert!(fixture.by_label("Exporting").is_some(), "the window shows"); + assert!(any_open(fixture.ctx(), OpenFilter::Modal), "the window is a modal layer"); + assert!(!any_open(fixture.ctx(), OpenFilter::Asks), "the window asks nothing"); + + let mut fixture = Fixture::new(|ui| { + Prompt::new("Replace the file?", "A file with this name exists.").answers([FooterButton::new("Replace", DialogRole::Accept)]).show(ui); + }); + fixture.idle(6); + assert!(any_open(fixture.ctx(), OpenFilter::Asks), "a prompt with an answer asks"); +} + const BAND: PartKey = PartKey::new("band"); /// A style with no look. diff --git a/crates/ui-panels/tests/it/dock_group.rs b/crates/ui-panels/tests/it/dock_group.rs index b76f4b2753..70e4217822 100644 --- a/crates/ui-panels/tests/it/dock_group.rs +++ b/crates/ui-panels/tests/it/dock_group.rs @@ -296,6 +296,55 @@ fn a_press_on_an_app_drag_widget_in_the_body_is_no_surface_press() { assert!(surface.get(), "a press on the empty body is the group's surface press"); } +// As a group narrows, at both densities, the drag band narrows to its least before the shown tab goes below the width a +// shrunk tab keeps (its first letters), alone and beside a tab that goes to the overflow menu. The shown tab stays +// inside the group, and the band never covers it, down to a 40 pt column. +#[trial] +fn a_narrow_groups_drag_band_narrows_before_the_shown_tab() { + use craft_theme::Size; + let tab = |width: f32, density: Size, names: &'static [&'static str]| { + let panels: Vec = names.iter().enumerate().map(|(at, name)| PanelTitle::new(PanelKey::new(at as u64 + 1), *name)).collect(); + let group_rect = Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(width, 200.0)); + let grip = Rc::new(Cell::new(None::)); + let seen = Rc::clone(&grip); + let mut fixture = Fixture::new(move |ui| { + let out = DockGroup::new(1usize, Titles::from_content(panels.clone()), panels[0].key).show_at(ui, group_rect, |_, _| ()); + seen.set(out.output.grip.map(|(rect, _)| rect)); + }); + fixture.density(density).settle(); + (fixture.by_label("Tools").map(|node| node.rect), grip.get()) + }; + for density in [Size::Compact, Size::Comfortable] { + // The least a tab shows: the narrowest "Tools" gets beside a shown tab as the group narrows by 1 pt steps, before + // it overflows; so within 1 pt of the strip's least. + let least = (0..260) + .filter_map(|step| tab(300.0 - step as f32, density, &["Tools Options", "Tools"]).0) + .map(|rect| rect.width()) + .fold(f32::INFINITY, f32::min); + assert!(least.is_finite(), "the other tab shows shrunk in some group ({density:?})"); + for names in [&["Tools"][..], &["Tools", "Swatches"][..]] { + let (Some(natural), Some(whole)) = tab(300.0, density, names) else { panic!("a wide group shows the tab and the band ({density:?})") }; + let least = least.min(natural.width()); + // The band at its narrowest, in the narrowest group. + let (_, Some(narrowest)) = tab(40.0, density, names) else { panic!("a 40 pt group shows the band ({density:?}, {names:?})") }; + assert!(narrowest.width() < whole.width() - 0.5, "the band narrows in a 40 pt group ({density:?}, {names:?})"); + for width in (0..13).map(|step| 40.0 + 8.0 * step as f32) { + let (shown, grip) = tab(width, density, names); + let Some(shown) = shown else { panic!("the shown tab shows in a {width} pt group ({density:?}, {names:?})") }; + let Some(grip) = grip else { panic!("the band shows in a {width} pt group ({density:?}, {names:?})") }; + let group = Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(width, 200.0)); + assert!(group.contains_rect(shown), "the shown tab {shown:?} lies inside the {width} pt group ({density:?}, {names:?})"); + assert!(!grip.intersects(shown.shrink(0.5)), "the band {grip:?} does not cover the shown tab {shown:?} in {width} pt ({density:?})"); + assert!( + shown.width() >= least - 1.0 || grip.width() <= narrowest.width() + 0.5, + "the band {grip:?} narrows to {} pt before the shown tab {shown:?} goes below {least} pt in {width} pt ({density:?}, {names:?})", + narrowest.width() + ); + } + } + } +} + // Closable panel tabs stay panel tabs: in a group too narrow for their whole names every tab keeps its place in the // strip, the shown one its whole name, and each shows a close button. A middle click closes an inactive tab without // showing it first. diff --git a/crates/ui-panels/tests/it/focus/dialog_open.rs b/crates/ui-panels/tests/it/focus/dialog_open.rs new file mode 100644 index 0000000000..a331358c43 --- /dev/null +++ b/crates/ui-panels/tests/it/focus/dialog_open.rs @@ -0,0 +1,48 @@ +//! Where focus goes when a dialog with no text field and no default stop opens. + +use super::{control, focused, id}; +use craft_behavior::{Input, NavShape, Roving}; +use craft_ui::runtime::focus::{FocusPolicy, KeyUse}; +use craft_ui::testing::focus::{Group, Stop, begin_body, end_body, pop_scope, push_scope, register_group, register_stop, widget}; +use craft_ui::testing::{Frames, trial}; +use egui::Ui; + +/// The stop a dialog with no field and no default stop focuses when it opens: `body` names its body's stops, `end` +/// the stops after its body (an end region's and a footer's buttons). A name starting with "text" is read-only text +/// that only a press focuses, and one starting with "row" is a child of a collection's row. +fn opens_on(body: &[&str], end: &[&str]) -> Option { + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + push_scope(ui.ctx(), id("dialog"), FocusPolicy::DIALOG, None); + begin_body(ui.ctx()); + for name in body { + if name.starts_with("text") { + widget(ui, id(name)); + register_stop(ui.ctx(), Stop::new(id(name), KeyUse::of(Input::Text)).press_only()); + } else if name.starts_with("row") { + widget(ui, id(name)); + register_stop(ui.ctx(), Stop::new(id(name), KeyUse::of(Input::Pointer)).in_group(id("row"))); + register_group(ui.ctx(), Group::new(id("row"), Roving::new(NavShape::Flat)).row(id("rows"))); + } else { + control(ui, name); + } + } + end_body(ui.ctx()); + for name in end { + control(ui, name); + } + pop_scope(ui.ctx()); + }; + frames.idle(3, &mut show); + focused(&frames.ctx) +} + +/// A dialog with no field and no default stop opens on the first body stop that Tab reaches, past read-only text, and +/// leaves the buttons after its body unfocused when the body has none, so Enter answers nothing nobody chose. +#[trial] +fn a_dialog_with_no_field_or_default_opens_on_its_first_reachable_body_stop() { + assert_eq!(opens_on(&["list", "new"], &["close"]), Some(id("list")), "the body's first stop takes the focus"); + assert_eq!(opens_on(&["text", "list"], &["close"]), Some(id("list")), "read-only text that Tab passes over does not"); + assert_eq!(opens_on(&["row child", "list"], &["close"]), Some(id("list")), "nor does a row's child, which Tab passes over"); + assert_eq!(opens_on(&[], &["action", "close"]), None, "with nothing in the body, no button after it takes the focus"); +} diff --git a/crates/ui-panels/tests/it/focus/mod.rs b/crates/ui-panels/tests/it/focus/mod.rs index fd2552ac98..0ad8cde79d 100644 --- a/crates/ui-panels/tests/it/focus/mod.rs +++ b/crates/ui-panels/tests/it/focus/mod.rs @@ -1,5 +1,6 @@ //! The focus service and the key stage, driven through registered stops over real egui widgets. +pub(crate) mod dialog_open; pub(crate) mod dialog_tab; pub(crate) mod keys; pub(crate) mod press; diff --git a/crates/ui-panels/tests/it/main.rs b/crates/ui-panels/tests/it/main.rs index 83aaa72406..1c11662b45 100644 --- a/crates/ui-panels/tests/it/main.rs +++ b/crates/ui-panels/tests/it/main.rs @@ -18,6 +18,7 @@ pub(crate) mod popup_surface; pub(crate) mod rails; pub(crate) mod sections; +pub(crate) mod story_shapes; craft_ui::registry!(); diff --git a/crates/ui-panels/tests/it/rails/mod.rs b/crates/ui-panels/tests/it/rails/mod.rs index 24d4dcca32..743f26dae1 100644 --- a/crates/ui-panels/tests/it/rails/mod.rs +++ b/crates/ui-panels/tests/it/rails/mod.rs @@ -4,7 +4,7 @@ pub(crate) mod drawer; pub(crate) mod locate; -use craft_behavior::{GesturePhase, Mixed}; +use craft_behavior::{GesturePhase, Mixed, PartKey}; use craft_ui::contract::overlay::{PlacementChange, PlacementKind}; use craft_ui::contract::{Props as _, Role, Show as _}; use craft_ui::docking::{FloatingGroup, GroupDrag}; @@ -12,6 +12,7 @@ use craft_ui::rails::{FlyoutButton, RailTool}; use craft_ui::runtime::commands::EditCommands; use craft_ui::runtime::drag; use craft_ui::runtime::frame::take_output; +use craft_ui::testing::focus::AccessActionKind; use craft_ui::testing::pointer::{moved, press, secondary}; use craft_ui::testing::{Fixture, Target, trial}; use egui::{Key, Modifiers, Pos2, Rect, Vec2}; @@ -131,6 +132,48 @@ fn the_flyout_of_a_low_tool_slides_up_to_stay_in_the_window() { assert!(flyout.bottom() > target.rect.bottom() + 1.0, "it slides: its bottom {} is below the tool's {}", flyout.bottom(), target.rect.bottom()); } +/// A tool group's button is one access node: the corner mark is the pointer's and adds no node, so a screen reader +/// reads the tool once. The button reports that it opens a menu and whether the flyout is open, Expand and Collapse +/// on it open and close the flyout, and a press on the mark still opens it at once. +#[trial] +fn a_tool_groups_button_is_one_node_that_reports_and_opens_the_flyout() { + let owner = Rc::new(Cell::new(None)); + let seen = owner.clone(); + let all = tools(&[UNDO, REDO, CUT]); + let mut fixture = Fixture::new(move |ui| { + let out = FlyoutButton::new(&all, &UNDO).show(ui); + seen.set(Some(out.response.id)); + }); + fixture.settle(); + let named = |fixture: &Fixture| -> Vec { + fixture.by_role(Role::BUTTON).into_iter().filter(|button| fixture.tree().name_of(button.node) == Some("Undo")).collect() + }; + let buttons = named(&fixture); + let rects: Vec = buttons.iter().map(|button| button.rect).collect(); + assert_eq!(buttons.len(), 1, "one Button node is named after the tool: {rects:?}"); + let button = buttons[0]; + let menu = Some(craft_ui::contract::PopupKind::Menu); + assert_eq!(fixture.tree().has_popup_of(button.node), menu, "the button says it opens a menu"); + assert_eq!(fixture.tree().expanded_of(button.node), Some(false), "the button reports the flyout closed"); + + take_output(fixture.ctx()); + fixture.access(AccessActionKind::Expand, &button).idle(2); + assert!(!fixture.by_role(Role::MENU).is_empty(), "Expand on the button opens the flyout"); + assert!(take_output(fixture.ctx()).fired.is_empty(), "Expand selects no tool"); + assert_eq!(fixture.tree().expanded_of(button.node), Some(true), "the button reports the flyout open"); + fixture.access(AccessActionKind::Collapse, &button).idle(2); + assert!(fixture.by_role(Role::MENU).is_empty(), "Collapse on the button closes the flyout"); + assert_eq!(fixture.tree().expanded_of(button.node), Some(false), "the button reports the flyout closed again"); + + let owner = owner.get().expect("the flyout button shows"); + let mark = fixture.part_rect(owner, PartKey::new("mark")).expect("the button has a corner mark"); + assert!(button.rect.contains_rect(mark), "the mark {mark:?} lies on the button {:?}", button.rect); + fixture.frame(vec![moved(mark.center())]); + fixture.frame(vec![press(mark.center())]).idle(2); + assert!(!fixture.by_role(Role::MENU).is_empty(), "a press on the mark opens the flyout without a hold"); + assert_eq!(named(&fixture).len(), 1, "the open flyout leaves one node named after the tool"); +} + /// A rail button tells assistive technology which tool is the current one: the current tool's button is pressed and /// every other tool's button is not, as it paints. #[trial] @@ -149,6 +192,29 @@ fn the_current_tools_button_reports_pressed_and_the_others_not() { assert_eq!(pressed("Cut"), Some(Mixed::Same(false)), "another tool's button reports that it is not"); } +/// A rail button with keyboard focus is ringed as a button is: a focus stroke of two points around its own rect. +#[trial] +fn a_focused_rail_button_shows_the_focus_ring_around_it() { + let all = tools(&[UNDO, REDO]); + let mut fixture = Fixture::new(move |ui| { + FlyoutButton::new(&all, &UNDO).show(ui); + }); + fixture.settle(); + let ring = |fixture: &mut Fixture| { + fixture.frame_shapes().iter().find_map(|shape| match shape { + egui::Shape::Rect(rect) if rect.stroke.width >= 2.0 => Some(rect.rect), + _ => None, + }) + }; + assert!(ring(&mut fixture).is_none(), "an unfocused rail button has no ring"); + fixture.key(Key::Tab, Modifiers::NONE); + fixture.settle(); + assert!(fixture.focused().is_some(), "Tab focused the rail button"); + let target = fixture.by_role(Role::BUTTON).into_iter().next().expect("the rail button shows"); + let ring = ring(&mut fixture).expect("the focused rail button paints a focus ring"); + assert!(ring.expand(1.0).contains_rect(target.rect), "the ring {ring:?} goes around the button {:?}", target.rect); +} + /// With a click command a click, Enter or Space fires it and selects nothing; a hold, a drag away and a right click /// list the tools, and the release that ends a hold fires nothing. #[trial] diff --git a/crates/ui-panels/tests/it/story_shapes.rs b/crates/ui-panels/tests/it/story_shapes.rs new file mode 100644 index 0000000000..ef8f94c747 --- /dev/null +++ b/crates/ui-panels/tests/it/story_shapes.rs @@ -0,0 +1,17 @@ +//! A fixture returns the clipped shapes of a frame that uploads textures. + +use craft_ui::testing::{Fixture, Registry, trial}; + +/// Menu, rail and tile stories; the first frame of each uploads textures, the font atlas among them. +const STORIES: [&str; 6] = + ["tool_rail_marked_in_a_closed_group", "edit_menu", "menu", "menu_taller_than_the_window", "menu_with_companion", "tile_actions"]; + +#[trial] +fn the_first_frame_of_a_story_returns_its_clipped_shapes() { + let registry = Registry::of(&[craft_ui::testing::register, craft_ui_widgets::testing::register]); + for name in STORIES { + let entry = registry.stories().iter().find(|entry| entry.story.name == name).unwrap_or_else(|| panic!("story {name}")); + let shapes = Fixture::story(&entry.story).frame_clipped_shapes(); + assert!(!shapes.is_empty(), "{name}: the frame paints the story"); + } +} diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 3734ecc754..7a5e6d2f31 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -172,8 +172,9 @@ pub struct DockArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> { /// The floating window holding the panel takes over the held primary press in this pass, with the pointer at the /// grab point inside the window ([`FloatingGroup::continue_move`]): the window follows the pointer and docks where it /// would dock on release. A request of the pass: a host that floats a panel from a rail's `torn_off` keeps it for - /// the one pass after, when the window shows. Without a held press, or when no window holds the panel, it does - /// nothing. + /// the one pass after, when the window shows. Where the dock opens OS windows (`DockConfig::native_windows`), the + /// window shows in the app window until the press ends, and then opens its OS window where it was released. Without + /// a held press, when no window holds the panel, or when the window has shown in an OS window, it does nothing. #[prop(quantity = "panel and grab point")] continue_move: Option<(P, Vec2)>, /// Moves key focus to the group that shows the panel, as a press on the group's body does, and picks its tab, as a @@ -1725,7 +1726,8 @@ impl Pass<'_, P> { let rights: Vec = window.panels().map(|panel| scene.permissions(panel)).collect(); let dock = scene.dock.with(("floating", window.id)); let group_id = dock.with("window"); - let opening = native::opening(&ctx, scene.config, window, &specs, group_id); + let continued = scene.continue_move.filter(|(panel, _)| window.panels().any(|held| held == *panel)).map(|(_, grab)| grab); + let opening = native::opening(&ctx, scene.config, window, &specs, group_id, continued.is_some()); // An OS window lays out at its own monitor's scale, which sizes its chrome; one in the app window at the // main window's. let scale = opening @@ -1791,7 +1793,7 @@ impl Pass<'_, P> { if scene.focus.is_some_and(|focus| window.panels().any(|held| held == focus)) { group = group.raise(); } - if let Some((_, grab)) = scene.continue_move.filter(|(panel, _)| window.panels().any(|held| held == *panel)) { + if let Some(grab) = continued { group = group.continue_move(grab); } if scene.raise.is_some_and(|raised| window.panels().any(|held| held == raised)) { @@ -1827,6 +1829,7 @@ impl Pass<'_, P> { }); self.dock = area_dock; let output = shown.output; + native::waited(&ctx, &opening, &output); // The window's grips, then everything it drew, in the OS window it shows in, if it has one. let grips = output.grip.map(|(rect, node)| DockSource::new(SourceKind::WindowGrip(anchor.clone()), rect, node)); let resize = diff --git a/crates/ui-patterns/src/patterns/form_dialogs/about.rs b/crates/ui-patterns/src/patterns/form_dialogs/about.rs index b6750bb915..592bcbd1a9 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/about.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/about.rs @@ -1,5 +1,5 @@ //! `AboutDialog`: Help > About in one window for every app, with the app's own data. Tabs About, Contributors and -//! Models, then the app's own tabs. +//! Models, then Licenses when the app gives license texts, then the app's own tabs. mod contributors; mod credits; @@ -7,7 +7,7 @@ mod credits; pub(crate) mod stories; pub use contributors::{CommitShare, ContributorSort, NameMode}; -pub use credits::{AboutImage, AboutInfo, AboutLink, Contributor, Credits, ModelCredit}; +pub use credits::{AboutImage, AboutInfo, AboutLicense, AboutLink, Contributor, Credits, ModelCredit}; use crate::buttons::{Button, IconButton, Link}; use crate::choice::Segmented; @@ -29,6 +29,7 @@ use crate::sections::{DialogRole, FooterButton}; use crate::style::TypeRole; use crate::table::Table; use crate::tabs::{Tab, TabKind, TabStrip}; +use crate::text::SelectableText; use contributors::{Writer, sorted_indices}; use craft_behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, SelectionChange, keyed}; use craft_theme::{Mode, Variant}; @@ -45,6 +46,9 @@ craft_ui::words! { about_tab: "aboutDialog.tab" = "About"; contributors_tab: "aboutDialog.contributors" = "Contributors"; models_tab: "aboutDialog.models" = "Models"; + licenses_tab: "aboutDialog.licenses" = "Licenses"; + /// The name of the Licenses tab's picker, which lists the licenses by name. + license: "aboutDialog.license" = "License"; /// The footer button of the listed layout ([`AboutLayout::Listed`]). close: "aboutDialog.close" = "Close"; version: template "aboutDialog.version" = "Version {version}"; @@ -107,7 +111,9 @@ pub enum AboutTab { Contributors, /// The credited AI models. Models, - /// The app's own tab at this position in the app's tabs, shown after Models. + /// The app's third-party license texts, shown after Models when the app gives any. + Licenses, + /// The app's own tab at this position in the app's tabs, shown after Models and Licenses. App(u8), } @@ -125,7 +131,7 @@ pub enum AboutLayout { Listed, } -/// A tab the app adds after Models: a name for the hosted dialog's `tab` field, a title and a body. +/// A tab the app adds after Models and Licenses: a name for the hosted dialog's `tab` field, a title and a body. /// /// The body is `Send` because a [`HostedAbout`] lives on the dialog stack, which needs its dialogs `Send`. pub struct AboutAppTab { @@ -150,6 +156,8 @@ struct View { descending: bool, /// The contributors show as a table; the grab bag of name links otherwise. table: bool, + /// The position of the license the Licenses tab shows. + license: usize, } /// The Models table's columns, the first of which holds the row label. @@ -238,12 +246,15 @@ impl Outcome for AboutOutput { /// header press sorts by its column, activating a row (Enter or a double click) reports the profile URL, and the /// row's tooltip is the summary. /// - **Models.** A table of the credited models with their commits, share of all commits and lines. -/// - **App tabs.** The app's own [`AboutAppTab`]s ([`app_tabs`](AboutDialog::app_tabs)) follow Models, each body in a -/// vertically scrolling stack. +/// - **Licenses.** Shown only when the app gives [`AboutLicense`]s ([`licenses`](AboutDialog::licenses)): a License +/// picker that lists them by name when there are several, then the picked license's full text, monospace and +/// selectable, in a vertically scrolling stack. +/// - **App tabs.** The app's own [`AboutAppTab`]s ([`app_tabs`](AboutDialog::app_tabs)) follow Models and Licenses, +/// each body in a vertically scrolling stack. /// -/// The name mode, the sort order and the view are kept in the dialog's container while it is open, and so is the tab -/// unless [`tab`](AboutDialog::tab) binds it. Links are reported -/// in [`AboutOutput::link`] and never opened from here. Enter and Escape close the dialog. +/// The name mode, the sort order, the view and the picked license are kept in the dialog's container while it is open, +/// and so is the tab unless [`tab`](AboutDialog::tab) binds it. Links are reported in [`AboutOutput::link`] and never +/// opened from here. Enter and Escape close the dialog. #[must_use = "show the dialog with `show`"] #[derive(crate::contract::Pattern, crate::contract::Props)] pub struct AboutDialog<'a> { @@ -255,7 +266,10 @@ pub struct AboutDialog<'a> { /// Binds the shown tab to `tab`; the dialog opens on it. #[prop] tab: Option>, - /// The app's own tabs, shown after Models. + /// The third-party license texts the Licenses tab shows; without any the dialog has no Licenses tab. + #[prop] + licenses: Option<&'a [AboutLicense]>, + /// The app's own tabs, shown after Models and Licenses. #[prop] app_tabs: Option<&'a mut [AboutAppTab]>, /// How the About tab lays out the info, and the footer button that goes with it. @@ -266,12 +280,13 @@ pub struct AboutDialog<'a> { impl<'a> AboutDialog<'a> { /// The dialog over `info` and `credits`, opening on the About tab. pub fn new(info: &'a AboutInfo, credits: &'a Credits) -> Self { - AboutDialog { info, credits, open: None, tab: None, app_tabs: None, layout: AboutLayout::default() } + AboutDialog { info, credits, open: None, tab: None, licenses: None, app_tabs: None, layout: AboutLayout::default() } } /// Shows the dialog. pub fn show(self, ui: &mut Ui) -> AboutOutput { - let AboutDialog { info, credits, open, tab, mut app_tabs, layout } = self; + let AboutDialog { info, credits, open, tab, licenses, mut app_tabs, layout } = self; + let licenses = licenses.unwrap_or_default(); // The strip shows the titles while the body draws a tab, so it reads its own copy of them. let app_titles: Vec