mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-26 04:57:32 +00:00
Merge remote-tracking branch 'origin/main' into HEAD
This commit is contained in:
@@ -11,7 +11,7 @@ nextest-version = "0.9.150"
|
||||
#
|
||||
# GPU tests: each test is its own process here, so the in-process `gpu_lock()` mutexes no longer
|
||||
# serialize them. Too many concurrent wgpu devices time out (`PollError: ... Wait timed out`), so
|
||||
# this group caps them at 4.
|
||||
# this group caps them at 4. scripts/ci-gpu-lavapipe.py reads this group's filters directly.
|
||||
[test-groups]
|
||||
gpu = { max-threads = 4 }
|
||||
|
||||
|
||||
@@ -151,7 +151,7 @@ jobs:
|
||||
# egui/winit/rfd.
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
libgtk-3-dev mesa-vulkan-drivers libvulkan1
|
||||
# The tests build with the optional craft-fonts input (crates/text/build.rs), so the
|
||||
# Japanese font tests that skip without it run. Same commit as release.yml.
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
@@ -164,7 +164,7 @@ jobs:
|
||||
timeout-minutes: 100
|
||||
# fmt, clippy, layers, scorecard, tests, panic_hunt, doctests and the wasm32 check, with
|
||||
# `--locked --features heif`, then the missing-translations report (xtask/src/main.rs).
|
||||
command: cargo xtask ci
|
||||
command: python3 scripts/test-ci-gpu-lavapipe.py && cargo xtask ci && python3 scripts/ci-gpu-lavapipe.py
|
||||
|
||||
# Windows tests run as two legs in parallel: the unit tests and the integration tests. As one job
|
||||
# they took ~28 min on the Windows runner; the legs take ~13 and ~15. Splitting the integration
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
name: House rules
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- AGENTS.md
|
||||
- CLAUDE.md
|
||||
- .github/workflows/house-rules.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- AGENTS.md
|
||||
- CLAUDE.md
|
||||
- .github/workflows/house-rules.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: house-rules-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
house-rules:
|
||||
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
|
||||
with:
|
||||
rust: true
|
||||
@@ -1,3 +1,56 @@
|
||||
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
|
||||
## House rules
|
||||
|
||||
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
|
||||
|
||||
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
|
||||
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
|
||||
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
|
||||
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
|
||||
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
|
||||
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
|
||||
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
|
||||
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
|
||||
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
|
||||
10. **Keep secrets and personal details out** of the repository, logs and requests.
|
||||
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
|
||||
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
|
||||
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
|
||||
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
|
||||
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
|
||||
<!-- craft-house-rules:end -->
|
||||
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
|
||||
## Rust Craft repositories
|
||||
|
||||
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
|
||||
|
||||
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
|
||||
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
|
||||
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
|
||||
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
|
||||
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
|
||||
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
|
||||
|
||||
## Licence allowlist
|
||||
|
||||
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
|
||||
|
||||
- `ISC`
|
||||
- `MIT`
|
||||
- `BSD-2-Clause`
|
||||
- `BSD-3-Clause`
|
||||
- `Apache-2.0`
|
||||
- `OFL-1.1`
|
||||
- `Ubuntu-font-1.0`
|
||||
- `Bitstream-Vera`
|
||||
- `CC0-1.0`
|
||||
- `CC-BY-4.0`
|
||||
- `CC-BY-SA-4.0`
|
||||
- `LicenseRef-Public-Domain`
|
||||
|
||||
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
|
||||
<!-- craft-house-rules:end -->
|
||||
|
||||
# AGENTS.md: guide for AI agents and contributors
|
||||
|
||||
PhotoCraft is an open-source, native, Photoshop-comparable image editor written in **Rust only** (no JavaScript or TypeScript). **No Tauri, Electron or webview shells:** the desktop app is native egui/eframe on wgpu, and the web build is the same Rust compiled to WebAssembly (trunk + wasm-bindgen). Never add Tauri (or any webview/JS UI framework) as a dependency, build step or packaging target. The product name is always written **PhotoCraft** (`{Function}Craft` in PascalCase, like its siblings ArtCraft, ArtCraftX, DesignCraft, VectorCraft, EffectCraft, FilmCraft, LightCraft, PdfCraft) in user-facing text: UI, window titles, About, installers, release names, docs prose. Machine names stay lowercase: crates (`photocraft-*`), binaries, file names, ids (`ai.storyteller.photocraft`). Shared Rust components live in [storytold/craft-libs](https://github.com/storytold/craft-libs) and are pinned by immutable git revision. UI libraries stay at L6. The goal is 1:1 Photoshop parity (same menus, shortcuts, behaviour and file fidelity) with better performance, and every feature drivable by agents. Read this file first, then `docs/`.
|
||||
@@ -70,7 +123,6 @@ People trust PhotoCraft with their work, and a crash loses it. A malformed file,
|
||||
8. **Performance is a feature.** Benchmark heavy operations on a 24–36 MP image in release. Work per tile in parallel (rayon), skip empty tiles, never scan a full surface per frame (cache per revision), and record before/after timings in the dev log.
|
||||
|
||||
9. **Never panic on input** (see *Never crash* above). A command's `run` closure and anything it calls must return `Err`, never panic, for *any* params or document state: validate params, check bounds before indexing or dividing, and reject absurd sizes before allocating. The `panic_hunt` integration test fuzzes every command with adversarial params and must stay green.
|
||||
10. **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
|
||||
|
||||
## 4. Picking work
|
||||
|
||||
@@ -130,7 +182,7 @@ Then append a terse entry to `log/devlog.md` (what landed, numbers, what's still
|
||||
- `docs/parity-checklist.md`: generated Photoshop menu coverage.
|
||||
- `docs/scorecard.md`: generated scorecard (sources: `scorecard/*.toml`, `perf/budgets.toml`, `perf/baseline.json`, corpus floors, prefs audit).
|
||||
- `docs/releasing.md`: cutting a release (`cargo xtask version`, the `release` branch), signing secrets, packaging scripts in `packaging/`.
|
||||
- `plan/` (local, gitignored): research, parity plan, execution plan, estimates.
|
||||
- `plan/` is an optional gitignored notebook (research, parity notes, estimates). Do not ask for it and do not stop when it is absent.
|
||||
- `log/` (local, gitignored): the dev log.
|
||||
|
||||
## 8. Keeping the native format complete
|
||||
|
||||
+7
-1
@@ -25,6 +25,7 @@ next to them.
|
||||
| `crates/ui-egui/src/i18n/vi.tsv` | Vietnamese UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ar.tsv` | Arabic UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/tr.tsv` | Turkish UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/az.tsv` | Azerbaijani (Latin script) UI translations | PhotoCraft contributors; AI contributor: OpenAI Codex | PhotoCraft English labels; Google Translate drafts with edited core terminology, contexts and plurals | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/bs.tsv` | Bosnian (Latin, Ijekavian) UI translations | Nine (@nine-codes) with Claude Code, AI-assisted; not yet reviewed by a native speaker | Original translations of PhotoCraft's English labels, shared with storytold/craft-i18n `locales/bs/` | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/sr.tsv` | Serbian (Latin, Ekavian) UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ru.tsv` | Russian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
@@ -32,10 +33,15 @@ next to them.
|
||||
| `crates/ui-egui/src/i18n/fi.tsv` | Finnish UI translations | @Janiz-zzz, @metuuu and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/da.tsv` | Danish UI translations | @pechnikov2026-star and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/nb.tsv` | Norwegian Bokmål UI translations | @nikolainyegaard, @Bolla76 and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/he.tsv` | Hebrew UI translations | @tronicum with Claude Code, AI-assisted (machine-translated); not yet reviewed by a native speaker | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ur.tsv` | Urdu UI translations | @tronicum with Claude Code, AI-assisted (machine-translated); not yet reviewed by a native speaker | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ro.tsv` | Romanian UI translations | @tronicum with Claude Code, AI-assisted (machine-translated); not yet reviewed by a native speaker | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/th.tsv` | Thai UI translations | @Thanawatttt and PhotoCraft contributors, with opencode (DeepSeek) as an AI contributor | Machine-assisted first draft from PhotoCraft's English labels, reviewed for UI terminology | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `crates/ui-egui/src/i18n/ta.tsv` | Tamil UI translations | @newsbaba24x7 and PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) |
|
||||
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
|
||||
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
|
||||
| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg` (113 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg` (115 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
|
||||
Generated
+49
@@ -3064,6 +3064,28 @@ dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_casemap"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2edfd120d8445de853cf53a1abec916f638f933a70a6f4bf8f7e2d7b7f884e9"
|
||||
dependencies = [
|
||||
"icu_casemap_data",
|
||||
"icu_collections",
|
||||
"icu_locale_core",
|
||||
"icu_properties",
|
||||
"icu_provider",
|
||||
"potential_utf",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_casemap_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "059fcda0fc8d33effc6633a8cf0d8a3c17caf7d7c91918fba9918744f501e4e8"
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.3.0"
|
||||
@@ -3072,6 +3094,7 @@ checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"potential_utf",
|
||||
"serde",
|
||||
"utf8_iter",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
@@ -5341,6 +5364,7 @@ dependencies = [
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"wat",
|
||||
"web-time",
|
||||
"winsafe",
|
||||
]
|
||||
|
||||
@@ -5504,6 +5528,7 @@ dependencies = [
|
||||
"photocraft-geom",
|
||||
"proptest",
|
||||
"rayon",
|
||||
"rustix 1.1.5",
|
||||
"serde",
|
||||
"sysinfo",
|
||||
"winsafe",
|
||||
@@ -5529,10 +5554,13 @@ name = "photocraft-tablet"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"log",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-graphics",
|
||||
"objc2-foundation 0.3.2",
|
||||
"windows",
|
||||
"wintab",
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
@@ -5574,6 +5602,8 @@ dependencies = [
|
||||
"egui_kittest",
|
||||
"epaint_default_fonts",
|
||||
"flate2",
|
||||
"icu_casemap",
|
||||
"icu_locale_core",
|
||||
"log",
|
||||
"photocraft-algo",
|
||||
"photocraft-cms",
|
||||
@@ -9206,6 +9236,25 @@ version = "0.0.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6"
|
||||
|
||||
[[package]]
|
||||
name = "wintab"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e05efdae68aa69ef1f4bc0148a5c6cf7f2bc234963a723252fd75f2f9e70d86"
|
||||
dependencies = [
|
||||
"windows",
|
||||
"wintab-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wintab-sys"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d3d0743ba07fe30ca1ccc1471ee50adf32bc70932b86a00c8f1051177950de2"
|
||||
dependencies = [
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winx"
|
||||
version = "0.36.4"
|
||||
|
||||
@@ -443,7 +443,15 @@ impl eframe::App for WebShell {
|
||||
Ok(bytes) => {
|
||||
if place {
|
||||
if let Some(doc) = target_doc {
|
||||
place_inbox.lock().unwrap_or_else(PoisonError::into_inner).push((doc, name, bytes));
|
||||
let mut queued = place_inbox.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let held = queued.iter().fold(0usize, |sum, (_, _, b)| sum.saturating_add(b.len()));
|
||||
// Reads that finish before the next frame drains the inbox are
|
||||
// bounded like the app's own drop queue.
|
||||
if photocraft_ui_egui::file_open::place_inbox_takes(queued.len(), held, bytes.len()) {
|
||||
queued.push((doc, name, bytes));
|
||||
} else {
|
||||
log::warn!("dropped file {name} wasn't placed: too many dropped files are waiting");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
inbox.lock().unwrap_or_else(PoisonError::into_inner).push((name, bytes));
|
||||
|
||||
@@ -670,6 +670,14 @@ fn main() -> eframe::Result {
|
||||
if let Some(monitor) = tablet::install_windows() {
|
||||
let _ = tablet_monitor_win.set(monitor);
|
||||
}
|
||||
// With Windows Ink disabled for the tablet, WinTab supplies the pen pressure, tilt,
|
||||
// rotation and eraser end; the vendor driver still moves the cursor.
|
||||
#[cfg(target_os = "windows")]
|
||||
if let Some(poll) =
|
||||
tablet::install_wintab(cc, &app.stylus.feed, app.session.prefs().tools.tablet_input == photocraft_engine::prefs::TabletInput::WinTab)
|
||||
{
|
||||
app.services.tablet_poll = Some(poll);
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
tablet::spawn_x11(&app.stylus.feed, display);
|
||||
app.services.right_button_down = tablet::right_button_service();
|
||||
@@ -1031,7 +1039,7 @@ mod tests {
|
||||
read
|
||||
};
|
||||
|
||||
let r = read(r#"{"interface":{"enableAnimations":"nope"},"integrations":{"allowAgentControl":false,"controlPort":7878}}"#);
|
||||
let r = read(r#"{"interface":{"showTooltips":"nope"},"integrations":{"allowAgentControl":false,"controlPort":7878}}"#);
|
||||
assert!(!r.allow_agent_control, "a bad value in another section");
|
||||
assert_eq!(r.control_port, 7878);
|
||||
let r = read(r#"{"integrations":{"allowAgentControl":false,"controlPort":"x"}}"#);
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
//! each sample into the UI's [`StylusFeed`], where the canvas reads it exactly like the web runner's
|
||||
//! Pointer Events and automation's simulated pen. On Windows, winit forwards `WM_POINTER` pressure
|
||||
//! as touch force, but drops `PEN_FLAG_BARREL` (`0x0001`); `photocraft-tablet` recovers the barrel
|
||||
//! button through a thread-local message hook beside winit.
|
||||
//! button through a thread-local message hook beside winit. With Windows Ink disabled for the
|
||||
//! tablet, the optional WinTab mode reads pressure, tilt, rotation and the eraser end from a
|
||||
//! WinTab 1.4 system context instead ([`install_wintab`]).
|
||||
//!
|
||||
//! Wayland compositors give a pen only to clients that bind the tablet protocol
|
||||
//! (`zwp_tablet_v2`), which winit 0.30 doesn't (and binding it on winit's connection needs
|
||||
@@ -39,6 +41,41 @@ pub fn install_windows() -> Option<photocraft_tablet::windows::Monitor> {
|
||||
photocraft_tablet::windows::Monitor::install().map_err(|e| log::warn!("{e}")).ok()
|
||||
}
|
||||
|
||||
/// Installs the WinTab backend on the real PhotoCraft window and returns its per-frame poll.
|
||||
///
|
||||
/// `enabled` is Preferences > Tools > Pen Tablet > Tablet input set to WinTab. With Windows Ink disabled there, the vendor
|
||||
/// driver still moves the cursor; this backend only supplies pressure/tilt/rotation/eraser
|
||||
/// through the normal stylus feed. On failure it logs why and leaves Windows Ink untouched.
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn install_wintab(cc: &eframe::CreationContext<'_>, feed: &StylusFeed, enabled: bool) -> Option<photocraft_ui_egui::TabletPollFn> {
|
||||
if !enabled {
|
||||
return None;
|
||||
}
|
||||
use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle};
|
||||
let hwnd = match cc.window_handle().ok()?.as_raw() {
|
||||
RawWindowHandle::Win32(handle) => handle.hwnd.get(),
|
||||
_ => return None,
|
||||
};
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
if let Err(error) = photocraft_tablet::wintab::install(hwnd, Box::new(move || ctx.request_repaint())) {
|
||||
log::warn!("WinTab backend: {error}");
|
||||
return None;
|
||||
}
|
||||
let sink = sink(feed.clone());
|
||||
log::info!("WinTab backend active (system context)");
|
||||
let logged = std::cell::Cell::new(false);
|
||||
Some(Box::new(move |focused| {
|
||||
photocraft_tablet::wintab::poll(focused, &|sample| {
|
||||
if let Some(sample) = sample
|
||||
&& !logged.replace(true)
|
||||
{
|
||||
log::info!("WinTab sample: pressure={:.3} tilt=({:.1},{:.1}) eraser={}", sample.pressure, sample.tilt_x, sample.tilt_y, sample.eraser);
|
||||
}
|
||||
sink(sample);
|
||||
});
|
||||
}))
|
||||
}
|
||||
|
||||
/// Stylus barrel button down check (Windows). The right mouse button is left to egui, which
|
||||
/// reports the logical secondary button (swapped buttons included) for the app's own window only.
|
||||
#[cfg(target_os = "windows")]
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M12 17v5" />
|
||||
<path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 450 B |
@@ -0,0 +1,14 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
|
||||
<path d="M3 3v5h5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 297 B |
@@ -201,6 +201,9 @@ sync_github_name = true
|
||||
real_name = "Guillem Hermida"
|
||||
sync_github_name = true
|
||||
|
||||
[people.fokas-hoa]
|
||||
display_name = "Tasos Fokas"
|
||||
|
||||
[people.fjamesprice]
|
||||
sync_github_name = true
|
||||
|
||||
|
||||
@@ -65,10 +65,6 @@ pub(super) fn fit(pts: &[Pt], closed: bool, s: &Settings) -> Vec<Pt> {
|
||||
let mut keep: Vec<usize> = if closed { corners.clone() } else { std::iter::once(0).chain(corners.iter().copied()).chain(std::iter::once(n - 1)).collect() };
|
||||
keep.sort_unstable();
|
||||
keep.dedup();
|
||||
let mut is_corner = vec![false; n];
|
||||
for &k in &keep {
|
||||
is_corner[k] = true;
|
||||
}
|
||||
if closed && keep.len() < 2 {
|
||||
// A smooth loop: split it at two far-apart points (not corners) to simplify each half.
|
||||
let a = keep.first().copied().unwrap_or(0);
|
||||
@@ -92,8 +88,6 @@ pub(super) fn fit(pts: &[Pt], closed: bool, s: &Settings) -> Vec<Pt> {
|
||||
verts.push(n - 1);
|
||||
}
|
||||
let v: Vec<Pt> = verts.iter().map(|&i| p[i]).collect();
|
||||
let corner: Vec<bool> = verts.iter().map(|&i| is_corner[i]).collect();
|
||||
let _ = &corner;
|
||||
let mut out = v.clone();
|
||||
if closed {
|
||||
out.extend(v.first().copied());
|
||||
|
||||
@@ -303,7 +303,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_images_stop_before_the_transpose_and_row_passes() {
|
||||
fn empty_images_trace_to_nothing() {
|
||||
for r in [Rect::new(0, 0, 0, 4), Rect::new(0, 0, 4, 0), Rect::new(0, 0, 0, 0)] {
|
||||
let t = trace(&[], r, &settings(4, 2.0, 1.0));
|
||||
assert!(t.regions.is_empty());
|
||||
|
||||
@@ -44,8 +44,8 @@ pub(super) fn components(labels: &[u8], w: usize, h: usize) -> (Vec<u32>, usize)
|
||||
(comp, n as usize)
|
||||
}
|
||||
|
||||
/// Merges small and sliver components into their neighbours. Returns each pixel's region and
|
||||
/// each region's mean colour.
|
||||
/// Merges components smaller than the Edge Simplicity area into the neighbour they share the most
|
||||
/// border with. Returns each pixel's region and each region's mean colour.
|
||||
pub(super) fn merge_regions(comp: &[u32], n: usize, c: &[Px], w: usize, h: usize, s: &Settings) -> (Vec<u32>, Vec<Px>) {
|
||||
let mut area = vec![0u32; n];
|
||||
let mut sum = vec![[0.0f64; 3]; n];
|
||||
|
||||
+200
-54
@@ -393,62 +393,105 @@ fn resize_controlled(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Op
|
||||
canvas = canvas.map(|c| scaled_rect(c, p.sx, p.sy));
|
||||
cur = Some(next);
|
||||
}
|
||||
let mut out = cur.unwrap_or_else(|| s.clone());
|
||||
let mut out = preserve_details(cur.unwrap_or_else(|| s.clone()), filter, sx, sy);
|
||||
out.prune();
|
||||
out
|
||||
}
|
||||
|
||||
/// Preserve Details' light sharpening of an enlargement (Lanczos's output, for the other filters
|
||||
/// nothing).
|
||||
fn preserve_details(mut out: Surface, filter: Resample, sx: f64, sy: f64) -> Surface {
|
||||
if filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0) {
|
||||
let dst = out.content_bounds();
|
||||
let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 };
|
||||
let area = crate::output_area(&p, dst, dst, None);
|
||||
out = crate::apply(&out, &p, area, dst, None);
|
||||
}
|
||||
out.prune();
|
||||
out
|
||||
}
|
||||
|
||||
/// One pass. With `canvas`, the content and the canvas repeat their edge outwards (see
|
||||
/// [`resize_surface_in_canvas`]).
|
||||
fn resize_pass(s: &Surface, pass: Pass, canvas: Option<Rect>, budget: usize, ctl: &photocraft_raster::Interrupt) -> Surface {
|
||||
let Pass { sx, sy, kx, ky } = pass;
|
||||
let edge = canvas.map(|c| s.content_bounds().union(&c)).filter(|a| !a.is_empty());
|
||||
let fmt = s.format();
|
||||
let mut out = Surface::with_default(fmt, &s.default_pixel());
|
||||
let src = s.content_bounds();
|
||||
let dst = scaled_rect(src, sx, sy);
|
||||
if dst.is_empty() {
|
||||
return out;
|
||||
/// Output rows computed together by [`PassState::band`].
|
||||
const BAND: usize = 64;
|
||||
|
||||
/// One pass prepared: its taps and the constants every band needs. [`PassState::band`] computes
|
||||
/// one band of output rows from the source, so the parallel loop of [`resize_pass`] and
|
||||
/// [`ResizeSteps`] run the same code and give the same pixels.
|
||||
struct PassState {
|
||||
n: usize,
|
||||
alpha: bool,
|
||||
/// The output extent.
|
||||
dst: Rect,
|
||||
/// The area every tap is clamped into (the source's content, or with a canvas that and the canvas).
|
||||
area: Rect,
|
||||
hx: Vec<Taps>,
|
||||
vy: Vec<Taps>,
|
||||
x_lo: i32,
|
||||
x_hi: i32,
|
||||
def: Vec<f32>,
|
||||
/// A source row of nothing but the default pixel, after the horizontal pass.
|
||||
def_row: Vec<f32>,
|
||||
rows_per_read: i32,
|
||||
}
|
||||
|
||||
impl PassState {
|
||||
/// Prepares `pass` over `s`; `None` when the output is empty. With `canvas`, the content and
|
||||
/// the canvas repeat their edge outwards (see [`resize_surface_in_canvas`]).
|
||||
fn new(s: &Surface, pass: Pass, canvas: Option<Rect>, budget: usize) -> Option<Self> {
|
||||
let Pass { sx, sy, kx, ky } = pass;
|
||||
let edge = canvas.map(|c| s.content_bounds().union(&c)).filter(|a| !a.is_empty());
|
||||
let fmt = s.format();
|
||||
let src = s.content_bounds();
|
||||
let dst = scaled_rect(src, sx, sy);
|
||||
if dst.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let n = fmt.channels();
|
||||
let alpha = fmt.alpha;
|
||||
// With `edge`, every tap is clamped into the edge area, which holds the content.
|
||||
let area = edge.unwrap_or(src);
|
||||
let hx = taps(dst.x0, dst.x1, sx, kx, edge.map(|r| (r.x0, r.x1 - 1)), (area.x0, area.x1 - 1));
|
||||
let vy = taps(dst.y0, dst.y1, sy, ky, edge.map(|r| (r.y0, r.y1 - 1)), (area.y0, area.y1 - 1));
|
||||
let x_lo = hx.iter().filter(|t| !t.weights.is_empty()).map(|t| t.start).min().unwrap_or(area.x0);
|
||||
let x_hi = hx.iter().map(|t| t.start + t.weights.len() as i32).max().unwrap_or(area.x0).max(x_lo);
|
||||
let mut def = s.default_pixel();
|
||||
premultiply(&mut def, n, alpha);
|
||||
let dw = dst.width() as usize;
|
||||
let mut st = Self { n, alpha, dst, area, hx, vy, x_lo, x_hi, def, def_row: Vec::new(), rows_per_read: 1 };
|
||||
st.def_row = {
|
||||
let row: Vec<f32> = st.def.iter().copied().cycle().take((x_hi - x_lo) as usize * n).collect();
|
||||
let mut out = vec![0.0f32; dw * n];
|
||||
st.horizontal(&row, &mut out);
|
||||
out
|
||||
};
|
||||
// At most one tile row per read anyway, so this always fits an `i32`.
|
||||
st.rows_per_read = (budget / ((x_hi - x_lo).max(1) as usize * n).max(dw * n)).clamp(1, TILE_SIZE as usize) as i32;
|
||||
Some(st)
|
||||
}
|
||||
let n = fmt.channels();
|
||||
let alpha = fmt.alpha;
|
||||
// With `edge`, every tap is clamped into the edge area, which holds the content.
|
||||
let area = edge.unwrap_or(src);
|
||||
let hx = taps(dst.x0, dst.x1, sx, kx, edge.map(|r| (r.x0, r.x1 - 1)), (area.x0, area.x1 - 1));
|
||||
let vy = taps(dst.y0, dst.y1, sy, ky, edge.map(|r| (r.y0, r.y1 - 1)), (area.y0, area.y1 - 1));
|
||||
let x_lo = hx.iter().filter(|t| !t.weights.is_empty()).map(|t| t.start).min().unwrap_or(area.x0);
|
||||
let x_hi = hx.iter().map(|t| t.start + t.weights.len() as i32).max().unwrap_or(area.x0).max(x_lo);
|
||||
let mut def = s.default_pixel();
|
||||
premultiply(&mut def, n, alpha);
|
||||
let dw = dst.width() as usize;
|
||||
const BAND: usize = 64;
|
||||
let bands: Vec<(usize, usize)> = (0..vy.len()).step_by(BAND).map(|b| (b, (b + BAND).min(vy.len()))).collect();
|
||||
// Horizontal pass of one source row (`row` spans `x_lo..x_hi`) into `dw` samples.
|
||||
let horizontal = |row: &[f32], out: &mut [f32]| match n {
|
||||
1 => horizontal_fixed::<1>(row, out, &hx, x_lo, &def),
|
||||
2 => horizontal_fixed::<2>(row, out, &hx, x_lo, &def),
|
||||
3 => horizontal_fixed::<3>(row, out, &hx, x_lo, &def),
|
||||
4 => horizontal_fixed::<4>(row, out, &hx, x_lo, &def),
|
||||
5 => horizontal_fixed::<5>(row, out, &hx, x_lo, &def),
|
||||
_ => horizontal_dynamic(row, out, &hx, x_lo, &def, n),
|
||||
};
|
||||
// A source row of nothing but the default pixel, after the horizontal pass.
|
||||
let def_row = {
|
||||
let row: Vec<f32> = def.iter().copied().cycle().take((x_hi - x_lo) as usize * n).collect();
|
||||
let mut out = vec![0.0f32; dw * n];
|
||||
horizontal(&row, &mut out);
|
||||
out
|
||||
};
|
||||
// At most one tile row per read anyway, so this always fits an `i32`.
|
||||
let rows_per_read = (budget / ((x_hi - x_lo).max(1) as usize * n).max(dw * n)).clamp(1, TILE_SIZE as usize) as i32;
|
||||
let run = |&(b0, b1): &(usize, usize)| -> (Rect, Vec<f32>) {
|
||||
let band = vy.get(b0..b1).unwrap_or(&[]);
|
||||
|
||||
/// How many bands of [`BAND`] output rows the pass has.
|
||||
fn bands(&self) -> usize {
|
||||
self.vy.len().div_ceil(BAND)
|
||||
}
|
||||
|
||||
/// Horizontal pass of one source row (`row` spans `x_lo..x_hi`) into `dw` samples.
|
||||
fn horizontal(&self, row: &[f32], out: &mut [f32]) {
|
||||
let (hx, x_lo, def) = (&self.hx, self.x_lo, &self.def);
|
||||
match self.n {
|
||||
1 => horizontal_fixed::<1>(row, out, hx, x_lo, def),
|
||||
2 => horizontal_fixed::<2>(row, out, hx, x_lo, def),
|
||||
3 => horizontal_fixed::<3>(row, out, hx, x_lo, def),
|
||||
4 => horizontal_fixed::<4>(row, out, hx, x_lo, def),
|
||||
5 => horizontal_fixed::<5>(row, out, hx, x_lo, def),
|
||||
_ => horizontal_dynamic(row, out, hx, x_lo, def, self.n),
|
||||
}
|
||||
}
|
||||
|
||||
/// Band `b` of the output: its rectangle and samples, from the pass's source `s`.
|
||||
fn band(&self, s: &Surface, b: usize) -> (Rect, Vec<f32>) {
|
||||
let (n, alpha, area, dst, x_lo, x_hi) = (self.n, self.alpha, self.area, self.dst, self.x_lo, self.x_hi);
|
||||
let dw = dst.width() as usize;
|
||||
let (b0, b1) = (b * BAND, ((b + 1) * BAND).min(self.vy.len()));
|
||||
let band = self.vy.get(b0..b1).unwrap_or(&[]);
|
||||
let y_lo = band.iter().filter(|t| !t.weights.is_empty()).map(|t| t.start).min().unwrap_or(area.y0);
|
||||
let y_hi = band.iter().map(|t| t.start + t.weights.len() as i32).max().unwrap_or(area.y0).max(y_lo);
|
||||
let mut res = vec![0.0f32; band.len() * dw * n];
|
||||
@@ -472,7 +515,7 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option<Rect>, budget: usize, ctl
|
||||
if s.has_tiles_in(Rect::new(x_lo, y, x_hi, y1)) {
|
||||
let mut c0 = y;
|
||||
while c0 < y1 {
|
||||
let c1 = (c0 + rows_per_read).min(y1);
|
||||
let c1 = (c0 + self.rows_per_read).min(y1);
|
||||
let read = Rect::new(x_lo, c0, x_hi, c1);
|
||||
s.read_region_into(read, &mut rows);
|
||||
premultiply(&mut rows, n, alpha);
|
||||
@@ -480,7 +523,7 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option<Rect>, budget: usize, ctl
|
||||
hrows.resize((c1 - c0) as usize * dw * n, 0.0);
|
||||
let rw = read.width() as usize * n;
|
||||
for (row, out) in rows.chunks_exact(rw.max(1)).zip(hrows.chunks_exact_mut(dw * n)) {
|
||||
horizontal(row, out);
|
||||
self.horizontal(row, out);
|
||||
}
|
||||
for (r, h) in (c0..c1).zip(hrows.chunks_exact(dw * n)) {
|
||||
add(&mut res, r, h);
|
||||
@@ -494,7 +537,7 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option<Rect>, budget: usize, ctl
|
||||
let (a, b) = ((y - t.start).max(0) as usize, (y1 - t.start).max(0) as usize);
|
||||
let w: f32 = t.weights.get(a.min(t.weights.len())..b.min(t.weights.len())).unwrap_or(&[]).iter().sum();
|
||||
if w != 0.0 {
|
||||
for (dv, sv) in d.iter_mut().zip(&def_row) {
|
||||
for (dv, sv) in d.iter_mut().zip(&self.def_row) {
|
||||
*dv += sv * w;
|
||||
}
|
||||
}
|
||||
@@ -503,7 +546,7 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option<Rect>, budget: usize, ctl
|
||||
y = y1;
|
||||
}
|
||||
for (t, d) in band.iter().zip(res.chunks_exact_mut(dw * n)) {
|
||||
for (dv, sv) in d.iter_mut().zip(&def_row) {
|
||||
for (dv, sv) in d.iter_mut().zip(&self.def_row) {
|
||||
*dv += sv * t.outside;
|
||||
}
|
||||
}
|
||||
@@ -514,7 +557,15 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option<Rect>, budget: usize, ctl
|
||||
}
|
||||
unpremultiply(&mut res, n, alpha);
|
||||
(Rect::new(dst.x0, dst.y0 + b0 as i32, dst.x1, dst.y0 + b1 as i32), res)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass. With `canvas`, the content and the canvas repeat their edge outwards (see
|
||||
/// [`resize_surface_in_canvas`]).
|
||||
fn resize_pass(s: &Surface, pass: Pass, canvas: Option<Rect>, budget: usize, ctl: &photocraft_raster::Interrupt) -> Surface {
|
||||
let mut out = Surface::with_default(s.format(), &s.default_pixel());
|
||||
let Some(st) = PassState::new(s, pass, canvas, budget) else { return out };
|
||||
let bands: Vec<usize> = (0..st.bands()).collect();
|
||||
// Bands go into the output a group at a time, so the `f32` rows held at once are bounded by
|
||||
// the group, not by the whole destination (#1544).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -523,15 +574,15 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option<Rect>, budget: usize, ctl
|
||||
let group = 1;
|
||||
for chunk in bands.chunks(group) {
|
||||
if ctl.cancelled() {
|
||||
return Surface::new(fmt);
|
||||
return Surface::new(s.format());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let parts: Vec<(Rect, Vec<f32>)> = {
|
||||
use rayon::prelude::*;
|
||||
chunk.par_iter().map(run).collect()
|
||||
chunk.par_iter().map(|&b| st.band(s, b)).collect()
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let parts: Vec<(Rect, Vec<f32>)> = chunk.iter().map(run).collect();
|
||||
let parts: Vec<(Rect, Vec<f32>)> = chunk.iter().map(|&b| st.band(s, b)).collect();
|
||||
for (r, d) in parts {
|
||||
out.write_region(r, &d);
|
||||
}
|
||||
@@ -539,6 +590,101 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option<Rect>, budget: usize, ctl
|
||||
out
|
||||
}
|
||||
|
||||
/// [`resize_surface`] (or, with a canvas, [`resize_surface_in_canvas`]) in resumable steps, for a
|
||||
/// caller that cannot block, such as the web build with no threads: [`ResizeSteps::step`] computes
|
||||
/// bands of output rows until the caller says to stop, and returns the surface once they are all
|
||||
/// done. It runs [`resize_with_budget`]'s passes and [`resize_pass`]'s bands through the same
|
||||
/// code, so its result equals [`resize_surface`]'s.
|
||||
pub struct ResizeSteps {
|
||||
/// The current pass's source: the input, then each pass's output.
|
||||
src: Surface,
|
||||
passes: std::vec::IntoIter<Pass>,
|
||||
total: usize,
|
||||
canvas: Option<Rect>,
|
||||
filter: Resample,
|
||||
scale: (f64, f64),
|
||||
run: Option<PassRun>,
|
||||
/// Final pruning must yield too: sparse output can contain many default-filled tiles.
|
||||
prune: Option<photocraft_raster::PruneCursor>,
|
||||
}
|
||||
|
||||
/// The pass being computed by [`ResizeSteps`].
|
||||
struct PassRun {
|
||||
pass: Pass,
|
||||
state: PassState,
|
||||
out: Surface,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl ResizeSteps {
|
||||
/// Resizes `src` by `(sx, sy)` about the document origin, as [`resize_surface`] (no `canvas`)
|
||||
/// or [`resize_surface_in_canvas`] does.
|
||||
pub fn new(src: Surface, sx: f64, sy: f64, filter: Resample, canvas: Option<Rect>) -> Self {
|
||||
let passes = plan(filter, sx, sy);
|
||||
Self { src, total: passes.len(), passes: passes.into_iter(), canvas, filter, scale: (sx, sy), run: None, prune: None }
|
||||
}
|
||||
|
||||
/// How far along it is, `0.0..=1.0`: whole passes plus the bands done of the current one.
|
||||
pub fn progress(&self) -> f32 {
|
||||
let done = self.total.saturating_sub(self.passes.len() + usize::from(self.run.is_some()));
|
||||
let part = self.run.as_ref().map_or(0.0, |r| r.next as f32 / r.state.bands().max(1) as f32);
|
||||
((done as f32 + part) / self.total.max(1) as f32).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Does at least one unit of work (planning a pass, one band of 64 output rows, or the
|
||||
/// closing prune batch) and goes on while `more()` returns true. `Some` once the resize is done.
|
||||
pub fn step(&mut self, more: &mut dyn FnMut() -> bool) -> Option<Surface> {
|
||||
loop {
|
||||
match self.run.take() {
|
||||
None => {
|
||||
if let Some(pass) = self.passes.next() {
|
||||
let out = Surface::with_default(self.src.format(), &self.src.default_pixel());
|
||||
match PassState::new(&self.src, pass, self.canvas, READ_BUDGET) {
|
||||
Some(state) => self.run = Some(PassRun { pass, state, out, next: 0 }),
|
||||
None => self.advance(out, pass),
|
||||
}
|
||||
} else if let Some(out) = self.finish_step() {
|
||||
return Some(out);
|
||||
}
|
||||
}
|
||||
Some(mut run) if run.next < run.state.bands() => {
|
||||
let (r, data) = run.state.band(&self.src, run.next);
|
||||
run.out.write_region(r, &data);
|
||||
run.next += 1;
|
||||
self.run = Some(run);
|
||||
}
|
||||
Some(run) => self.advance(run.out, run.pass),
|
||||
}
|
||||
if !more() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next pass reads this one's output.
|
||||
fn advance(&mut self, out: Surface, pass: Pass) {
|
||||
self.canvas = self.canvas.map(|c| scaled_rect(c, pass.sx, pass.sy));
|
||||
self.src = out;
|
||||
}
|
||||
|
||||
/// The last pass's output, with the same final pruning as [`resize_with_budget`], but at
|
||||
/// most four tiles per unit so a broad transparent area cannot monopolize the closing poll.
|
||||
fn finish_step(&mut self) -> Option<Surface> {
|
||||
if self.prune.is_none() {
|
||||
let placeholder = Surface::new(self.src.format());
|
||||
let out = std::mem::replace(&mut self.src, placeholder);
|
||||
self.src = preserve_details(out, self.filter, self.scale.0, self.scale.1);
|
||||
self.prune = Some(self.src.prune_cursor());
|
||||
}
|
||||
let cursor = self.prune.as_mut()?;
|
||||
if !self.src.prune_batch(cursor, 4) {
|
||||
return None;
|
||||
}
|
||||
let placeholder = Surface::new(self.src.format());
|
||||
Some(std::mem::replace(&mut self.src, placeholder))
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves a surface by whole pixels (default pixel kept).
|
||||
pub fn translate_surface(s: &Surface, dx: i32, dy: i32) -> Surface {
|
||||
s.translated(dx, dy, s.content_bounds())
|
||||
|
||||
@@ -434,3 +434,162 @@ fn controlled_resize_matches_pixels_and_discards_cancelled_work() {
|
||||
assert!(resize_surface_with_interrupt(&src, 1.7, 0.6, Resample::Bicubic, &ctl).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// Every band group of a pass asks `ctl` again, not only the start of each pass: counting the
|
||||
/// calls catches a missing per-group check, which a cancel (that fails at the first call or at the
|
||||
/// final one alike) cannot.
|
||||
#[test]
|
||||
fn controlled_resize_checks_cancellation_per_band_group() {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let src = ramp(depth);
|
||||
let calls = std::sync::atomic::AtomicUsize::new(0);
|
||||
let cancelled = || {
|
||||
calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
false
|
||||
};
|
||||
let progress = |_| {};
|
||||
let ctl = photocraft_raster::Interrupt::new(&cancelled, &progress);
|
||||
assert!(resize_surface_with_interrupt(&src, 1.7, 0.6, Resample::Bicubic, &ctl).is_ok());
|
||||
let passes = plan(Resample::Bicubic, 1.7, 0.6).len();
|
||||
let checks = calls.load(std::sync::atomic::Ordering::Relaxed);
|
||||
assert!(checks > passes + 2, "{checks} cancellation checks for {passes} passes; per-group checks are missing");
|
||||
}
|
||||
}
|
||||
|
||||
/// A pseudo-random surface of `w`×`h` in a format of `mode`, `sample` and `alpha`.
|
||||
fn noisy(w: i32, h: i32, mode: ColorMode, sample: SampleType, alpha: bool) -> Surface {
|
||||
let fmt = PixelFormat::new(mode, sample, alpha);
|
||||
let n = fmt.channels();
|
||||
let mut seed = 0x2545_f491u32;
|
||||
let v: Vec<f32> = (0..w as usize * h as usize * n)
|
||||
.map(|_| {
|
||||
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||
(seed >> 8) as f32 / (1u32 << 24) as f32
|
||||
})
|
||||
.collect();
|
||||
let mut s = Surface::new(fmt);
|
||||
s.write_region(Rect::new(0, 0, w, h), &v);
|
||||
s
|
||||
}
|
||||
|
||||
/// Drives `steps` to the end, `per_call` units of work at a time (0: unlimited); returns the
|
||||
/// surface and how many calls it took.
|
||||
fn drive(mut steps: ResizeSteps, per_call: usize) -> (Surface, usize) {
|
||||
let mut calls = 0;
|
||||
loop {
|
||||
calls += 1;
|
||||
let mut left = per_call;
|
||||
let mut more = || {
|
||||
left = left.wrapping_sub(1);
|
||||
per_call == 0 || left > 0
|
||||
};
|
||||
if let Some(s) = steps.step(&mut more) {
|
||||
return (s, calls);
|
||||
}
|
||||
assert!(calls < 10_000, "the resize never finished");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_equal_resize_surface() {
|
||||
let cases = [
|
||||
(SampleType::U8, ColorMode::Rgb, true),
|
||||
(SampleType::U16, ColorMode::Rgb, false),
|
||||
(SampleType::F32, ColorMode::Rgb, true),
|
||||
(SampleType::U8, ColorMode::Grayscale, true),
|
||||
];
|
||||
for (sample, mode, alpha) in cases {
|
||||
let src = noisy(150, 130, mode, sample, alpha);
|
||||
// Up, down, one axis each way, and enough output rows for several bands.
|
||||
for (sx, sy) in [(0.6, 0.6), (1.7, 1.7), (0.4, 2.2), (1.0, 0.5)] {
|
||||
for filter in [Resample::Bicubic, Resample::Lanczos, Resample::BicubicAutomatic, Resample::Nearest] {
|
||||
let expected = resize_surface(&src, sx, sy, filter);
|
||||
for per_call in [0, 1, 7] {
|
||||
let (got, _) = drive(ResizeSteps::new(src.clone(), sx, sy, filter, None), per_call);
|
||||
assert!(got == expected, "{sample:?} {mode:?} alpha={alpha} scale=({sx}, {sy}) {filter:?} per_call={per_call}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_equal_resize_surface_in_canvas() {
|
||||
let src = noisy(90, 70, ColorMode::Rgb, SampleType::U8, true);
|
||||
let canvas = Rect::new(0, 0, 90, 70);
|
||||
for (sx, sy) in [(0.7, 0.7), (1.9, 1.3)] {
|
||||
let expected = resize_surface_in_canvas(&src, sx, sy, Resample::Bicubic, canvas);
|
||||
let (got, _) = drive(ResizeSteps::new(src.clone(), sx, sy, Resample::Bicubic, Some(canvas)), 1);
|
||||
assert!(got == expected, "scale=({sx}, {sy})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_take_several_calls_and_report_progress() {
|
||||
let src = noisy(120, 300, ColorMode::Rgb, SampleType::U8, true);
|
||||
let mut steps = ResizeSteps::new(src, 0.9, 0.9, Resample::Bicubic, None);
|
||||
assert_eq!(steps.progress(), 0.0);
|
||||
let mut seen = Vec::new();
|
||||
let mut calls = 0;
|
||||
let out = loop {
|
||||
calls += 1;
|
||||
if let Some(s) = steps.step(&mut || false) {
|
||||
break s;
|
||||
}
|
||||
seen.push(steps.progress());
|
||||
};
|
||||
// Planning, one call per 64-row band (270 rows: five), and the closing call.
|
||||
assert!(calls >= 6, "{calls}");
|
||||
assert!(seen.windows(2).all(|w| w[0] <= w[1]), "progress goes back: {seen:?}");
|
||||
assert!(seen.iter().all(|p| (0.0..=1.0).contains(p)));
|
||||
assert_eq!(out.content_bounds(), Rect::new(0, 0, 108, 270));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steps_of_an_empty_surface_are_empty() {
|
||||
let src = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
|
||||
let expected = resize_surface(&src, 0.5, 0.5, Resample::Bicubic);
|
||||
let (got, _) = drive(ResizeSteps::new(src, 0.5, 0.5, Resample::Bicubic, None), 1);
|
||||
assert!(got == expected);
|
||||
}
|
||||
|
||||
/// A transparent image with distant opaque corners keeps broad resize bounds. Its empty
|
||||
/// output tiles must be pruned across polls rather than scanning the whole surface at once.
|
||||
#[test]
|
||||
fn sparse_resize_final_pruning_yields_between_tile_batches() {
|
||||
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
sparse_resize_final_pruning(sample);
|
||||
}
|
||||
}
|
||||
|
||||
fn sparse_resize_final_pruning(sample: SampleType) {
|
||||
let mut src = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
|
||||
for (x0, y0) in [(0, 0), (4600, 504)] {
|
||||
for y in y0..y0 + 8 {
|
||||
for x in x0..x0 + 8 {
|
||||
src.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let expected = resize_surface(&src, 0.5, 0.5, Resample::Nearest);
|
||||
let mut steps = ResizeSteps::new(src, 0.5, 0.5, Resample::Nearest, None);
|
||||
let mut polls = 0;
|
||||
while !steps.passes.as_slice().is_empty() || steps.run.is_some() {
|
||||
assert!(steps.step(&mut || false).is_none());
|
||||
polls += 1;
|
||||
assert!(polls < 100, "the resize passes did not finish");
|
||||
}
|
||||
let unpruned = steps.src.tile_count();
|
||||
assert!(unpruned >= 9, "the fixture must leave a broad output to scan: {unpruned}");
|
||||
let mut closing_polls = 0;
|
||||
let actual = loop {
|
||||
closing_polls += 1;
|
||||
if let Some(out) = steps.step(&mut || false) {
|
||||
break out;
|
||||
}
|
||||
assert!(closing_polls < 100, "the final prune did not finish");
|
||||
};
|
||||
assert!(closing_polls >= unpruned.div_ceil(4), "{unpruned} tiles were scanned in {closing_polls} closing polls");
|
||||
assert!(actual == expected, "stepped pruning must preserve pixels and remove the same empty tiles");
|
||||
assert!(actual.tile_count() < unpruned, "the fixture must include default-filled output tiles");
|
||||
}
|
||||
|
||||
@@ -661,7 +661,7 @@ mod waited_error_tests {
|
||||
fn waited_job_keeps_typed_failure() {
|
||||
let mut headless = Headless::trusted_local();
|
||||
let id = JobId(123);
|
||||
let error = photocraft_engine::EngineError::PsdHardBudget { name: "large.psd".into(), required: 9000, limit: 4000 };
|
||||
let error = photocraft_engine::EngineError::PsdHardBudget { name: "large.psd".into(), required: 9000, limit: 4000, free_memory: None };
|
||||
headless.waited.insert(
|
||||
id,
|
||||
Some(JobEvent {
|
||||
|
||||
@@ -79,12 +79,16 @@ fn attach_memory_error_details(obj: &mut Value, err: &AutomationError) {
|
||||
}
|
||||
}
|
||||
}
|
||||
AutomationError::Import(photocraft_io::IoError::PsdImportBudget { required, limit })
|
||||
| AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { required, limit, .. }) => {
|
||||
AutomationError::Import(photocraft_io::IoError::PsdImportBudget { required, limit, free_memory })
|
||||
| AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { required, limit, free_memory, .. }) => {
|
||||
if let Some(m) = obj.as_object_mut() {
|
||||
m.insert("required".into(), json!(required));
|
||||
m.insert("hard".into(), json!(limit));
|
||||
m.insert("hardLimit".into(), json!(limit));
|
||||
if let Some(free) = free_memory {
|
||||
m.insert("available".into(), json!(free));
|
||||
m.insert("availableRam".into(), json!(free));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -1092,7 +1092,12 @@ fn approve_high_memory_rejects_invalid_types_and_formats_structured_error() {
|
||||
// fields, and only the fields an approval request has: no soft limit and no capacity, since
|
||||
// no approval can raise the ceiling.
|
||||
let mut hard_obj = json!({"id": 2, "ok": false, "error": "test"});
|
||||
let hard = crate::AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { name: "big.psd".into(), required: 9000, limit: 8000 });
|
||||
let hard = crate::AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget {
|
||||
name: "big.psd".into(),
|
||||
required: 9000,
|
||||
limit: 8000,
|
||||
free_memory: None,
|
||||
});
|
||||
super::attach_memory_error_details(&mut hard_obj, &hard);
|
||||
assert_eq!(hard_obj["required"], 9000);
|
||||
assert_eq!(hard_obj["hard"], 8000);
|
||||
@@ -1100,6 +1105,20 @@ fn approve_high_memory_rejects_invalid_types_and_formats_structured_error() {
|
||||
for absent in ["soft", "softLimit", "available", "availableRam"] {
|
||||
assert!(hard_obj.get(absent).is_none(), "a hard refusal has no {absent}: {hard_obj}");
|
||||
}
|
||||
|
||||
// When measured free memory set the limit, the refusal also reports it.
|
||||
let mut low_obj = json!({"id": 3, "ok": false, "error": "test"});
|
||||
let low = crate::AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget {
|
||||
name: "big.psd".into(),
|
||||
required: 9000,
|
||||
limit: 8000,
|
||||
free_memory: Some(10_000),
|
||||
});
|
||||
super::attach_memory_error_details(&mut low_obj, &low);
|
||||
assert_eq!(low_obj["hardLimit"], 8000);
|
||||
assert_eq!(low_obj["available"], 10_000);
|
||||
assert_eq!(low_obj["availableRam"], 10_000);
|
||||
assert!(low_obj.get("soft").is_none(), "a hard refusal has no soft limit: {low_obj}");
|
||||
}
|
||||
|
||||
/// #10897: `doc.place` forwards the strict one-shot high-memory approval on both routes: the
|
||||
|
||||
@@ -514,8 +514,9 @@ fn png_result(png: &[u8], note: String) -> CallToolResult {
|
||||
}
|
||||
|
||||
/// Adds the typed byte counts of a memory refusal to an error object: an approval request keeps
|
||||
/// its soft limit, hard limit and (when known) capacity; a hard refusal keeps only its required
|
||||
/// and hard amounts, because no approval can raise that ceiling.
|
||||
/// its soft limit, hard limit and (when known) capacity; a hard refusal keeps its required and
|
||||
/// hard amounts, because no approval can raise that ceiling, and adds the free memory when
|
||||
/// measured memory set the limit.
|
||||
fn attach_memory_error_details(obj: &mut Value, err: &AutomationError) {
|
||||
let Some(obj) = obj.as_object_mut() else { return };
|
||||
match err {
|
||||
@@ -531,11 +532,15 @@ fn attach_memory_error_details(obj: &mut Value, err: &AutomationError) {
|
||||
obj.insert("availableRam".into(), json!(avail));
|
||||
}
|
||||
}
|
||||
AutomationError::Import(photocraft_io::IoError::PsdImportBudget { required, limit })
|
||||
| AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { required, limit, .. }) => {
|
||||
AutomationError::Import(photocraft_io::IoError::PsdImportBudget { required, limit, free_memory })
|
||||
| AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { required, limit, free_memory, .. }) => {
|
||||
obj.insert("required".into(), json!(required));
|
||||
obj.insert("hard".into(), json!(limit));
|
||||
obj.insert("hardLimit".into(), json!(limit));
|
||||
if let Some(free) = free_memory {
|
||||
obj.insert("available".into(), json!(free));
|
||||
obj.insert("availableRam".into(), json!(free));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -1614,7 +1619,12 @@ mod tests {
|
||||
assert!(serde_json::from_value::<PlaceParams>(json!({"path": "file.psd", "approve_high_memory": invalid})).is_err(), "{invalid}");
|
||||
}
|
||||
|
||||
let err = AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget { name: "huge.psd".into(), required: 9_000, limit: 8_000 });
|
||||
let err = AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget {
|
||||
name: "huge.psd".into(),
|
||||
required: 9_000,
|
||||
limit: 8_000,
|
||||
free_memory: None,
|
||||
});
|
||||
let res = to_result(Err(err)).unwrap();
|
||||
assert_eq!(res.is_error, Some(true));
|
||||
let text = &res.content.first().and_then(|c| c.as_text()).unwrap().text;
|
||||
@@ -1625,6 +1635,21 @@ mod tests {
|
||||
for absent in ["soft", "softLimit", "available", "availableRam"] {
|
||||
assert!(v.get(absent).is_none(), "a hard refusal has no {absent}: {v}");
|
||||
}
|
||||
|
||||
// With measured free memory behind the limit, the refusal reports it too.
|
||||
let err = AutomationError::Engine(photocraft_engine::EngineError::PsdHardBudget {
|
||||
name: "huge.psd".into(),
|
||||
required: 9_000,
|
||||
limit: 8_000,
|
||||
free_memory: Some(10_000),
|
||||
});
|
||||
let res = to_result(Err(err)).unwrap();
|
||||
let text = &res.content.first().and_then(|c| c.as_text()).unwrap().text;
|
||||
let v: Value = serde_json::from_str(text).unwrap();
|
||||
assert_eq!(v["hardLimit"], 8_000);
|
||||
assert_eq!(v["available"], 10_000);
|
||||
assert_eq!(v["availableRam"], 10_000);
|
||||
assert!(v.get("soft").is_none(), "a hard refusal has no soft limit: {v}");
|
||||
}
|
||||
|
||||
/// The MCP server applies finished jobs before every tool call too (#503).
|
||||
|
||||
@@ -745,6 +745,7 @@ fn documents_filesystem_path_params(id: &str, params: &str) -> bool {
|
||||
| "path.clippingPath.set"
|
||||
| "path.rename"
|
||||
| "path.stroke"
|
||||
| "path.toShape"
|
||||
| "type.attachToPath"
|
||||
| "type.fillPath"
|
||||
| "type.detachFromPath"
|
||||
|
||||
+929
-276
File diff suppressed because it is too large
Load Diff
@@ -32,7 +32,8 @@ pub use crate::cicp::Cicp;
|
||||
pub use crate::codecs::exr_cryptomatte::{cryptomatte_id, cryptomatte_key, cryptomatte_preview_color};
|
||||
pub use crate::codecs::gif_frames::{AnimationFrame, MAX_GIF_FRAMES};
|
||||
pub use crate::codecs::png::{
|
||||
PngExtras, PngHeader, PngPalette, PngRowSink, PngRows, encode_indexed as encode_png_indexed, palette as png_palette, stereo as png_stereo,
|
||||
PngDecodeRows, PngExtras, PngHeader, PngPalette, PngRowSink, PngRows, SharedBytes, encode_indexed as encode_png_indexed, palette as png_palette,
|
||||
stereo as png_stereo,
|
||||
};
|
||||
pub use crate::codecs::tiff::{
|
||||
PhotoshopTags as TiffPhotoshopTags, TiffBands, photoshop_tags as tiff_photoshop_tags, writes_little_endian as tiff_writes_little_endian,
|
||||
@@ -50,7 +51,7 @@ pub use crate::options::{
|
||||
DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, JpegFormat, Limits, PngCompression, PngStereo, TIFF_PYRAMID_MIN,
|
||||
TiffCompression,
|
||||
};
|
||||
pub use crate::orientation::{exif_orientation, upright_exif, upright_xmp};
|
||||
pub use crate::orientation::{OrientSteps, exif_orientation, upright_exif, upright_xmp};
|
||||
pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution};
|
||||
pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding};
|
||||
pub use half::f16;
|
||||
@@ -99,10 +100,56 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res
|
||||
Format::Jxl => Err(CodecError::unsupported(format, "JPEG XL reading is not yet available; export is supported")),
|
||||
Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::decode(format, bytes, l),
|
||||
}?;
|
||||
finish_format(format, bytes, img, opts)
|
||||
}
|
||||
|
||||
/// What [`decode_as_with`] does with a PNG decoded in steps by [`PngDecodeRows`] (`img` is its
|
||||
/// output): the resolution from the metadata, the upright orientation and the final limit check,
|
||||
/// so the result equals [`decode_as_with`]'s on the same file.
|
||||
pub fn finish_png_decode(img: Image, opts: &DecodeOptions) -> Result<Image, CodecError> {
|
||||
match begin_png_finish(img, opts)? {
|
||||
PngFinish::Done(img) => Ok(*img),
|
||||
PngFinish::Orient(mut steps) => loop {
|
||||
if let Some(img) = steps.step(&mut || true)? {
|
||||
return Ok(img);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Where [`begin_png_finish`] leaves a decoded PNG.
|
||||
pub enum PngFinish {
|
||||
/// Finished: it was already upright (or the options keep the orientation).
|
||||
Done(Box<Image>),
|
||||
/// To be turned upright, a band of rows at a time, by driving these steps.
|
||||
Orient(Box<OrientSteps>),
|
||||
}
|
||||
|
||||
/// [`finish_png_decode`] with the turning upright (orientations 2-8) left to the caller, in
|
||||
/// bands it can pace: the resolution from the metadata and the limit checks are made here, and the
|
||||
/// result of the steps equals what [`finish_png_decode`] returns.
|
||||
pub fn begin_png_finish(mut img: Image, opts: &DecodeOptions) -> Result<PngFinish, CodecError> {
|
||||
if img.meta.dpi.is_none() {
|
||||
img.meta.dpi = resolution::from_metadata(img.meta.exif.as_deref(), img.meta.xmp.as_deref());
|
||||
}
|
||||
let o = img.meta.exif.as_deref().map_or(1, exif_orientation);
|
||||
let l = &opts.limits;
|
||||
// As `finish_decode` does: the final guard, then (turning 5-8 swaps the sides) the upright size.
|
||||
l.check(img.width(), img.height(), img.layout(), img.sample_type())?;
|
||||
if opts.keep_orientation || !(2..=8).contains(&o) {
|
||||
return Ok(PngFinish::Done(Box::new(img)));
|
||||
}
|
||||
if (5..=8).contains(&o) {
|
||||
l.check(img.height(), img.width(), img.layout(), img.sample_type())?;
|
||||
}
|
||||
Ok(PngFinish::Orient(Box::new(OrientSteps::new(img, o)?)))
|
||||
}
|
||||
|
||||
/// The steps after a decoder of `format` has produced `img` from `bytes`.
|
||||
fn finish_format(format: Format, bytes: &[u8], mut img: Image, opts: &DecodeOptions) -> Result<Image, CodecError> {
|
||||
// Without a resolution of the format's own (PNG pHYs, TIFF tags, JPEG's metadata), the
|
||||
// XMP or EXIF one counts, like Photoshop: a WebP, HEIF or PNG from a camera or phone
|
||||
// opens at its recorded resolution, not at the 72 ppi default.
|
||||
let mut img = img;
|
||||
if img.meta.dpi.is_none() && format != Format::Tiff {
|
||||
img.meta.dpi = resolution::from_metadata(img.meta.exif.as_deref(), img.meta.xmp.as_deref());
|
||||
}
|
||||
|
||||
@@ -311,6 +311,104 @@ fn orient_bytes(src: &[u8], bpp: usize, o: u16, (w, h): (usize, usize), ow: usiz
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the oriented output rows `y0..` that fit in `dst` (whole rows of `ow` pixels), `bpp`
|
||||
/// bytes per pixel: one band of [`orient_bytes`], the same pixels it writes.
|
||||
fn orient_band(src: &[u8], dst: &mut [u8], bpp: usize, o: u16, (w, h): (usize, usize), ow: usize, y0: usize) {
|
||||
macro_rules! go {
|
||||
($n:literal) => {{
|
||||
let (s, _) = src.as_chunks::<$n>();
|
||||
let (d, _) = dst.as_chunks_mut::<$n>();
|
||||
band(s, d, o, (w, h), ow, y0)
|
||||
}};
|
||||
}
|
||||
match bpp {
|
||||
1 => go!(1),
|
||||
2 => go!(2),
|
||||
3 => go!(3),
|
||||
4 => go!(4),
|
||||
5 => go!(5),
|
||||
6 => go!(6),
|
||||
8 => go!(8),
|
||||
10 => go!(10),
|
||||
12 => go!(12),
|
||||
16 => go!(16),
|
||||
_ => go!(20),
|
||||
}
|
||||
}
|
||||
|
||||
/// An image turned upright a band of rows at a time, for a caller that must not block for the
|
||||
/// whole image (the web build has no threads): [`OrientSteps::step`] gives the [`Image`]
|
||||
/// [`Image::oriented`] gives, once every band is written.
|
||||
pub struct OrientSteps {
|
||||
src: Image,
|
||||
o: u16,
|
||||
bpp: usize,
|
||||
/// The oriented size.
|
||||
ow: usize,
|
||||
oh: usize,
|
||||
out: Vec<u8>,
|
||||
/// Output rows written so far.
|
||||
done: usize,
|
||||
}
|
||||
|
||||
impl OrientSteps {
|
||||
/// Sets up turning `img` upright for orientation `o` (2–8; anything else leaves it as it is).
|
||||
/// Allocates the output, which the image is turned into beside the original.
|
||||
pub fn new(img: Image, o: u16) -> Result<Self, CodecError> {
|
||||
let (w, h) = (img.width() as usize, img.height() as usize);
|
||||
let (ow, oh) = if o >= 5 { (h, w) } else { (w, h) };
|
||||
let (layout, sample) = (img.layout(), img.sample_type());
|
||||
let bpp = layout.channels() * sample.bytes();
|
||||
let turns = (2..=8).contains(&o);
|
||||
if turns && (!matches!(bpp, 1..=6 | 8 | 10 | 12 | 16 | 20) || w == 0 || h == 0) {
|
||||
return Err(CodecError::InvalidImage(format!("cannot orient {layout:?} {sample:?} {w}x{h}")));
|
||||
}
|
||||
// Reserve without touching: `step` grows the buffer a band at a time, so no slice
|
||||
// zero-fills the whole output.
|
||||
let mut out = Vec::new();
|
||||
if turns {
|
||||
let n = img.data().len();
|
||||
out.try_reserve_exact(n).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {n} bytes to orient the image")))?;
|
||||
}
|
||||
Ok(Self { src: img, o, bpp, ow, oh, out, done: 0 })
|
||||
}
|
||||
|
||||
/// How much of the image is turned, `0.0..=1.0`.
|
||||
pub fn progress(&self) -> f32 {
|
||||
if self.oh == 0 { 1.0 } else { self.done as f32 / self.oh as f32 }
|
||||
}
|
||||
|
||||
/// Writes bands of [`BAND`] output rows, at least one, then goes on while `more()` returns
|
||||
/// true; `Some` with the upright image once the last band is written.
|
||||
pub fn step(&mut self, more: &mut dyn FnMut() -> bool) -> Result<Option<Image>, CodecError> {
|
||||
if !(2..=8).contains(&self.o) {
|
||||
let placeholder = Image::from_raw(0, 0, self.src.layout(), self.src.sample_type(), Vec::new())?;
|
||||
return Ok(Some(std::mem::replace(&mut self.src, placeholder)));
|
||||
}
|
||||
let (w, h) = (self.src.width() as usize, self.src.height() as usize);
|
||||
while self.done < self.oh {
|
||||
let rows = BAND.min(self.oh - self.done);
|
||||
let row_bytes = self.ow.checked_mul(self.bpp).ok_or_else(|| CodecError::InvalidImage("image too large".into()))?;
|
||||
let at = self.done.saturating_mul(row_bytes);
|
||||
let end = at.saturating_add(rows.saturating_mul(row_bytes));
|
||||
if self.out.len() < end {
|
||||
self.out.resize(end, 0);
|
||||
}
|
||||
let dst = self.out.get_mut(at..end).ok_or_else(|| CodecError::InvalidImage("the oriented rows are out of range".into()))?;
|
||||
orient_band(self.src.data(), dst, self.bpp, self.o, (w, h), self.ow, self.done);
|
||||
self.done += rows;
|
||||
if self.done < self.oh && !more() {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let (layout, sample) = (self.src.layout(), self.src.sample_type());
|
||||
let placeholder = Image::from_raw(0, 0, layout, sample, Vec::new())?;
|
||||
let src = std::mem::replace(&mut self.src, placeholder);
|
||||
let data = std::mem::take(&mut self.out);
|
||||
src.oriented_with(self.o, data).map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
impl Image {
|
||||
/// The image turned upright for orientation `o` (1–8; anything else is
|
||||
/// treated as 1 and returns the image unchanged). Width and height swap
|
||||
@@ -321,8 +419,7 @@ impl Image {
|
||||
return Ok(self);
|
||||
}
|
||||
let (w, h) = (self.width() as usize, self.height() as usize);
|
||||
let swap = o >= 5;
|
||||
let (ow, oh) = if swap { (h, w) } else { (w, h) };
|
||||
let ow = if o >= 5 { h } else { w };
|
||||
let (layout, sample) = (self.layout(), self.sample_type());
|
||||
let bpp = layout.channels() * sample.bytes();
|
||||
// Every layout/sample pair is 1–20 bytes per pixel and has a fixed-size path.
|
||||
@@ -330,6 +427,16 @@ impl Image {
|
||||
return Err(CodecError::InvalidImage(format!("cannot orient {layout:?} {sample:?} {w}x{h}")));
|
||||
}
|
||||
let data = orient_bytes(self.data(), bpp, o, (w, h), ow)?;
|
||||
self.oriented_with(o, data)
|
||||
}
|
||||
|
||||
/// The upright image of orientation `o` (2–8) whose turned pixels are `data`: the size,
|
||||
/// metadata and extra samples of [`Image::oriented`].
|
||||
fn oriented_with(self, o: u16, data: Vec<u8>) -> Result<Image, CodecError> {
|
||||
let (w, h) = (self.width() as usize, self.height() as usize);
|
||||
let swap = o >= 5;
|
||||
let (ow, oh) = if swap { (h, w) } else { (w, h) };
|
||||
let (layout, sample) = (self.layout(), self.sample_type());
|
||||
let mut meta = self.meta.clone();
|
||||
// Extra samples (a TIFF's alpha and spot planes, one sample a pixel) turn with the image.
|
||||
// A plane of the wrong size is left as it is: importers drop it with a warning.
|
||||
|
||||
@@ -204,6 +204,9 @@ fn png_opens_upright_for_every_orientation() {
|
||||
assert_eq!(img.dimensions(), (w as u32, h as u32), "o={o}");
|
||||
assert_eq!(img.data(), &up[..], "o={o}");
|
||||
assert_eq!(exif_orientation(img.meta.exif.as_deref().unwrap()), 1, "o={o}: metadata says upright");
|
||||
// Decoded in steps and finished by `finish_png_decode`, it is the same image.
|
||||
let stepped = PngDecodeRows::new(file.as_slice(), &Limits::default()).unwrap().step(&mut || true).unwrap().unwrap();
|
||||
assert_eq!(finish_png_decode(stepped, &DecodeOptions::default()).unwrap(), img, "o={o}: stepped");
|
||||
// Opting out keeps the stored pixels and the tag.
|
||||
let raw = decode_with(&file, &DecodeOptions { keep_orientation: true, ..Default::default() }).unwrap();
|
||||
assert_eq!((raw.dimensions(), raw.data()), ((sw as u32, sh as u32), &s[..]), "o={o}");
|
||||
@@ -211,6 +214,76 @@ fn png_opens_upright_for_every_orientation() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An image turned upright a band of rows at a time is the image `oriented` gives, for every
|
||||
/// orientation, pixel size and shape, and takes a call per band.
|
||||
#[test]
|
||||
fn orient_steps_equal_oriented() {
|
||||
for o in 1..=8u16 {
|
||||
for (layout, sample) in [
|
||||
(ChannelLayout::Gray, SampleType::U8),
|
||||
(ChannelLayout::GrayA, SampleType::U16),
|
||||
(ChannelLayout::Rgb, SampleType::U8),
|
||||
(ChannelLayout::Rgba, SampleType::U16),
|
||||
(ChannelLayout::Rgba, SampleType::F32),
|
||||
] {
|
||||
for (w, h) in [(1u32, 1u32), (7, 5), (130, 66), (65, 200)] {
|
||||
let len = w as usize * h as usize * layout.channels() * sample.bytes();
|
||||
let data: Vec<u8> = (0..len).map(|i| (i.wrapping_mul(2_654_435_761) >> 11) as u8).collect();
|
||||
let mut img = Image::from_raw(w, h, layout, sample, data).unwrap();
|
||||
img.meta.dpi = Some((100.0, 200.0));
|
||||
img.meta.exif = Some(exif(u32::from(o), false, false));
|
||||
let want = img.clone().oriented(o).unwrap();
|
||||
let mut steps = OrientSteps::new(img, o).unwrap();
|
||||
let mut calls = 0;
|
||||
let got = loop {
|
||||
calls += 1;
|
||||
assert!(steps.progress() <= 1.0);
|
||||
if let Some(img) = steps.step(&mut || false).unwrap() {
|
||||
break img;
|
||||
}
|
||||
};
|
||||
assert_eq!(got, want, "o={o} {layout:?} {sample:?} {w}x{h}");
|
||||
let rows = if o >= 5 { w } else { h } as usize;
|
||||
let expected = if (2..=8).contains(&o) { rows.div_ceil(64) } else { 1 };
|
||||
assert_eq!(calls, expected, "o={o} {w}x{h}: one call per band of 64 rows");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A PNG turned upright in bands by `begin_png_finish` is the image `decode` gives, for every
|
||||
/// orientation, and a band of a tall image is not the whole of it.
|
||||
#[test]
|
||||
fn png_finishes_upright_in_bands_for_every_orientation() {
|
||||
let (w, h) = (70, 150);
|
||||
let up = upright(w, h, |x, y| (x * 7 + y * 13) as u8);
|
||||
for o in 1..=8u16 {
|
||||
let (s, sw, sh) = stored(&up, w, h, o);
|
||||
let png = encode(&gray(sw, sh, s), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let file = png_with_exif(&png, &exif(u32::from(o), o % 2 == 0, false));
|
||||
let want = decode(&file).unwrap();
|
||||
let img = PngDecodeRows::new(file.as_slice(), &Limits::default()).unwrap().step(&mut || true).unwrap().unwrap();
|
||||
let got = match begin_png_finish(img, &DecodeOptions::default()).unwrap() {
|
||||
PngFinish::Done(img) => {
|
||||
assert_eq!(o, 1);
|
||||
*img
|
||||
}
|
||||
PngFinish::Orient(mut steps) => {
|
||||
assert!(o > 1);
|
||||
let mut calls = 0;
|
||||
loop {
|
||||
calls += 1;
|
||||
if let Some(img) = steps.step(&mut || false).unwrap() {
|
||||
assert!(calls > 1, "o={o}: more than one band");
|
||||
break img;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
assert_eq!(got, want, "o={o}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Extra samples (a TIFF's alpha and spot planes) turn with the image, so a channel stays
|
||||
/// aligned with the pixels for every orientation.
|
||||
#[test]
|
||||
|
||||
@@ -195,6 +195,279 @@ fn tiff_f32_output_matches_oracle() {
|
||||
assert_eq!(o, img.to_f32_samples().unwrap());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PNG decoded in steps (PngDecodeRows)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Decodes `bytes` with [`PngDecodeRows`], going on for `per_call` rows per call (0: unlimited);
|
||||
/// returns the image and how many calls it took.
|
||||
fn decode_in_steps(bytes: &[u8], per_call: usize) -> Result<(Image, usize), CodecError> {
|
||||
let mut rows = PngDecodeRows::new(bytes, &Limits::default())?;
|
||||
let mut calls = 0;
|
||||
loop {
|
||||
calls += 1;
|
||||
let mut left = per_call;
|
||||
let mut more = || {
|
||||
left = left.wrapping_sub(1);
|
||||
per_call == 0 || left > 0
|
||||
};
|
||||
if let Some(img) = rows.step(&mut more)? {
|
||||
return Ok((img, calls));
|
||||
}
|
||||
assert!(calls < 100_000, "the decoder never finished");
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_steps_equal_decode(bytes: &[u8], what: &str) {
|
||||
let whole = decode(bytes);
|
||||
for per_call in [1, 7, 0] {
|
||||
// `decode` also takes the resolution from EXIF or XMP and turns the image upright;
|
||||
// `finish_png_decode` does that for a stepped decode, as the stepped import does.
|
||||
let stepped = decode_in_steps(bytes, per_call).and_then(|(img, calls)| Ok((finish_png_decode(img, &DecodeOptions::default())?, calls)));
|
||||
match (&whole, stepped) {
|
||||
(Ok(a), Ok((b, _))) => assert_eq!(a, &b, "{what}, {per_call} rows per call"),
|
||||
(Err(_), Err(_)) => {}
|
||||
(a, b) => panic!("{what}, {per_call} rows per call: decode {:?}, steps {:?}", a.as_ref().map(|_| ()), b.map(|_| ())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_rows_equal_decode_in_every_layout_and_depth() {
|
||||
for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba] {
|
||||
for sample in [SampleType::U8, SampleType::U16] {
|
||||
let mut img = synth(41, 29, layout, sample, 77, 0.3).with_icc(Some(sample_icc(400)));
|
||||
img.meta.text.push(("Comment".into(), "stepped".into()));
|
||||
img.meta.dpi = Some((300.0, 300.0));
|
||||
for interlaced in [false, true] {
|
||||
let bytes = encode(&img, Format::Png, &EncodeOptions { png_interlaced: interlaced, ..Default::default() }).unwrap();
|
||||
assert_steps_equal_decode(&bytes, &format!("{layout:?} {sample:?} interlaced={interlaced}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_rows_equal_decode_for_palette_and_transparency() {
|
||||
let pal = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [9, 9, 9]];
|
||||
let idx: Vec<u8> = (0..50 * 20).map(|i| (i % 4) as u8).collect();
|
||||
let bytes = encode_png_indexed(50, 20, &idx, &pal, Some(3), None, None).unwrap();
|
||||
assert_steps_equal_decode(&bytes, "palette with a transparent entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_rows_take_one_call_per_row_and_report_progress() {
|
||||
let bytes = encode(&synth(16, 40, ChannelLayout::Rgb, SampleType::U8, 5, 0.2), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let mut rows = PngDecodeRows::new(bytes.as_slice(), &Limits::default()).unwrap();
|
||||
assert_eq!(rows.size(), (16, 40));
|
||||
assert_eq!(rows.progress(), 0.0);
|
||||
let mut seen = Vec::new();
|
||||
let img = loop {
|
||||
if let Some(img) = rows.step(&mut || false).unwrap() {
|
||||
break img;
|
||||
}
|
||||
seen.push(rows.progress());
|
||||
};
|
||||
assert_eq!(seen.len(), 39, "one call per row but the last, which also finishes the file");
|
||||
assert!(seen.windows(2).all(|w| w[0] < w[1]));
|
||||
assert_eq!(rows.progress(), 1.0);
|
||||
assert_eq!(img, decode(&bytes).unwrap());
|
||||
// A decoder that has finished says so instead of decoding again.
|
||||
assert!(rows.step(&mut || true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_rows_share_their_bytes_without_copying_them() {
|
||||
let bytes = std::sync::Arc::new(encode(&synth(20, 20, ChannelLayout::Rgba, SampleType::U8, 3, 0.2), Format::Png, &EncodeOptions::default()).unwrap());
|
||||
let mut rows = PngDecodeRows::new(SharedBytes(bytes.clone()), &Limits::default()).unwrap();
|
||||
let img = rows.step(&mut || true).unwrap().unwrap();
|
||||
assert_eq!(img, decode(&bytes).unwrap());
|
||||
drop(rows);
|
||||
assert_eq!(std::sync::Arc::strong_count(&bytes), 1, "the decoder let go of the bytes");
|
||||
}
|
||||
|
||||
/// A CRC-valid PNG chunk.
|
||||
fn png_chunk(kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
|
||||
let mut crc = flate2::Crc::new();
|
||||
crc.update(kind);
|
||||
crc.update(data);
|
||||
let mut out = u32::try_from(data.len()).unwrap().to_be_bytes().to_vec();
|
||||
out.extend_from_slice(kind);
|
||||
out.extend_from_slice(data);
|
||||
out.extend_from_slice(&crc.sum().to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn zlib(text: &[u8]) -> Vec<u8> {
|
||||
use std::io::Write;
|
||||
let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
encoder.write_all(text).unwrap();
|
||||
encoder.finish().unwrap()
|
||||
}
|
||||
|
||||
/// A `zTXt` chunk (`deflated`) or a compressed `iTXt` one (`!deflated`) with `text` as its value.
|
||||
fn png_text_chunk(kind: &[u8; 4], keyword: &[u8], text: &[u8]) -> Vec<u8> {
|
||||
let mut data = keyword.to_vec();
|
||||
data.push(0);
|
||||
if kind == b"zTXt" {
|
||||
data.push(0);
|
||||
} else {
|
||||
data.extend_from_slice(&[1, 0, 0, 0]);
|
||||
}
|
||||
data.extend_from_slice(&zlib(text));
|
||||
png_chunk(kind, &data)
|
||||
}
|
||||
|
||||
/// `png` with `chunks` between the image data and `IEND` (the text-after-IDAT case).
|
||||
fn with_chunks_before_iend(png: &[u8], chunks: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut at = 8;
|
||||
loop {
|
||||
let len = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize;
|
||||
if &png[at + 4..at + 8] == b"IEND" {
|
||||
let mut out = png[..at].to_vec();
|
||||
for c in chunks {
|
||||
out.extend_from_slice(c);
|
||||
}
|
||||
out.extend_from_slice(&png[at..]);
|
||||
return out;
|
||||
}
|
||||
at += len + 12;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_rows_read_compressed_text_in_bounded_batches() {
|
||||
let img = synth(19, 23, ChannelLayout::Rgba, SampleType::U8, 9, 0.4);
|
||||
let base = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let text = "A".repeat(150_000);
|
||||
for kind in [b"zTXt", b"iTXt"] {
|
||||
let bytes = with_chunks_before_iend(&base, &[png_text_chunk(kind, b"Comment", text.as_bytes())]);
|
||||
let mut rows = PngDecodeRows::new(bytes.as_slice(), &Limits::default()).unwrap();
|
||||
let mut calls = 0;
|
||||
// An empty budget: every step reads one bounded batch and stops.
|
||||
let stepped = loop {
|
||||
calls += 1;
|
||||
if let Some(img) = rows.step(&mut || false).unwrap() {
|
||||
break img;
|
||||
}
|
||||
assert!(calls < 100_000, "the decoder never finished");
|
||||
};
|
||||
assert_eq!(stepped, decode(&bytes).unwrap(), "{kind:?}");
|
||||
assert_eq!(stepped.meta.text, vec![("Comment".into(), text.clone())], "{kind:?}: the whole value is kept");
|
||||
assert!(calls > 20, "{kind:?}: {calls} bounded calls, not one blocking pass");
|
||||
assert_steps_equal_decode(&bytes, &format!("compressed {kind:?} text"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An Adam7 image whose compressed text needs many metadata yields: the pixels are decoded
|
||||
/// once, before the first yield, and later steps only read text.
|
||||
#[test]
|
||||
fn png_rows_finish_adam7_text_in_bounded_batches() {
|
||||
let img = synth(19, 23, ChannelLayout::Rgba, SampleType::U8, 9, 0.4);
|
||||
let base = encode(&img, Format::Png, &EncodeOptions { png_interlaced: true, ..Default::default() }).unwrap();
|
||||
let text = "A".repeat(150_000);
|
||||
for kind in [b"zTXt", b"iTXt"] {
|
||||
let bytes = with_chunks_before_iend(&base, &[png_text_chunk(kind, b"Comment", text.as_bytes())]);
|
||||
let mut rows = PngDecodeRows::new(bytes.as_slice(), &Limits::default()).unwrap();
|
||||
let mut calls = 0;
|
||||
let stepped = loop {
|
||||
calls += 1;
|
||||
if let Some(img) = rows.step(&mut || false).unwrap() {
|
||||
break img;
|
||||
}
|
||||
assert!(calls < 100_000, "the decoder never finished");
|
||||
};
|
||||
assert_eq!(stepped, decode(&bytes).unwrap(), "{kind:?}");
|
||||
assert_eq!(stepped.meta.text, vec![("Comment".into(), text.clone())], "{kind:?}: the whole value is kept");
|
||||
assert!(calls > 20, "{kind:?}: {calls} bounded calls after the one Adam7 pass");
|
||||
}
|
||||
}
|
||||
|
||||
/// An uncompressed `iTXt` chunk (`value` is its text, so its CRC covers the whole value).
|
||||
fn png_itxt_uncompressed(keyword: &[u8], value: &[u8]) -> Vec<u8> {
|
||||
let mut data = keyword.to_vec();
|
||||
data.push(0);
|
||||
data.extend_from_slice(&[0, 0, 0, 0]);
|
||||
data.extend_from_slice(value);
|
||||
png_chunk(b"iTXt", &data)
|
||||
}
|
||||
|
||||
/// The CRC of a large text chunk takes bounded batches too, before any of its value is read.
|
||||
#[test]
|
||||
fn png_rows_read_a_large_text_crc_in_bounded_batches() {
|
||||
let img = synth(5, 5, ChannelLayout::Rgb, SampleType::U8, 3, 0.2);
|
||||
let base = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let text: String = (0..300_000u32).map(|i| char::from(b'a' + (i % 26) as u8)).collect();
|
||||
let bytes = with_chunks_before_iend(&base, &[png_itxt_uncompressed(b"Comment", text.as_bytes())]);
|
||||
let mut rows = PngDecodeRows::new(bytes.as_slice(), &Limits::default()).unwrap();
|
||||
let mut calls = 0;
|
||||
let stepped = loop {
|
||||
calls += 1;
|
||||
if let Some(img) = rows.step(&mut || false).unwrap() {
|
||||
break img;
|
||||
}
|
||||
assert!(calls < 100_000, "the decoder never finished");
|
||||
};
|
||||
assert_eq!(stepped.meta.text, vec![("Comment".into(), text)]);
|
||||
assert!(calls > 60, "{calls} calls: the CRC and the value each take bounded batches");
|
||||
}
|
||||
|
||||
/// A text chunk whose CRC does not match is still dropped after its bounded CRC batches.
|
||||
#[test]
|
||||
fn png_rows_drop_a_corrupt_text_crc() {
|
||||
let img = synth(5, 5, ChannelLayout::Rgb, SampleType::U8, 3, 0.2);
|
||||
let base = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let mut chunk = png_itxt_uncompressed(b"Comment", b"not accepted");
|
||||
let at = chunk.len() - 5;
|
||||
chunk[at] ^= 0xFF;
|
||||
let bytes = with_chunks_before_iend(&base, &[chunk]);
|
||||
let stepped = decode_in_steps(&bytes, 0).unwrap().0;
|
||||
assert!(stepped.meta.text.is_empty(), "a broken CRC drops the text");
|
||||
assert_eq!(stepped, decode(&bytes).unwrap(), "the one-pass decode drops it too");
|
||||
}
|
||||
|
||||
/// An uncompressed iTXt value that is not UTF-8 is dropped without charging its bytes against
|
||||
/// the budget, even when it is larger than all of it: the previous reader checked UTF-8 first.
|
||||
#[test]
|
||||
fn png_rows_drop_invalid_uncompressed_text_before_charging_the_budget() {
|
||||
let img = synth(4, 4, ChannelLayout::Rgb, SampleType::U8, 3, 0.2);
|
||||
let base = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let mut value = vec![b'A'; 12_000];
|
||||
value[11_999] = 0xFF;
|
||||
let bytes = with_chunks_before_iend(&base, &[png_itxt_uncompressed(b"Comment", &value)]);
|
||||
let opts = DecodeOptions { limits: Limits { max_alloc: 200, ..Default::default() }, ..Default::default() };
|
||||
let mut rows = PngDecodeRows::new(bytes.as_slice(), &opts.limits).unwrap();
|
||||
let stepped = rows.step(&mut || true).unwrap().unwrap();
|
||||
let stepped = finish_png_decode(stepped, &opts).unwrap();
|
||||
assert!(stepped.meta.text.is_empty(), "invalid UTF-8 is skipped, not a budget failure");
|
||||
let whole = decode_with(&bytes, &opts).unwrap();
|
||||
assert!(whole.meta.text.is_empty(), "the one-pass decode skips it too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_rows_fail_like_decode_on_damaged_files() {
|
||||
let img = synth(64, 64, ChannelLayout::Rgb, SampleType::U8, 11, 1.0);
|
||||
for interlaced in [false, true] {
|
||||
let bytes = encode(&img, Format::Png, &EncodeOptions { png_interlaced: interlaced, ..Default::default() }).unwrap();
|
||||
// Cuts inside the signature, the IHDR chunk or the next chunk header leave no complete image.
|
||||
for cut in [8, 20, 40] {
|
||||
let truncated = bytes.get(..cut).unwrap();
|
||||
assert!(decode(truncated).is_err(), "cut at {cut} interlaced={interlaced}");
|
||||
assert!(decode_in_steps(truncated, 1).is_err(), "cut at {cut} interlaced={interlaced}");
|
||||
}
|
||||
for cut in [bytes.len() / 3, bytes.len() / 2, bytes.len() - 20] {
|
||||
assert_steps_equal_decode(bytes.get(..cut).unwrap(), &format!("cut at {cut} interlaced={interlaced}"));
|
||||
}
|
||||
// A flipped byte in the middle of the compressed data.
|
||||
let mut bad = bytes.clone();
|
||||
let mid = bad.len() / 2;
|
||||
bad[mid] ^= 0xFF;
|
||||
assert_steps_equal_decode(&bad, "a damaged byte");
|
||||
}
|
||||
assert!(decode_in_steps(&[], 1).is_err());
|
||||
assert!(decode_in_steps(b"not a png at all, just some text bytes", 1).is_err());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PngSuite corpus (repo-root corpus/pngsuite/*.png; feature `corpus`, fetched by
|
||||
// `cargo xtask corpus --all`; missing = failure)
|
||||
@@ -229,6 +502,39 @@ fn pngsuite_corpus_matches_oracle() {
|
||||
assert!(checked > 100, "{}: only {checked} PNGs compared: run `cargo xtask corpus --all`", dir.display());
|
||||
}
|
||||
|
||||
/// The preflight charges the decoded layout's bytes per pixel: a 1000×1000 Gray8 PNG (1 MB) fits a
|
||||
/// 1.5 MB budget, which the old worst-case RGBA16 preflight (8 MB) refused.
|
||||
#[test]
|
||||
fn png_preflight_uses_the_output_layout() {
|
||||
let img = synth(1000, 1000, ChannelLayout::Gray, SampleType::U8, 7, 0.5);
|
||||
let bytes = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let opts = DecodeOptions { limits: Limits { max_alloc: 1_500_000, ..Limits::none() }, ..Default::default() };
|
||||
let got = decode_with(&bytes, &opts).expect("a Gray8 image is charged 1 byte per pixel");
|
||||
assert_eq!(got.data(), img.data());
|
||||
let tight = DecodeOptions { limits: Limits { max_alloc: 900_000, ..Limits::none() }, ..Default::default() };
|
||||
assert!(decode_with(&bytes, &tight).is_err(), "the actual pixel budget still applies");
|
||||
}
|
||||
|
||||
#[cfg(feature = "corpus")]
|
||||
#[test]
|
||||
fn png_rows_equal_decode_on_the_pngsuite_corpus() {
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/pngsuite");
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
panic!("{} is missing: run `cargo xtask corpus --all`", dir.display());
|
||||
};
|
||||
let mut checked = 0;
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if p.extension().and_then(|s| s.to_str()) != Some("png") {
|
||||
continue;
|
||||
}
|
||||
let bytes = std::fs::read(&p).unwrap();
|
||||
assert_steps_equal_decode(&bytes, &p.display().to_string());
|
||||
checked += 1;
|
||||
}
|
||||
assert!(checked > 100, "{}: only {checked} PNGs compared: run `cargo xtask corpus --all`", dir.display());
|
||||
}
|
||||
|
||||
/// Row-by-row decoding gives `decode`'s pixels and metadata for every PngSuite file it takes (all
|
||||
/// but the interlaced ones), and fails where `decode` fails.
|
||||
#[cfg(feature = "corpus")]
|
||||
@@ -288,3 +594,53 @@ fn pngsuite_corpus_rows_match_the_whole_decode() {
|
||||
eprintln!("pngsuite: {streamed} streamed, {refused} refused (interlaced), {skipped} skipped (not detected as PNG)");
|
||||
assert!(streamed > 100, "only {streamed} PNGs streamed: run `cargo xtask corpus --all`");
|
||||
}
|
||||
|
||||
/// Streaming a PNG's rows a group at a time gives the pixels and metadata `decode` gives, holds
|
||||
/// only a group at a time, and stops between rows when asked.
|
||||
#[test]
|
||||
fn step_stream_gives_the_pixels_and_extras_of_decode() {
|
||||
for (layout, sample) in [(ChannelLayout::Gray, SampleType::U8), (ChannelLayout::Rgb, SampleType::U16), (ChannelLayout::Rgba, SampleType::U8)] {
|
||||
let (w, h) = (23u32, 19u32);
|
||||
let len = w as usize * h as usize * layout.channels() * sample.bytes();
|
||||
let mut img = Image::from_raw(w, h, layout, sample, (0..len).map(|i| (i.wrapping_mul(2_654_435_761) >> 11) as u8).collect()).unwrap();
|
||||
img.meta.dpi = Some((144.0, 144.0));
|
||||
img.meta.text.push(("Comment".into(), "streamed".into()));
|
||||
img.icc = Some(vec![7; 40]);
|
||||
let bytes = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let want = decode(&bytes).unwrap();
|
||||
for group in [0u32, 1, 4, 19, 64] {
|
||||
let mut dec = PngDecodeRows::new_streaming(bytes.as_slice(), &Limits::default()).unwrap();
|
||||
assert!(dec.streamable());
|
||||
assert_eq!(dec.header(), PngHeader { width: w, height: h, layout, sample });
|
||||
let (mut data, mut next, mut calls) = (Vec::new(), 0u32, 0);
|
||||
let extras = loop {
|
||||
calls += 1;
|
||||
let mut sink = |y0: u32, rows: &[u8]| -> Result<(), CodecError> {
|
||||
assert_eq!(y0, next, "{layout:?} group {group}");
|
||||
assert!(rows.len() <= group.max(1) as usize * dec_line(w, layout, sample), "a group at most");
|
||||
next += (rows.len() / dec_line(w, layout, sample)) as u32;
|
||||
data.extend_from_slice(rows);
|
||||
Ok(())
|
||||
};
|
||||
if let Some(extras) = dec.step_stream(group, &mut || false, &mut sink).unwrap() {
|
||||
break extras;
|
||||
}
|
||||
assert!(calls < 10_000);
|
||||
};
|
||||
assert!(calls > 1, "{layout:?}: stopped between rows");
|
||||
assert_eq!(data, want.data(), "{layout:?} group {group}: pixels");
|
||||
assert_eq!((extras.icc.as_deref(), extras.meta.dpi, &extras.meta.text), (want.icc.as_deref(), want.meta.dpi, &want.meta.text));
|
||||
assert_eq!(extras.orientation, 1);
|
||||
assert!(dec.step_stream::<CodecError>(group, &mut || true, &mut |_, _| Ok(())).is_err(), "spent");
|
||||
}
|
||||
}
|
||||
// An interlaced file doesn't stream.
|
||||
let img = Image::from_raw(9, 9, ChannelLayout::Gray, SampleType::U8, vec![1; 81]).unwrap();
|
||||
let bytes = encode(&img, Format::Png, &EncodeOptions { png_interlaced: true, ..Default::default() }).unwrap();
|
||||
assert!(!PngDecodeRows::new_streaming(bytes.as_slice(), &Limits::default()).unwrap().streamable());
|
||||
}
|
||||
|
||||
/// Bytes per row of `w` pixels.
|
||||
fn dec_line(w: u32, layout: ChannelLayout, sample: SampleType) -> usize {
|
||||
w as usize * layout.channels() * sample.bytes()
|
||||
}
|
||||
|
||||
@@ -2143,6 +2143,21 @@ fn shapeless_effects_render_the_same_in_bands_and_parts() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The interruptible composite renders band by band: with shapeless effects (whose maps are built
|
||||
/// per band) it still gives the whole-document composite.
|
||||
#[test]
|
||||
fn interruptible_composite_with_shapeless_effects_matches_the_whole_composite() {
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let d = shapeless_fx_doc(depth);
|
||||
let fmt = PixelFormat::new(ColorMode::Rgb, depth, true);
|
||||
purge_effect_cache();
|
||||
let expected = composite_to_surface(&d, d.bounds(), fmt, None);
|
||||
purge_effect_cache();
|
||||
let actual = composite_to_surface_with_interrupt(&d, d.bounds(), fmt, None, &photocraft_raster::Interrupt::NONE).unwrap();
|
||||
assert!(actual.read_region(d.bounds()) == expected.read_region(d.bounds()), "{depth:?}: the interruptible composite differs");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapeless_effect_maps_cover_only_the_band_being_rendered() {
|
||||
// Transparency Shapes Layer off makes an effect region the whole canvas: on a 1920 × 103675
|
||||
|
||||
@@ -24,6 +24,7 @@ serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
web-time = { workspace = true }
|
||||
photocraft-paint = { workspace = true }
|
||||
photocraft-algo = { workspace = true }
|
||||
photocraft-text = { workspace = true }
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_doc::{Document, Fill, Layer, LayerContent, TextLayer};
|
||||
use photocraft_doc::{Document, Fill, GradientStyle, Layer, LayerContent, TextLayer};
|
||||
use photocraft_geom::{Affine, Point, Rect};
|
||||
use photocraft_raster::Surface;
|
||||
|
||||
@@ -52,8 +52,12 @@ fn map_angle(a: &Affine, deg: f32) -> f32 {
|
||||
}
|
||||
|
||||
fn map_fill(a: &Affine, f: &mut Fill) {
|
||||
if let Fill::Gradient { angle, offset, .. } = f {
|
||||
if let Fill::Gradient { angle, offset, style, reverse, .. } = f {
|
||||
*angle = map_angle(a, *angle);
|
||||
// An Angle gradient sweeps clockwise from its angle; a mirror turns the sweep around.
|
||||
if *style == GradientStyle::Angle && a.m[0] * a.m[3] - a.m[1] * a.m[2] < 0.0 {
|
||||
*reverse = !*reverse;
|
||||
}
|
||||
// The centre offset (a fraction of the frame) turns with the canvas: exact for 90° turns
|
||||
// and flips, where the frame's sides swap with the axes. Scale (Image Size) resizes the
|
||||
// frame too, so only each axis's direction applies.
|
||||
@@ -138,6 +142,26 @@ pub(crate) fn retarget_type_resolution(doc: &mut Document, dpi: f32) {
|
||||
}
|
||||
retag_text(dpi, t);
|
||||
});
|
||||
// The styles travelling with the copies scale the same way: a style a copy brings to a
|
||||
// document that lacks it defines the rewritten size, so the copy has no local override.
|
||||
let st = &mut doc.text_styles;
|
||||
let sets = st
|
||||
.character
|
||||
.iter_mut()
|
||||
.map(|c| &mut c.attrs)
|
||||
.chain(st.paragraph.iter_mut().chain([&mut st.basic]).flat_map(|p| [&mut p.para_attrs, &mut p.char_attrs]));
|
||||
for attrs in sets {
|
||||
for (key, v) in attrs.iter_mut() {
|
||||
let Some(n) = v.as_f64().filter(|n| n.is_finite()) else { continue };
|
||||
let n = n as f32;
|
||||
let scaled = match key.as_str() {
|
||||
"size_pt" | "leading_pt" => point_size(n, k),
|
||||
"baseline_shift_pt" | "first_line_indent_pt" | "start_indent_pt" | "end_indent_pt" | "space_before_pt" | "space_after_pt" => grown(n, k),
|
||||
_ => continue,
|
||||
};
|
||||
*v = serde_json::json!(scaled);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A positive size in points times `k`, kept finite and above zero (a tiny ratio must not make
|
||||
|
||||
@@ -221,6 +221,32 @@ fn gradient_fill_offset_stays_a_fraction_of_the_frame() {
|
||||
assert!((offset.0 - 0.1).abs() < 1e-6 && (offset.1 - 0.25).abs() < 1e-6, "{offset:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turns_carry_an_angle_gradient_fill_with_its_pixels() {
|
||||
// An Angle gradient sweeps clockwise: a mirror must reverse it, a turn must not.
|
||||
for t in TURNS {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": W, "height": H})).unwrap();
|
||||
let p = json!({"from": [20, 14], "to": [50, 4], "style": "angle", "dither": false});
|
||||
s.execute("gradient.fill.create", p).unwrap();
|
||||
let before = photocraft_compose::flatten(doc(&s));
|
||||
s.execute(command(t), json!({})).unwrap();
|
||||
let want = expected(&before, t, doc(&s).size.width);
|
||||
let (mean, big) = diff(&photocraft_compose::flatten(doc(&s)).px, &want);
|
||||
assert!(mean < 2.0 / 255.0 && big < 0.02, "{t:?}: mean {mean} big {big}");
|
||||
let flip = matches!(t, Turn::FlipHorizontal | Turn::FlipVertical);
|
||||
assert_eq!(s.execute("gradient.fill.get", json!({})).unwrap()["reverse"], json!(flip), "{t:?}");
|
||||
// Turning back restores the fill model (Reverse toggled twice for flips).
|
||||
s.execute(command(t), json!({})).unwrap();
|
||||
if matches!(t, Turn::Cw90 | Turn::Ccw90) {
|
||||
s.execute(command(t), json!({})).unwrap();
|
||||
s.execute(command(t), json!({})).unwrap();
|
||||
}
|
||||
let g = s.execute("gradient.fill.get", json!({})).unwrap();
|
||||
assert_eq!(g["reverse"], json!(false), "{t:?}: {g}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape's (fill, stroke) gradient angles after `cmd` on a shape whose fill and stroke both
|
||||
/// start as a 0° (left to right) gradient.
|
||||
fn shape_gradient_angles_after(cmd: &str, p: serde_json::Value) -> (f32, f32) {
|
||||
|
||||
@@ -882,7 +882,7 @@ fn build() -> Vec<CommandSpec> {
|
||||
"Gradient…",
|
||||
["Layer", "New Fill Layer"],
|
||||
None,
|
||||
r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask)}"##,
|
||||
r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask),"stops"?,"transparency"?,"midpoints"?,"scale"?,"offset"?,"dither"?,"align"? (as gradient.fill.set; stops replace from/to)}"##,
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?;
|
||||
@@ -891,15 +891,26 @@ fn build() -> Vec<CommandSpec> {
|
||||
let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear"));
|
||||
let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false);
|
||||
let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true);
|
||||
// The rest of a recorded Gradient Fill (a loaded action's Make): applied as
|
||||
// `gradient.fill.set` would, in the same step.
|
||||
let rest: serde_json::Map<String, Value> = ["stops", "transparency", "midpoints", "scale", "offset", "dither", "align"]
|
||||
.iter()
|
||||
.filter_map(|k| p.get(*k).map(|v| ((*k).to_string(), v.clone())))
|
||||
.collect();
|
||||
let (fg, bg) = (s.tools.foreground, s.tools.background);
|
||||
let id = s.edit("New Gradient Fill Layer", |doc, active| {
|
||||
let fill = Fill::gradient(
|
||||
let mut fill = Fill::gradient(
|
||||
vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))],
|
||||
angle,
|
||||
1.0,
|
||||
style,
|
||||
reverse,
|
||||
)
|
||||
.in_mode(doc.mode);
|
||||
);
|
||||
if !rest.is_empty() {
|
||||
let l = Layer::new(String::new(), LayerContent::Fill(fill.clone()));
|
||||
fill = crate::gradient_fill_cmds::apply_set(&l, &fill, doc.bounds(), &Value::Object(rest.clone()), fg, bg)?;
|
||||
}
|
||||
let fill = fill.in_mode(doc.mode);
|
||||
let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));
|
||||
mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?;
|
||||
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto);
|
||||
|
||||
@@ -849,6 +849,7 @@ pub(super) const EVENTS: &[Event] = &[
|
||||
"layer.new.layerViaCut",
|
||||
"layer.newFillLayer.solidColor",
|
||||
"layer.newFillLayer.pattern",
|
||||
"layer.newFillLayer.gradient",
|
||||
"layer.newAdjustmentLayer.levels",
|
||||
"layer.newAdjustmentLayer.curves",
|
||||
"layer.newAdjustmentLayer.hueSaturation",
|
||||
@@ -893,6 +894,7 @@ pub(super) const EVENTS: &[Event] = &[
|
||||
"layer.setLabelColor",
|
||||
"layer.setAdjustment",
|
||||
"layer.fill.pattern.set",
|
||||
"gradient.fill.set",
|
||||
"layer.new.layerFromBackground",
|
||||
"layer.layerStyle.blendingOptions",
|
||||
"layer.smartFilter.blendingOptions",
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use super::adjustments::{HUE_RANGES, adjustment_by_class, adjustment_by_suffix, adjustment_steps, levels_complete};
|
||||
use super::descriptors::{
|
||||
PCT, PX, Target, ang, class, class_ref, code, color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, get_ref, get_text, jbool,
|
||||
jnum, jstr, layer_ref, layer_target, long, name_ref, pct, px, ref_class, target, target_ref, text, trimmed,
|
||||
PCT, PX, Target, ang, boolean, class, class_ref, code, color_desc, color_hex, desc, enm, enumerated, get_bool, get_enum, get_list, get_num, get_obj,
|
||||
get_ref, get_text, jbool, jnum, jstr, layer_ref, layer_target, long, name_ref, num, pct, px, ref_class, target, target_ref, text, trimmed,
|
||||
};
|
||||
use super::fields::{Mapped, none, step, steps};
|
||||
use super::steps_layer::quick_mask_ref;
|
||||
use super::tables::{LABEL_COLORS, MODES, blend_label, blend_ps, lookup, lookup_back};
|
||||
use super::tables::{CHANNELS, LABEL_COLORS, MODES, blend_label, blend_ps, channel_of, channel_ref, lookup, lookup_back};
|
||||
use super::{D, Descriptor, Id, Map, ReferenceItem, UnicodeString, Value, json};
|
||||
|
||||
/// A `Md ` value as a blend-mode label, only when it is a `BlnM` enumeration: another
|
||||
@@ -78,6 +78,354 @@ fn pattern_desc(p: &Value) -> Option<Descriptor> {
|
||||
Some(t)
|
||||
}
|
||||
|
||||
/// Gradient Fill layers: `GrdT` ↔ `style`.
|
||||
const GRADIENT_STYLES: &[(&str, &str)] = &[("Lnr", "linear"), ("Rdl", "radial"), ("Angl", "angle"), ("Rflt", "reflected"), ("Dmnd", "diamond")];
|
||||
|
||||
/// The `gradientLayer` keys [`gradient_params`] reads; a descriptor with any other key stays a
|
||||
/// kept Photoshop step.
|
||||
const GRADIENT_LAYER_KEYS: &[&str] = &["Grad", "Type", "Angl", "Rvrs", "Dthr", "Algn", "Scl ", "Ofst", "gradientsInterpolationMethod"];
|
||||
|
||||
/// The hidden param an imported Gradient Fill step keeps its recorded `gradientLayer` descriptor
|
||||
/// in, so Save Actions writes it back unchanged while its params are the ones it loaded with.
|
||||
const GRADIENT_DESCRIPTOR: &str = "__atnDescriptor";
|
||||
|
||||
/// A `gradientLayer` descriptor as the params of `layer.newFillLayer.gradient` /
|
||||
/// `gradient.fill.set`. Midpoint k belongs to the segment that ends at stop k + 1, as the PSD
|
||||
/// reader reads it; all-default midpoints give `[]`, which clears custom ones on a Set. None for
|
||||
/// what the fill does not play: a Noise gradient, a smoothness below 100 %, a non-classic
|
||||
/// interpolation, a transparency midpoint, stops out of order or values out of range.
|
||||
fn gradient_params(t: &Descriptor) -> Option<Map<String, Value>> {
|
||||
if t.items.iter().any(|(k, _)| !GRADIENT_LAYER_KEYS.iter().any(|g| k.is(g))) {
|
||||
return None;
|
||||
}
|
||||
let mut p = Map::new();
|
||||
if let Some(s) = t.get("Type") {
|
||||
p.insert("style".into(), lookup(GRADIENT_STYLES, &enumerated(s)?)?.into());
|
||||
}
|
||||
if let Some(a) = t.get("Angl") {
|
||||
p.insert("angle".into(), num(a)?.into());
|
||||
}
|
||||
for (key, param) in [("Rvrs", "reverse"), ("Dthr", "dither"), ("Algn", "align")] {
|
||||
if let Some(v) = t.get(key) {
|
||||
p.insert(param.into(), boolean(v)?.into());
|
||||
}
|
||||
}
|
||||
if let Some(s) = t.get("Scl ") {
|
||||
p.insert("scale".into(), num(s)?.into());
|
||||
}
|
||||
if let Some(o) = t.get("Ofst") {
|
||||
let D::Descriptor(o) = o else { return None };
|
||||
p.insert("offset".into(), json!([get_num(o, "Hrzn")?, get_num(o, "Vrtc")?]));
|
||||
}
|
||||
if t.get("gradientsInterpolationMethod").is_some_and(|m| enumerated(m).as_deref() != Some("Gcls")) {
|
||||
return None;
|
||||
}
|
||||
let g = get_obj(t, "Grad")?;
|
||||
if get_enum(g, "GrdF").as_deref() != Some("CstS") || g.get("Intr").is_some_and(|i| num(i) != Some(4096.0)) {
|
||||
return None;
|
||||
}
|
||||
let (mut stops, mut mids, mut previous) = (Vec::new(), Vec::new(), 0.0);
|
||||
for (i, s) in get_list(g, "Clrs").filter(|c| (2..=1024).contains(&c.len()))?.iter().enumerate() {
|
||||
let D::Descriptor(s) = s else { return None };
|
||||
let color = match get_enum(s, "Type").as_deref() {
|
||||
None | Some("UsrS") => json!(color_hex(get_obj(s, "Clr ")?)?),
|
||||
Some("FrgC") => json!("foreground"),
|
||||
Some("BckC") => json!("background"),
|
||||
Some(_) => return None,
|
||||
};
|
||||
let at = get_num(s, "Lctn")?;
|
||||
if !(previous..=4096.0).contains(&at) {
|
||||
return None;
|
||||
}
|
||||
previous = at;
|
||||
stops.push(json!([at / 4096.0, color]));
|
||||
if i > 0 {
|
||||
// The dialog's midpoints are 5..95 %; playback would clamp anything else.
|
||||
let mid = get_num(s, "Mdpn").unwrap_or(50.0);
|
||||
if !(5.0..=95.0).contains(&mid) {
|
||||
return None;
|
||||
}
|
||||
mids.push(mid / 100.0);
|
||||
}
|
||||
}
|
||||
p.insert("stops".into(), Value::Array(stops));
|
||||
if let Some(trns) = get_list(g, "Trns") {
|
||||
let (mut out, mut previous) = (Vec::new(), 0.0);
|
||||
for s in trns {
|
||||
let D::Descriptor(s) = s else { return None };
|
||||
if get_num(s, "Mdpn").is_some_and(|m| m != 50.0) {
|
||||
return None;
|
||||
}
|
||||
// Playback would clamp and sort what is out of range or out of order.
|
||||
let (at, opacity) = (get_num(s, "Lctn")?, get_num(s, "Opct")?);
|
||||
if !(previous..=4096.0).contains(&at) || !(0.0..=100.0).contains(&opacity) {
|
||||
return None;
|
||||
}
|
||||
previous = at;
|
||||
out.push(json!([at / 4096.0, opacity]));
|
||||
}
|
||||
p.insert("transparency".into(), Value::Array(out));
|
||||
}
|
||||
if mids.iter().all(|m| *m == 0.5) {
|
||||
mids.clear();
|
||||
}
|
||||
p.insert("midpoints".into(), json!(mids));
|
||||
Some(p)
|
||||
}
|
||||
|
||||
/// [`gradient_params`] plus the recorded descriptor, for Save Actions.
|
||||
fn gradient_step(t: &Descriptor) -> Option<Value> {
|
||||
let mut p = gradient_params(t)?;
|
||||
p.insert(GRADIENT_DESCRIPTOR.into(), photocraft_paint::tile::b64_encode(&t.to_bytes()).into());
|
||||
Some(Value::Object(p))
|
||||
}
|
||||
|
||||
/// The `gradientLayer` descriptor for a Gradient Fill step: the recorded one while the params are
|
||||
/// still what it imports as, else one written from the params. That needs every stop as
|
||||
/// `#rrggbb` on a 1/4096 location, whole-percent midpoints and, for a Set (`set`), the
|
||||
/// transparency stops: Photoshop's Set replaces the whole gradient, where the command keeps the
|
||||
/// layer's own transparency.
|
||||
fn gradient_desc(p: &Value, set: bool) -> Option<Descriptor> {
|
||||
if let Some(t) = jstr(p, GRADIENT_DESCRIPTOR).and_then(photocraft_paint::tile::b64_decode).and_then(|b| Descriptor::from_bytes(&b).ok()) {
|
||||
let (mut a, mut b) = (Value::Object(gradient_params(&t)?), p.clone());
|
||||
b.as_object_mut()?.remove(GRADIENT_DESCRIPTOR);
|
||||
super::convert::normalise(&mut a);
|
||||
super::convert::normalise(&mut b);
|
||||
if a == b {
|
||||
return Some(t);
|
||||
}
|
||||
}
|
||||
const KEYS: &[&str] = &["style", "angle", "reverse", "dither", "align", "scale", "offset", "stops", "transparency", "midpoints", GRADIENT_DESCRIPTOR];
|
||||
if p.as_object()?.iter().any(|(k, v)| !v.is_null() && !KEYS.contains(&k.as_str())) || (set && p.get("transparency").is_none()) {
|
||||
return None;
|
||||
}
|
||||
let location = |v: &Value| {
|
||||
let t = v.as_f64()? * 4096.0;
|
||||
((0.0..=4096.0).contains(&t) && t.fract() == 0.0).then(|| long(t))
|
||||
};
|
||||
let stops = p.get("stops")?.as_array().filter(|s| (2..=1024).contains(&s.len()))?;
|
||||
let mids: Vec<f64> = match p.get("midpoints") {
|
||||
None | Some(Value::Null) => Vec::new(),
|
||||
Some(m) => m.as_array()?.iter().map(Value::as_f64).collect::<Option<_>>()?,
|
||||
};
|
||||
if mids.len() >= stops.len() {
|
||||
return None;
|
||||
}
|
||||
let (mut clrs, mut previous) = (Vec::new(), 0.0);
|
||||
for (i, s) in stops.iter().enumerate() {
|
||||
let [at, color] = s.as_array()?.as_slice() else { return None };
|
||||
if at.as_f64()? < previous {
|
||||
return None;
|
||||
}
|
||||
previous = at.as_f64()?;
|
||||
// A foreground or background stop is left out: Photoshop records the colour it had too.
|
||||
let color = color_desc(color.as_str()?)?;
|
||||
let mid = if i == 0 { 50.0 } else { mids.get(i - 1).copied().unwrap_or(0.5) * 100.0 };
|
||||
if (mid - mid.round()).abs() > 1e-9 || !(5.0..=95.0).contains(&mid.round()) {
|
||||
return None;
|
||||
}
|
||||
clrs.push(D::Descriptor(
|
||||
desc("Clrt").with("Clr ", D::Descriptor(color)).with("Type", enm("Clry", "UsrS")).with("Lctn", location(at)?).with("Mdpn", long(mid)),
|
||||
));
|
||||
}
|
||||
let default_trns = vec![json!([0, 100]), json!([1, 100])];
|
||||
let trns: Option<Vec<D>> = p
|
||||
.get("transparency")
|
||||
.and_then(Value::as_array)
|
||||
.unwrap_or(&default_trns)
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let [at, o] = s.as_array()?.as_slice() else { return None };
|
||||
Some(D::Descriptor(desc("TrnS").with("Opct", pct(o.as_f64()?)).with("Lctn", location(at)?).with("Mdpn", long(50.0))))
|
||||
})
|
||||
.collect();
|
||||
let grad = desc("Grdn")
|
||||
.with("Nm ", text("Custom"))
|
||||
.with("GrdF", enm("GrdF", "CstS"))
|
||||
.with("Intr", D::Double(4096.0))
|
||||
.with("Clrs", D::List(clrs))
|
||||
.with("Trns", D::List(trns?));
|
||||
let mut t = desc("gradientLayer");
|
||||
if let Some(a) = jnum(p, "angle") {
|
||||
t = t.with("Angl", ang(a));
|
||||
}
|
||||
if let Some(s) = jstr(p, "style") {
|
||||
t = t.with("Type", enm("GrdT", lookup_back(GRADIENT_STYLES, s)?));
|
||||
}
|
||||
for (param, key) in [("reverse", "Rvrs"), ("dither", "Dthr"), ("align", "Algn")] {
|
||||
if let Some(v) = p.get(param).filter(|v| !v.is_null()) {
|
||||
t = t.with(key, D::Boolean(v.as_bool()?));
|
||||
}
|
||||
}
|
||||
if let Some(s) = jnum(p, "scale") {
|
||||
t = t.with("Scl ", pct(s));
|
||||
}
|
||||
if let Some(o) = p.get("offset").filter(|v| !v.is_null()) {
|
||||
let [x, y] = o.as_array()?.as_slice() else { return None };
|
||||
t = t.with("Ofst", D::Descriptor(desc("Pnt ").with("Hrzn", pct(x.as_f64()?)).with("Vrtc", pct(y.as_f64()?))));
|
||||
}
|
||||
Some(t.with("Grad", D::Descriptor(grad)))
|
||||
}
|
||||
|
||||
/// `layer.newFillLayer.gradient` as a Make of a `contentLayer`. The two-colour form (`from`,
|
||||
/// `to`) becomes the stops it plays as; without them it plays the toolbox colours, which
|
||||
/// Photoshop records with the colour they had.
|
||||
fn gradient_make_to(p: &Value) -> Option<Descriptor> {
|
||||
let mut p = p.clone();
|
||||
let o = p.as_object_mut()?;
|
||||
if o.remove("path").is_some_and(|v| !v.is_null()) {
|
||||
return None;
|
||||
}
|
||||
// Stops replace `from` and `to` when the step plays, so those two are left out beside them.
|
||||
match (o.remove("from").filter(|v| !v.is_null()), o.remove("to").filter(|v| !v.is_null())) {
|
||||
_ if o.contains_key("stops") => {}
|
||||
(None, None) => {}
|
||||
(Some(a), Some(b)) => {
|
||||
o.insert("stops".into(), json!([[0, a], [1, b]]));
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
let t = gradient_desc(&p, false)?;
|
||||
Some(desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t)))))
|
||||
}
|
||||
|
||||
/// `layer.layerStyle.blendingOptions` as a Set of the target layer.
|
||||
fn blending_options_to(p: &Value) -> Option<Descriptor> {
|
||||
let o = p.as_object()?;
|
||||
let blend_if = p.get("blendIf");
|
||||
let mut t = desc("Lyr ");
|
||||
if blend_if.is_some() {
|
||||
// With Blend If, the dialog's opacities and mode are in the same `set`; without it,
|
||||
// Photoshop's `set` of them loads as `layer.setProps`.
|
||||
for (param, key) in [("opacity", "Opct"), ("fillOpacity", "fillOpacity")] {
|
||||
if let Some(v) = jnum(p, param) {
|
||||
t = t.with(key, pct(v));
|
||||
}
|
||||
}
|
||||
if let Some(m) = jstr(p, "blend") {
|
||||
t = t.with("Md ", enm("BlnM", blend_ps(m)?));
|
||||
}
|
||||
}
|
||||
for (key, param) in ADVANCED_BLENDING {
|
||||
if let Some(b) = jbool(p, param) {
|
||||
t = t.with(key, D::Boolean(b));
|
||||
}
|
||||
}
|
||||
if let Some(b) = blend_if {
|
||||
t = t.with("Blnd", blend_if_to(b)?);
|
||||
if let Some(fx) = jstr(p, EFFECTS_SCALE) {
|
||||
let fx = photocraft_paint::tile::b64_decode(fx).and_then(|b| Descriptor::from_bytes(&b).ok())?;
|
||||
if !scale_only(&fx) {
|
||||
return None;
|
||||
}
|
||||
t = t.with("Lefx", D::Descriptor(fx));
|
||||
}
|
||||
}
|
||||
// Only these export: Photoshop records the dialog's other options differently.
|
||||
if t.items.is_empty() || t.items.len() != o.len() {
|
||||
return None;
|
||||
}
|
||||
Some(desc("null").with("null", target_ref("Lyr ")).with("T ", D::Descriptor(t)))
|
||||
}
|
||||
|
||||
/// Blend If: a `Blnd` list's `Chnl` ↔ `blendIf` channel (`Gry` is the composite).
|
||||
fn blend_if_channel(r: &[ReferenceItem]) -> Option<&'static str> {
|
||||
match target(r) {
|
||||
Target::Ordinal(o) if o == "Cmps" => Some("gray"),
|
||||
Target::Ordinal(o) => channel_of(&o),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The slider keys of one `Blnd` entry: This Layer, then Underlying Layer, each black low and
|
||||
/// high, white low and high.
|
||||
const BLEND_IF_KEYS: [[&str; 4]; 2] = [["SrcB", "Srcl", "SrcW", "Srcm"], ["DstB", "Dstl", "DstW", "Dstt"]];
|
||||
|
||||
/// A `Blnd` list as `layer.layerStyle.blendingOptions`' `blendIf`. Each entry's sliders are
|
||||
/// whole levels 0..255 (also in a 16-bit document); Underlying Layer may be missing. None for
|
||||
/// anything else, so the step stays a kept Photoshop step.
|
||||
fn blend_if_from(list: &[D]) -> Option<Value> {
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for e in list {
|
||||
let D::Descriptor(e) = e else { return None };
|
||||
if e.items.iter().any(|(k, _)| !k.is("Chnl") && !BLEND_IF_KEYS.iter().flatten().any(|b| k.is(b))) {
|
||||
return None;
|
||||
}
|
||||
let channel = blend_if_channel(get_ref(e, "Chnl")?)?;
|
||||
let range = |keys: &[&str; 4]| -> Option<Option<Value>> {
|
||||
let v: Vec<Option<i32>> = keys
|
||||
.iter()
|
||||
.map(|k| match e.get(k) {
|
||||
Some(D::Integer(i)) if (0..=255).contains(i) => Some(*i),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
match v.iter().flatten().count() {
|
||||
0 if keys.iter().all(|k| e.get(k).is_none()) => Some(None),
|
||||
// In order, as the command takes them; an inverted range stays a Photoshop step.
|
||||
4 => {
|
||||
let q: Vec<i32> = v.into_iter().flatten().collect();
|
||||
q.windows(2).all(|w| w[0] <= w[1]).then(|| Some(json!(q)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let mut m = json!({"channel": channel, "thisLayer": range(&BLEND_IF_KEYS[0])??});
|
||||
if let Some(u) = range(&BLEND_IF_KEYS[1])? {
|
||||
m["underlying"] = u;
|
||||
}
|
||||
out.push(m);
|
||||
}
|
||||
(!out.is_empty()).then_some(Value::Array(out))
|
||||
}
|
||||
|
||||
/// `blendIf` back as a `Blnd` list: named channels and whole levels only (an index or `null`
|
||||
/// reset has no Photoshop form).
|
||||
fn blend_if_to(v: &Value) -> Option<D> {
|
||||
let entries = match v {
|
||||
Value::Array(a) => a.iter().collect::<Vec<_>>(),
|
||||
Value::Object(_) => vec![v],
|
||||
_ => return None,
|
||||
};
|
||||
let mut list = Vec::with_capacity(entries.len());
|
||||
for e in entries {
|
||||
let o = e.as_object()?;
|
||||
if o.keys().any(|k| !matches!(k.as_str(), "channel" | "thisLayer" | "underlying")) {
|
||||
return None;
|
||||
}
|
||||
let channel = match e.get("channel") {
|
||||
None | Some(Value::Null) => "gray",
|
||||
Some(Value::String(c)) if c == "grey" => "gray",
|
||||
Some(Value::String(c)) => c.as_str(),
|
||||
_ => return None,
|
||||
};
|
||||
lookup_back(CHANNELS, channel)?;
|
||||
let mut d = desc("Blnd").with("Chnl", channel_ref(Some(channel)));
|
||||
for (param, keys) in [("thisLayer", &BLEND_IF_KEYS[0]), ("underlying", &BLEND_IF_KEYS[1])] {
|
||||
let Some(r) = e.get(param) else {
|
||||
if param == "thisLayer" {
|
||||
return None;
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let r: Vec<f64> = r.as_array()?.iter().map(Value::as_f64).collect::<Option<_>>()?;
|
||||
let q = match r.as_slice() {
|
||||
[b, w] => [*b, *b, *w, *w],
|
||||
[a, b, c, w] => [*a, *b, *c, *w],
|
||||
_ => return None,
|
||||
};
|
||||
if !q.iter().all(|x| (0.0..=255.0).contains(x) && x.fract() == 0.0) || !q.windows(2).all(|w| w[0] <= w[1]) {
|
||||
return None;
|
||||
}
|
||||
for (k, x) in keys.iter().zip(q) {
|
||||
d = d.with(k, long(x));
|
||||
}
|
||||
}
|
||||
list.push(D::Descriptor(d));
|
||||
}
|
||||
Some(D::List(list))
|
||||
}
|
||||
|
||||
/// Layer › Layer Mask: the `UsrM` value of an Add Layer Mask `Mk` ↔ its command.
|
||||
const MASK_USING: &[(&str, &str)] = &[
|
||||
("RvlA", "layer.layerMask.revealAll"),
|
||||
@@ -303,6 +651,11 @@ pub(super) fn make_from(d: &Descriptor) -> Mapped {
|
||||
Some(p) => step("layer.newFillLayer.pattern", Value::Object(p)),
|
||||
None => Mapped::Unsupported { harmless: false },
|
||||
},
|
||||
// A name, opacity, mode or clipping beside `Type` would neither play nor save back.
|
||||
Some(t) if t.class_id.is("gradientLayer") => match gradient_step(t) {
|
||||
Some(p) if using.is_some_and(|u| u.items.iter().all(|(k, _)| k.is("Type"))) => step("layer.newFillLayer.gradient", p),
|
||||
_ => Mapped::Unsupported { harmless: false },
|
||||
},
|
||||
_ => Mapped::Unsupported { harmless: false },
|
||||
},
|
||||
Some("layerSection") => {
|
||||
@@ -432,6 +785,7 @@ pub(super) fn make_to(id: &str, p: &Value) -> Option<Descriptor> {
|
||||
let t = pattern_desc(p)?;
|
||||
desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t))))
|
||||
}
|
||||
"layer.newFillLayer.gradient" => gradient_make_to(p)?,
|
||||
"layer.duplicate" => {
|
||||
// Duplicate into a new document is a `Mk`, not a `Dplc` (see `make_from`).
|
||||
// Anything else falls through to the `Dplc` event below.
|
||||
@@ -658,6 +1012,25 @@ const LOCKS: &[(&str, &str)] = &[
|
||||
("protectAll", "all"),
|
||||
];
|
||||
|
||||
/// The Blending Options keys besides the Advanced checkboxes that `layer.layerStyle.blendingOptions`
|
||||
/// takes from a `set` of the layer: opacity, fill opacity, mode and Blend If.
|
||||
const BLENDING_DIALOG: &[&str] = &["Opct", "fillOpacity", "Md ", "Blnd"];
|
||||
|
||||
/// The hidden `layer.layerStyle.blendingOptions` param that keeps the `Lefx` = {Scl} the Layer
|
||||
/// Style dialog's OK records beside Blend If, so Save Actions writes the Set back unchanged.
|
||||
const EFFECTS_SCALE: &str = "__atnEffectsScale";
|
||||
|
||||
/// A `Lefx` holding only the effects' scale: what the dialog's OK records on a layer without
|
||||
/// effects. It changes nothing.
|
||||
fn scale_only(fx: &Descriptor) -> bool {
|
||||
fx.items.iter().all(|(k, _)| k.is("Scl "))
|
||||
}
|
||||
|
||||
/// A `T` key that is such a `Lefx`.
|
||||
fn is_scale_only(k: &Id, v: &D) -> bool {
|
||||
matches!(v, D::Descriptor(fx) if k.is("Lefx") && scale_only(fx))
|
||||
}
|
||||
|
||||
/// Blending Options' Advanced checkboxes ↔ `layer.layerStyle.blendingOptions` params.
|
||||
const ADVANCED_BLENDING: &[(&str, &str)] = &[("blendClipped", "blendClippedLayersAsGroup"), ("transparencyShapesLayer", "transparencyShapesLayer")];
|
||||
|
||||
@@ -739,6 +1112,32 @@ fn layer_set_from(d: &Descriptor, r: &[ReferenceItem]) -> Mapped {
|
||||
advanced.insert((*param).into(), b.into());
|
||||
}
|
||||
}
|
||||
if let Some(list) = get_list(t, "Blnd") {
|
||||
// Effects beside Blend If have no step here: keep the recorded step rather than play
|
||||
// and save it back without them.
|
||||
if t.items.iter().any(|(k, v)| k.is("Lefx") && !is_scale_only(k, v)) {
|
||||
return unsupported;
|
||||
}
|
||||
let Some(b) = blend_if_from(list) else { return unsupported };
|
||||
advanced.insert("blendIf".into(), b);
|
||||
// The Blending Options dialog's OK: with nothing but its own options, the opacities and
|
||||
// the mode go with Blend If into one step, saved back as the one `set`.
|
||||
if t.items.iter().all(|(k, v)| BLENDING_DIALOG.iter().any(|b| k.is(b)) || ADVANCED_BLENDING.iter().any(|(a, _)| k.is(a)) || is_scale_only(k, v)) {
|
||||
if let Some(D::Descriptor(fx)) = t.get("Lefx") {
|
||||
advanced.insert(EFFECTS_SCALE.into(), photocraft_paint::tile::b64_encode(&fx.to_bytes()).into());
|
||||
}
|
||||
for (key, param) in [("Opct", "opacity"), ("fillOpacity", "fillOpacity")] {
|
||||
if let Some(v) = get_num(t, key) {
|
||||
advanced.insert(param.into(), v.into());
|
||||
}
|
||||
}
|
||||
p.remove("opacity");
|
||||
p.remove("fill");
|
||||
if let Some(b) = p.remove("blend") {
|
||||
advanced.insert("blend".into(), b);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !advanced.is_empty() {
|
||||
if !targeted {
|
||||
return unsupported;
|
||||
@@ -751,10 +1150,7 @@ fn layer_set_from(d: &Descriptor, r: &[ReferenceItem]) -> Mapped {
|
||||
// The Layer Style dialog's OK on a layer without effects records only the effects'
|
||||
// scale (`Lefx` = {Scl}); an empty `T` is an OK that changed nothing. Neither changes
|
||||
// the document.
|
||||
let no_effect = t.items.iter().all(|(k, val)| match val {
|
||||
D::Descriptor(fx) if k.is("Lefx") => fx.items.iter().all(|(fk, _)| fk.is("Scl ")),
|
||||
_ => false,
|
||||
});
|
||||
let no_effect = t.items.iter().all(|(k, val)| is_scale_only(k, val));
|
||||
if !v.is_empty() {
|
||||
steps(v)
|
||||
} else if no_effect {
|
||||
@@ -808,6 +1204,12 @@ pub(super) fn set_from(d: &Descriptor) -> Mapped {
|
||||
Some(p) if !p.is_empty() => step("layer.fill.pattern.set", Value::Object(p)),
|
||||
_ => unsupported,
|
||||
},
|
||||
// Photoshop's Set replaces the whole gradient; one without transparency stops would
|
||||
// keep the layer's own on play, and could not be written back once edited.
|
||||
Some(t) if t.class_id.is("gradientLayer") => match gradient_step(t).filter(|p| p.get("transparency").is_some()) {
|
||||
Some(p) => step("gradient.fill.set", p),
|
||||
None => unsupported,
|
||||
},
|
||||
_ => unsupported,
|
||||
},
|
||||
(Some("AdjL"), Target::Ordinal(o)) if o == "Trgt" => {
|
||||
@@ -954,21 +1356,14 @@ pub(super) fn set_to(id: &str, p: &Value) -> Option<Descriptor> {
|
||||
}
|
||||
desc("null").with("null", target_ref("contentLayer")).with("T ", D::Descriptor(pattern_desc(p)?))
|
||||
}
|
||||
"layer.layerStyle.blendingOptions" => {
|
||||
let o = p.as_object()?;
|
||||
let mut t = desc("Lyr ");
|
||||
for (key, param) in ADVANCED_BLENDING {
|
||||
if let Some(b) = jbool(p, param) {
|
||||
t = t.with(key, D::Boolean(b));
|
||||
}
|
||||
}
|
||||
// Only the Advanced checkboxes export: Photoshop records the dialog's other options
|
||||
// differently.
|
||||
if t.items.is_empty() || t.items.len() != o.len() {
|
||||
"gradient.fill.set" => {
|
||||
// A named layer or dragged handles have no place in the event.
|
||||
if ["layer", "from", "to"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
return None;
|
||||
}
|
||||
desc("null").with("null", target_ref("Lyr ")).with("T ", D::Descriptor(t))
|
||||
desc("null").with("null", target_ref("contentLayer")).with("T ", D::Descriptor(gradient_desc(p, true)?))
|
||||
}
|
||||
"layer.layerStyle.blendingOptions" => blending_options_to(p)?,
|
||||
"layer.smartFilter.blendingOptions" => {
|
||||
if p.get("layer").is_some() {
|
||||
return None;
|
||||
|
||||
@@ -1056,6 +1056,11 @@ fn every_mapped_command_exports_and_imports_back() {
|
||||
("layer.smartFilter.deleteFilterMask", json!({"ifPresent": true})),
|
||||
("layer.smartFilter.blendingOptions", json!({"index": 1, "opacity": 0.5, "blend": "Darken"})),
|
||||
("layer.layerStyle.blendingOptions", json!({"blendClippedLayersAsGroup": false, "transparencyShapesLayer": false})),
|
||||
("layer.layerStyle.blendingOptions", json!({"blendIf": [{"channel": "gray", "thisLayer": [0, 30, 200, 255], "underlying": [0, 0, 255, 255]}]})),
|
||||
(
|
||||
"layer.layerStyle.blendingOptions",
|
||||
json!({"opacity": 40, "fillOpacity": 70, "blend": "Multiply", "blendIf": [{"channel": "blue", "thisLayer": [5, 5, 250, 250]}]}),
|
||||
),
|
||||
("layer.createClippingMask", json!({})),
|
||||
("layer.lockLayers", json!({"transparency": true})),
|
||||
("filter.stylize.diffuse", json!({"mode": "normal", "seed": 321654})),
|
||||
@@ -1200,6 +1205,9 @@ fn every_mapped_command_exports_and_imports_back() {
|
||||
"filter.sharpen.sharpenMore",
|
||||
// Saves back only as the descriptor it was loaded from (loaded_camera_raw_filter_steps_save_back_unchanged).
|
||||
"filter.cameraRaw",
|
||||
// Load with the recorded descriptor riding along (gradient_fill_steps_export_and_import_back).
|
||||
"gradient.fill.set",
|
||||
"layer.newFillLayer.gradient",
|
||||
];
|
||||
let unexpected: Vec<&str> = missing.iter().copied().filter(|id| !allowed.contains(id)).collect();
|
||||
assert!(unexpected.is_empty(), "add round-trip cases for {unexpected:?}");
|
||||
@@ -6284,6 +6292,365 @@ fn shear_nonfinite_coordinates_stay_kept() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #10771: a Gradient Fill as Photoshop records it: three stops, a transparency stop at 40 % and
|
||||
/// one midpoint per stop (`Mdpn` of stop k is the segment that ends at it).
|
||||
fn recorded_gradient(mids: [i32; 3]) -> Descriptor {
|
||||
let stop = |hex: &str, at: i32, mid: i32| {
|
||||
D::Descriptor(
|
||||
desc("Clrt")
|
||||
.with("Clr ", D::Descriptor(color_desc(hex).unwrap()))
|
||||
.with("Type", enm("Clry", "UsrS"))
|
||||
.with("Lctn", D::Integer(at))
|
||||
.with("Mdpn", D::Integer(mid)),
|
||||
)
|
||||
};
|
||||
let trn = |at: i32, o: f64| D::Descriptor(desc("TrnS").with("Opct", pct(o)).with("Lctn", D::Integer(at)).with("Mdpn", D::Integer(50)));
|
||||
let grad = desc("Grdn")
|
||||
.with("Nm ", text("Custom"))
|
||||
.with("GrdF", enm("GrdF", "CstS"))
|
||||
.with("Intr", D::Double(4096.0))
|
||||
.with("Clrs", D::List(vec![stop("#ff0000", 0, mids[0]), stop("#00ff00", 2048, mids[1]), stop("#0000ff", 4096, mids[2])]))
|
||||
.with("Trns", D::List(vec![trn(0, 100.0), trn(4096, 40.0)]));
|
||||
desc("gradientLayer").with("Angl", ang(30.0)).with("Type", enm("GrdT", "Rdl ")).with("Grad", D::Descriptor(grad))
|
||||
}
|
||||
|
||||
fn gradient_set(t: Descriptor) -> AtnItem {
|
||||
item("setd", "Set", Some(desc("null").with("null", target_ref("contentLayer")).with("T ", D::Descriptor(t))))
|
||||
}
|
||||
|
||||
fn gradient_make(t: Descriptor) -> AtnItem {
|
||||
let d = desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t))));
|
||||
item("Mk ", "Make", Some(d))
|
||||
}
|
||||
|
||||
/// The first saved step of `action` (strict save).
|
||||
fn saved_first(s: &mut Session) -> (AtnEvent, Option<Descriptor>) {
|
||||
let r = s.execute("actions.save", json!({"action": "A"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([]), "{r}");
|
||||
let saved = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
|
||||
let i = &saved.actions[0].items[0];
|
||||
(i.event.clone(), i.descriptor.clone())
|
||||
}
|
||||
|
||||
fn without_hidden(p: &Value) -> Value {
|
||||
let mut p = p.clone();
|
||||
p.as_object_mut().unwrap().remove("__atnDescriptor");
|
||||
normalise(&mut p);
|
||||
p
|
||||
}
|
||||
|
||||
fn active_fill(s: &Session) -> photocraft_doc::Fill {
|
||||
let st = s.active().unwrap();
|
||||
match &st.doc.layer(st.active_layer.unwrap()).unwrap().content {
|
||||
photocraft_doc::LayerContent::Fill(f) => f.clone(),
|
||||
c => panic!("not a fill layer: {}", c.kind_name()),
|
||||
}
|
||||
}
|
||||
|
||||
/// #10771: a recorded Set of a Gradient Fill loads as `gradient.fill.set` with its midpoints on
|
||||
/// the segment they belong to, plays them, and saves back as the recorded descriptor.
|
||||
#[test]
|
||||
fn gradient_fill_set_imports_midpoints_plays_and_saves_back_unchanged() {
|
||||
let recorded = recorded_gradient([50, 25, 70]);
|
||||
let mut s = Session::new();
|
||||
let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![gradient_set(recorded.clone())])).unwrap())})).unwrap();
|
||||
assert_eq!(loaded["unsupported"], json!([]), "{loaded}");
|
||||
let (id, p) = s.actions.list[0].steps[0].clone();
|
||||
assert_eq!(id, "gradient.fill.set");
|
||||
let mut expected = json!({
|
||||
"style": "radial", "angle": 30,
|
||||
"stops": [[0, "#ff0000"], [0.5, "#00ff00"], [1, "#0000ff"]],
|
||||
"transparency": [[0, 100], [1, 40]],
|
||||
"midpoints": [0.25, 0.7]
|
||||
});
|
||||
normalise(&mut expected);
|
||||
assert_eq!(without_hidden(&p), expected);
|
||||
assert_eq!(
|
||||
saved_first(&mut s),
|
||||
(AtnEvent::Code(*b"setd"), Some(desc("null").with("null", target_ref("contentLayer")).with("T ", D::Descriptor(recorded))))
|
||||
);
|
||||
// It plays on a Gradient Fill layer.
|
||||
s.execute("file.new", json!({"width": 16, "height": 12})).unwrap();
|
||||
s.execute("layer.newFillLayer.gradient", json!({"from": "#000000", "to": "#ffffff"})).unwrap();
|
||||
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
|
||||
assert!(played.get("failed").is_none(), "{played}");
|
||||
let photocraft_doc::Fill::Gradient { stops, midpoints, opacity_stops, .. } = active_fill(&s) else { panic!("not a gradient") };
|
||||
assert_eq!(stops.len(), 3);
|
||||
assert_eq!(midpoints, vec![0.25, 0.7]);
|
||||
assert_eq!(opacity_stops.len(), 2);
|
||||
// Default midpoints load as `[]`, which clears the custom ones when played.
|
||||
let mut s2 = Session::new();
|
||||
s2.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![gradient_set(recorded_gradient([50, 50, 50]))])).unwrap())})).unwrap();
|
||||
assert_eq!(s2.actions.list[0].steps[0].1["midpoints"], json!([]));
|
||||
s.actions = s2.actions;
|
||||
s.execute("actions.play", json!({"action": "A"})).unwrap();
|
||||
let photocraft_doc::Fill::Gradient { midpoints, .. } = active_fill(&s) else { panic!("not a gradient") };
|
||||
assert!(midpoints.is_empty() || midpoints.iter().all(|m| *m == 0.5), "{midpoints:?}");
|
||||
}
|
||||
|
||||
/// #10771: an edited loaded step writes a fresh descriptor from its params, midpoints included.
|
||||
#[test]
|
||||
fn edited_gradient_fill_set_writes_a_fresh_descriptor() {
|
||||
let mut s = Session::new();
|
||||
s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![gradient_set(recorded_gradient([50, 25, 70]))])).unwrap())})).unwrap();
|
||||
s.actions.list[0].steps[0].1["midpoints"] = json!([0.4, 0.6]);
|
||||
let (_, d) = saved_first(&mut s);
|
||||
let t = get_obj(d.as_ref().unwrap(), "T ").unwrap();
|
||||
let clrs = get_list(get_obj(t, "Grad").unwrap(), "Clrs").unwrap();
|
||||
let mids: Vec<f64> = clrs.iter().map(|c| if let D::Descriptor(c) = c { get_num(c, "Mdpn").unwrap() } else { panic!() }).collect();
|
||||
assert_eq!(mids, vec![50.0, 40.0, 60.0]);
|
||||
// Its own import is the edited params.
|
||||
let Mapped::Steps(steps) = (event_for(&AtnEvent::Code(*b"setd")).unwrap().from)(d.as_ref().unwrap()) else { panic!("did not import") };
|
||||
let mut edited = without_hidden(&s.actions.list[0].steps[0].1);
|
||||
edited["midpoints"] = json!([0.4, 0.6]);
|
||||
normalise(&mut edited);
|
||||
assert_eq!(without_hidden(&steps[0].1), edited);
|
||||
}
|
||||
|
||||
/// #10771: a recorded Make of a Gradient Fill layer plays its stops, transparency and midpoints
|
||||
/// and saves back unchanged.
|
||||
#[test]
|
||||
fn gradient_fill_make_imports_plays_and_saves_back_unchanged() {
|
||||
let recorded = recorded_gradient([50, 25, 70]);
|
||||
let mut s = Session::new();
|
||||
let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![gradient_make(recorded.clone())])).unwrap())})).unwrap();
|
||||
assert_eq!(loaded["unsupported"], json!([]), "{loaded}");
|
||||
assert_eq!(s.actions.list[0].steps[0].0, "layer.newFillLayer.gradient");
|
||||
let (event, d) = saved_first(&mut s);
|
||||
assert_eq!(event, AtnEvent::Code(*b"Mk "));
|
||||
assert_eq!(get_obj(get_obj(d.as_ref().unwrap(), "Usng").unwrap(), "Type"), Some(&recorded));
|
||||
for depth in [8, 16] {
|
||||
s.execute("file.new", json!({"width": 16, "height": 12, "depth": depth})).unwrap();
|
||||
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
|
||||
assert!(played.get("failed").is_none(), "{played}");
|
||||
let photocraft_doc::Fill::Gradient { stops, midpoints, opacity_stops, .. } = active_fill(&s) else { panic!("not a gradient") };
|
||||
assert_eq!((stops.len(), midpoints, opacity_stops.len()), (3, vec![0.25, 0.7], 2));
|
||||
// One undo step.
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert!(!matches!(s.active().unwrap().doc.layers.last().unwrap().content, photocraft_doc::LayerContent::Fill(_)));
|
||||
}
|
||||
}
|
||||
|
||||
/// #10771: PhotoCraft's own Gradient Fill steps export and load back as the same fill.
|
||||
#[test]
|
||||
fn gradient_fill_steps_export_and_import_back() {
|
||||
let set = json!({"style": "linear", "angle": 45, "stops": [[0, "#ff0000"], [0.25, "#00ff00"], [1, "#0000ff"]], "transparency": [[0, 100], [1, 50]], "midpoints": [0.3, 0.6]});
|
||||
let item = export_item("gradient.fill.set", &set, "S").unwrap();
|
||||
let Mapped::Steps(steps) = (event_for(&item.event).unwrap().from)(item.descriptor.as_ref().unwrap()) else { panic!("did not import") };
|
||||
let mut expected = set.clone();
|
||||
normalise(&mut expected);
|
||||
assert_eq!((steps[0].0.as_str(), without_hidden(&steps[0].1)), ("gradient.fill.set", expected));
|
||||
// The two-colour Make plays as the same two stops at full opacity.
|
||||
let item = export_item("layer.newFillLayer.gradient", &json!({"from": "#ff0000", "to": "#0000ff", "angle": 45}), "S").unwrap();
|
||||
let Mapped::Steps(steps) = (event_for(&item.event).unwrap().from)(item.descriptor.as_ref().unwrap()) else { panic!("did not import") };
|
||||
let mut expected = json!({"angle": 45, "stops": [[0, "#ff0000"], [1, "#0000ff"]], "transparency": [[0, 100], [1, 100]], "midpoints": []});
|
||||
normalise(&mut expected);
|
||||
assert_eq!((steps[0].0.as_str(), without_hidden(&steps[0].1)), ("layer.newFillLayer.gradient", expected));
|
||||
// Stops replace `from` and `to` when it plays, so a Make with all three exports its stops.
|
||||
let p = json!({"from": "#ff0000", "to": "#0000ff", "stops": [[0, "#00ff00"], [1, "#ffffff"]], "transparency": [[0, 100], [1, 100]]});
|
||||
let item = export_item("layer.newFillLayer.gradient", &p, "S").unwrap();
|
||||
let Mapped::Steps(steps) = (event_for(&item.event).unwrap().from)(item.descriptor.as_ref().unwrap()) else { panic!("did not import") };
|
||||
assert_eq!(steps[0].1["stops"], json!([[0.0, "#00ff00"], [1.0, "#ffffff"]]));
|
||||
// What the event cannot hold is refused: a Set without its transparency, toolbox colours,
|
||||
// dragged handles, a path, a midpoint off a whole percent.
|
||||
for (id, p) in [
|
||||
("gradient.fill.set", json!({"stops": [[0, "#ff0000"], [1, "#0000ff"]]})),
|
||||
("gradient.fill.set", json!({"stops": [[0, "foreground"], [1, "#0000ff"]], "transparency": [[0, 100], [1, 100]]})),
|
||||
("gradient.fill.set", json!({"from": [0, 0], "stops": [[0, "#ff0000"], [1, "#0000ff"]], "transparency": [[0, 100], [1, 100]]})),
|
||||
("gradient.fill.set", json!({"stops": [[0, "#ff0000"], [1, "#0000ff"]], "transparency": [[0, 100], [1, 100]], "midpoints": [0.333]})),
|
||||
("layer.newFillLayer.gradient", json!({"from": "#ff0000", "to": "#0000ff", "path": "work"})),
|
||||
("layer.newFillLayer.gradient", json!({"from": "#ff0000"})),
|
||||
] {
|
||||
assert!(export_item(id, &p, "S").is_none(), "{id}: {p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #10771: a Noise gradient, smoothness below 100 % or a transparency midpoint stay Photoshop
|
||||
/// steps rather than playing as a different fill.
|
||||
#[test]
|
||||
fn gradient_fills_the_command_cannot_play_stay_photoshop_steps() {
|
||||
// `with` appends; these replace the recorded value.
|
||||
fn replaced(mut d: Descriptor, key: &str, v: D) -> Descriptor {
|
||||
d.items.retain(|(k, _)| !k.is(key));
|
||||
d.with(key, v)
|
||||
}
|
||||
let base = recorded_gradient([50, 50, 50]);
|
||||
let with_grad = |f: &dyn Fn(Descriptor) -> Descriptor| {
|
||||
let g = get_obj(&base, "Grad").unwrap().clone();
|
||||
replaced(base.clone(), "Grad", D::Descriptor(f(g)))
|
||||
};
|
||||
let trns_mid = desc("TrnS").with("Opct", pct(100.0)).with("Lctn", D::Integer(0)).with("Mdpn", D::Integer(30));
|
||||
let trns_end = desc("TrnS").with("Opct", pct(100.0)).with("Lctn", D::Integer(4096)).with("Mdpn", D::Integer(50));
|
||||
let trns = |at: i32, o: f64| D::Descriptor(desc("TrnS").with("Opct", pct(o)).with("Lctn", D::Integer(at)).with("Mdpn", D::Integer(50)));
|
||||
for t in [
|
||||
// A midpoint outside the dialog's 5..95 % would play clamped.
|
||||
recorded_gradient([50, 2, 50]),
|
||||
recorded_gradient([50, 50, 97]),
|
||||
// Transparency stops out of range or out of order would play clamped and sorted.
|
||||
with_grad(&|g| replaced(g, "Trns", D::List(vec![trns(0, 100.0), trns(5000, 40.0)]))),
|
||||
with_grad(&|g| replaced(g, "Trns", D::List(vec![trns(0, 150.0), trns(4096, 40.0)]))),
|
||||
with_grad(&|g| replaced(g, "Trns", D::List(vec![trns(4096, 100.0), trns(0, 40.0)]))),
|
||||
// A Set without transparency stops would keep the layer's own.
|
||||
with_grad(&|mut g| {
|
||||
g.items.retain(|(k, _)| !k.is("Trns"));
|
||||
g
|
||||
}),
|
||||
with_grad(&|g| replaced(g, "GrdF", enm("GrdF", "ClNs"))),
|
||||
with_grad(&|g| replaced(g, "Intr", D::Double(2048.0))),
|
||||
with_grad(&|g| replaced(g, "Trns", D::List(vec![D::Descriptor(trns_mid.clone()), D::Descriptor(trns_end.clone())]))),
|
||||
base.clone().with("gradientsInterpolationMethod", enm("gradientInterpolationMethodType", "Perc")),
|
||||
] {
|
||||
let imp = import(&atn::write(&one_action(vec![gradient_set(t)])).unwrap()).unwrap();
|
||||
assert_eq!(imp.actions[0].steps[0].0, PHOTOSHOP_STEP);
|
||||
}
|
||||
// A Make whose new layer also gets a name, opacity, mode or clipping: the command plays none
|
||||
// of them, so the step stays as recorded.
|
||||
for (key, v) in [("Nm ", text("Sky")), ("Opct", pct(50.0)), ("Md ", enm("BlnM", "Mltp")), ("Grup", D::Boolean(true))] {
|
||||
let using = desc("contentLayer").with("Type", D::Descriptor(base.clone())).with(key, v);
|
||||
let make = item("Mk ", "Make", Some(desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(using))));
|
||||
let imp = import(&atn::write(&one_action(vec![make])).unwrap()).unwrap();
|
||||
assert_eq!(imp.actions[0].steps[0].0, PHOTOSHOP_STEP, "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
fn blend_if_entry(channel: &str, this: [i32; 4], under: Option<[i32; 4]>) -> D {
|
||||
let mut d = desc("Blnd").with("Chnl", channel_ref(Some(channel)));
|
||||
for (k, v) in ["SrcB", "Srcl", "SrcW", "Srcm"].into_iter().zip(this) {
|
||||
d = d.with(k, D::Integer(v));
|
||||
}
|
||||
if let Some(u) = under {
|
||||
for (k, v) in ["DstB", "Dstl", "DstW", "Dstt"].into_iter().zip(u) {
|
||||
d = d.with(k, D::Integer(v));
|
||||
}
|
||||
}
|
||||
D::Descriptor(d)
|
||||
}
|
||||
|
||||
fn layer_set(t: Descriptor) -> AtnItem {
|
||||
item("setd", "Set", Some(desc("null").with("null", target_ref("Lyr ")).with("T ", D::Descriptor(t))))
|
||||
}
|
||||
|
||||
fn blend_layers(depth: u8) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("edit.fill", json!({"color": "#808080"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn active_info(s: &Session) -> Value {
|
||||
let st = s.active().unwrap();
|
||||
crate::inspect::layer(st.doc.layer(st.active_layer.unwrap()).unwrap())
|
||||
}
|
||||
|
||||
/// #10771: Blend If loads as `layer.layerStyle.blendingOptions` and plays (it used to be a
|
||||
/// silent no-op), on 8- and 16-bit documents, Gray and a colour channel, split sliders.
|
||||
#[test]
|
||||
fn blend_if_imports_and_plays() {
|
||||
let blnd = D::List(vec![blend_if_entry("gray", [0, 30, 200, 255], Some([10, 10, 240, 250])), blend_if_entry("red", [20, 40, 255, 255], None)]);
|
||||
for depth in [8, 16] {
|
||||
let mut s = blend_layers(depth);
|
||||
let loaded = s
|
||||
.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![layer_set(desc("Lyr ").with("Blnd", blnd.clone()))])).unwrap())}))
|
||||
.unwrap();
|
||||
assert_eq!(loaded["unsupported"], json!([]), "{loaded}");
|
||||
let mut expected = json!({"blendIf": [{"channel": "gray", "thisLayer": [0, 30, 200, 255], "underlying": [10, 10, 240, 250]}, {"channel": "red", "thisLayer": [20, 40, 255, 255]}]});
|
||||
normalise(&mut expected);
|
||||
let (id, p) = &s.actions.list[0].steps[0];
|
||||
assert_eq!((id.as_str(), p), ("layer.layerStyle.blendingOptions", &expected));
|
||||
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
|
||||
assert!(played.get("failed").is_none(), "{played}");
|
||||
let b = active_info(&s)["blendIf"].clone();
|
||||
assert_eq!(b[0], json!({"channel": 0, "thisLayer": [0, 30, 200, 255], "underlying": [10, 10, 240, 250]}), "{b}");
|
||||
assert_eq!(b[1], json!({"channel": 1, "thisLayer": [20, 40, 255, 255], "underlying": [0, 0, 255, 255]}), "{b}");
|
||||
// It saves back as the same `Blnd`.
|
||||
let (_, d) = saved_first(&mut s);
|
||||
assert_eq!(get_obj(d.as_ref().unwrap(), "T ").unwrap().get("Blnd"), Some(&blnd));
|
||||
}
|
||||
}
|
||||
|
||||
/// #10771: the Blending Options dialog's OK (opacity, fill, mode and Blend If in one Set) is one
|
||||
/// step that applies them all; a Set that also renames splits into setProps and Blend If.
|
||||
#[test]
|
||||
fn blend_if_with_the_dialog_options_is_one_step_and_a_rename_splits() {
|
||||
let blnd = D::List(vec![blend_if_entry("gray", [0, 0, 128, 255], None)]);
|
||||
let dialog = desc("Lyr ").with("Opct", pct(40.0)).with("fillOpacity", pct(70.0)).with("Md ", enm("BlnM", "Mltp")).with("Blnd", blnd.clone());
|
||||
let mut s = blend_layers(8);
|
||||
s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![layer_set(dialog.clone())])).unwrap())})).unwrap();
|
||||
let steps = &s.actions.list[0].steps;
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert_eq!(steps[0].0, "layer.layerStyle.blendingOptions");
|
||||
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
|
||||
assert!(played.get("failed").is_none(), "{played}");
|
||||
let info = active_info(&s);
|
||||
assert!((info["opacity"].as_f64().unwrap() - 0.4).abs() < 1e-3, "{info}");
|
||||
assert_eq!(info["blend"], json!("Multiply"), "{info}");
|
||||
assert_eq!(info["blendIf"][0]["thisLayer"], json!([0, 0, 128, 255]), "{info}");
|
||||
let (_, d) = saved_first(&mut s);
|
||||
assert_eq!(get_obj(d.as_ref().unwrap(), "T "), Some(&dialog));
|
||||
// With a rename the Set is not the dialog's: the name and opacity go through setProps.
|
||||
let mut s = blend_layers(8);
|
||||
s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![layer_set(desc("Lyr ").with("Nm ", text("Renamed")).with("Opct", pct(40.0)).with("Blnd", blnd))])).unwrap())}))
|
||||
.unwrap();
|
||||
let ids: Vec<&str> = s.actions.list[0].steps.iter().map(|(id, _)| id.as_str()).collect();
|
||||
assert!(ids.contains(&"layer.setProps") && ids.contains(&"layer.layerStyle.blendingOptions"), "{ids:?}");
|
||||
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
|
||||
assert!(played.get("failed").is_none(), "{played}");
|
||||
let info = active_info(&s);
|
||||
assert_eq!(info["name"], json!("Renamed"));
|
||||
assert_eq!(info["blendIf"][0]["thisLayer"], json!([0, 0, 128, 255]), "{info}");
|
||||
}
|
||||
|
||||
/// #10771: the Layer Style dialog's OK on a layer without effects also records the effects'
|
||||
/// scale (`Lefx` = {Scl}). With Blend If it is still the dialog's one step and saves back with it.
|
||||
#[test]
|
||||
fn blend_if_with_the_recorded_effects_scale_saves_back_unchanged() {
|
||||
let blnd = D::List(vec![blend_if_entry("gray", [10, 20, 200, 230], Some([0, 0, 255, 255]))]);
|
||||
let dialog = desc("Lyr ").with("Opct", pct(80.0)).with("Blnd", blnd.clone()).with("Lefx", D::Descriptor(desc("Lefx").with("Scl ", pct(100.0))));
|
||||
let mut s = blend_layers(8);
|
||||
s.execute("actions.load", json!({"data": b64(&atn::write(&one_action(vec![layer_set(dialog.clone())])).unwrap())})).unwrap();
|
||||
let steps = &s.actions.list[0].steps;
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert_eq!(steps[0].0, "layer.layerStyle.blendingOptions");
|
||||
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
|
||||
assert!(played.get("failed").is_none(), "{played}");
|
||||
let info = active_info(&s);
|
||||
assert!((info["opacity"].as_f64().unwrap() - 0.8).abs() < 1e-3, "{info}");
|
||||
assert_eq!(info["blendIf"][0]["thisLayer"], json!([10, 20, 200, 230]), "{info}");
|
||||
let (_, d) = saved_first(&mut s);
|
||||
assert_eq!(get_obj(d.as_ref().unwrap(), "T "), Some(&dialog));
|
||||
// A `Lefx` with an effect in it is not the scale alone: the step is not the dialog's.
|
||||
let with_fx = desc("Lyr ").with("Blnd", blnd).with("Lefx", D::Descriptor(desc("Lefx").with("Scl ", pct(100.0)).with("DrSh", D::Descriptor(desc("DrSh")))));
|
||||
let imp = import(&atn::write(&one_action(vec![layer_set(with_fx)])).unwrap()).unwrap();
|
||||
assert!(imp.actions[0].steps.iter().all(|(_, p)| p.get("__atnEffectsScale").is_none()), "{:?}", imp.actions[0].steps);
|
||||
// Nor can it play without the shadow: it stays the recorded step.
|
||||
assert_eq!(imp.actions[0].steps.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>(), [PHOTOSHOP_STEP], "{:?}", imp.actions[0].steps);
|
||||
}
|
||||
|
||||
/// #10771: Blend If entries that are not whole levels, out of order, with half the Underlying
|
||||
/// sliders or an unknown key stay Photoshop steps.
|
||||
#[test]
|
||||
fn blend_if_the_command_cannot_play_stays_a_photoshop_step() {
|
||||
let with = |key: &str| match blend_if_entry("gray", [0, 0, 255, 255], None) {
|
||||
D::Descriptor(d) => D::Descriptor(d.with(key, D::Integer(3))),
|
||||
e => e,
|
||||
};
|
||||
let (half, unknown) = (with("DstB"), with("Zzzz"));
|
||||
let inverted = blend_if_entry("gray", [0, 200, 100, 255], None);
|
||||
for e in [blend_if_entry("gray", [0, 0, 300, 255], None), inverted, half, unknown] {
|
||||
let imp = import(&atn::write(&one_action(vec![layer_set(desc("Lyr ").with("Blnd", D::List(vec![e])))])).unwrap()).unwrap();
|
||||
assert_eq!(imp.actions[0].steps[0].0, PHOTOSHOP_STEP);
|
||||
}
|
||||
for p in [
|
||||
json!({"blendIf": null}),
|
||||
json!({"blendIf": {"channel": 2, "thisLayer": [0, 255]}}),
|
||||
json!({"blendIf": {"channel": "gray", "thisLayer": [200, 100]}}),
|
||||
json!({"blendIf": {"channel": "gray", "underlying": [0, 255]}}),
|
||||
] {
|
||||
assert!(export_item("layer.layerStyle.blendingOptions", &p, "S").is_none(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Save one action of steps through `actions.save`, returning the skipped list and the steps
|
||||
/// `actions.load` reads back.
|
||||
fn save_and_reload(steps: Vec<(String, Value)>) -> (Value, Vec<(String, Value)>) {
|
||||
|
||||
@@ -16,7 +16,7 @@ use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
use photocraft_cms::{Builtin, ColorSpace, GamutCheck, Intent, Lut3d, Profile, SampleKind, Transform};
|
||||
use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_doc::{DocId, Document, Duotone, Effect, Fill, FxPaint, Layer, LayerContent};
|
||||
use photocraft_doc::{DocId, Document, Duotone, Effect, Fill, FxPaint, Layer, LayerContent, TextStyles};
|
||||
use photocraft_raster::Surface;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -763,6 +763,26 @@ fn convert_layer_colors(l: &mut Layer, cc: &mut dyn FnMut(&mut Color)) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `cc` to every colour a type style sets (character styles, paragraph styles and Basic
|
||||
/// Paragraph), so type converted with its document still matches its styles instead of showing
|
||||
/// a local override.
|
||||
fn convert_style_colors(st: &mut TextStyles, cc: &mut dyn FnMut(&mut Color)) {
|
||||
let sets = st
|
||||
.character
|
||||
.iter_mut()
|
||||
.map(|c| &mut c.attrs)
|
||||
.chain(st.paragraph.iter_mut().chain([&mut st.basic]).flat_map(|p| [&mut p.para_attrs, &mut p.char_attrs]));
|
||||
for attrs in sets {
|
||||
for v in attrs.values_mut().filter(|v| v.is_object()) {
|
||||
let Ok(mut c) = serde_json::from_value::<Color>(v.clone()) else { continue };
|
||||
cc(&mut c);
|
||||
if let Ok(n) = serde_json::to_value(c) {
|
||||
*v = n;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paint_colors(p: &mut FxPaint, cc: &mut dyn FnMut(&mut Color)) {
|
||||
match p {
|
||||
FxPaint::Color(c) => cc(c),
|
||||
@@ -793,6 +813,7 @@ pub fn convert_document(doc: &mut Document, dst: &Profile, intent: Intent, bpc:
|
||||
convert_layer_colors(l, &mut |c| convert_color(c, from_mode, to_mode, &t));
|
||||
// Preserved PSD blocks describing colours in the old mode no longer apply.
|
||||
}
|
||||
convert_style_colors(&mut doc.text_styles, &mut |c| convert_color(c, from_mode, to_mode, &t));
|
||||
doc.mode = to_mode;
|
||||
doc.icc_profile = Some(dst.to_bytes());
|
||||
// Leaving Indexed / Duotone: the palette and inks no longer apply.
|
||||
@@ -819,6 +840,12 @@ fn ink_duotone(doc: &mut Document) {
|
||||
}
|
||||
});
|
||||
}
|
||||
convert_style_colors(&mut doc.text_styles, &mut |c| {
|
||||
if matches!(c.mode, ColorMode::Grayscale | ColorMode::Duotone) {
|
||||
let [r, g, b] = d.render(c.c[0]);
|
||||
*c = Color::rgba(r, g, b, c.alpha);
|
||||
}
|
||||
});
|
||||
doc.mode = ColorMode::Rgb;
|
||||
doc.icc_profile = Some(Builtin::Srgb.profile().to_bytes());
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use rayon::prelude::*;
|
||||
|
||||
use super::{
|
||||
ColorMode, Document, EngineError, Intent, PixelFormat, Profile, Result, SampleType, Surface, Transform, cms_err, convert_color, convert_document,
|
||||
convert_layer_colors, convert_surface, document_profile, space_mode,
|
||||
convert_layer_colors, convert_style_colors, convert_surface, document_profile, space_mode,
|
||||
};
|
||||
|
||||
const TILE_PIXELS: u128 = (TILE_SIZE * TILE_SIZE) as u128;
|
||||
@@ -197,6 +197,7 @@ pub(super) fn convert(doc: &mut Document, dst: &Profile, intent: Intent, bpc: bo
|
||||
for layer in &mut doc.layers {
|
||||
convert_layer_colors(layer, &mut |c| convert_color(c, from, to_mode, &t));
|
||||
}
|
||||
convert_style_colors(&mut doc.text_styles, &mut |c| convert_color(c, from, to_mode, &t));
|
||||
doc.mode = to_mode;
|
||||
doc.icc_profile = Some(dst.to_bytes());
|
||||
doc.color_table = None;
|
||||
|
||||
@@ -69,6 +69,7 @@ fn scratch_doc(doc: &Document) -> Document {
|
||||
copies.icc_profile = doc.icc_profile.clone();
|
||||
copies.resolution_dpi = doc.resolution_dpi;
|
||||
copies.patterns = doc.patterns.clone();
|
||||
copies.text_styles = doc.text_styles.clone();
|
||||
copies
|
||||
}
|
||||
|
||||
@@ -576,8 +577,10 @@ fn paste_layers(s: &mut Session, layers: &Document, dx: i32, dy: i32, board: Opt
|
||||
linked.push((*signature, *key, missing));
|
||||
}
|
||||
}
|
||||
let styles = std::mem::take(&mut copies.text_styles);
|
||||
let id = s.edit("Paste", |doc, active| {
|
||||
doc.patterns.extend(patterns);
|
||||
crate::layer_copy_cmds::land_text_styles(doc, styles);
|
||||
doc.metadata.psd_global_blocks.extend(linked);
|
||||
// The first pasted layer goes where a new layer would; the rest stack above it.
|
||||
let mut place = crate::layer_place::Place::AutoEditable;
|
||||
|
||||
@@ -112,6 +112,7 @@ pub(super) fn content_aware_scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (w, h) = (region.width() as usize, region.height() as usize);
|
||||
let (nw, nh) = (dst.width() as usize, dst.height() as usize);
|
||||
let label = "Content-Aware Scale";
|
||||
let background = s.tools.background;
|
||||
// A background job when started with `Session::start` (#210): seam carving runs on a worker
|
||||
// against the document snapshot and checks for cancellation before every seam.
|
||||
crate::jobs::run(
|
||||
@@ -128,8 +129,11 @@ pub(super) fn content_aware_scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
},
|
||||
move |s, out| {
|
||||
s.edit(label, |doc, _| {
|
||||
// The scaled area is vacated as Delete leaves it: transparent, or on the Background,
|
||||
// which can't hold transparency, the background colour (Photoshop).
|
||||
writable_surface(doc, id)?;
|
||||
crate::edit_cmds::clear_area(doc, id, region, None, background)?;
|
||||
let surf = writable_surface(doc, id)?;
|
||||
crate::pixels::try_clear_surface(surf, region, None)?;
|
||||
surf.write_region(dst, &out);
|
||||
surf.prune();
|
||||
Ok(())
|
||||
|
||||
@@ -14,6 +14,10 @@ fn px(s: &Session, x: i32, y: i32) -> Vec<f32> {
|
||||
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)
|
||||
}
|
||||
|
||||
fn px_rgba(s: &Session, x: i32, y: i32) -> [f32; 4] {
|
||||
active(s).surface().unwrap().rgba(x, y)
|
||||
}
|
||||
|
||||
fn active(s: &Session) -> &Layer {
|
||||
let st = s.active().unwrap();
|
||||
st.doc.layer(st.active_layer.unwrap()).unwrap()
|
||||
@@ -545,6 +549,38 @@ fn content_aware_scale_keeps_subject() {
|
||||
}
|
||||
}
|
||||
|
||||
/// On the Background, which can't hold transparency, the area a selection's Content-Aware Scale
|
||||
/// vacates takes the background colour, as Delete leaves it (Photoshop); the layer stays the
|
||||
/// Background. On a normal layer it is left transparent.
|
||||
#[test]
|
||||
fn content_aware_scale_on_the_background_vacates_to_the_background_colour() {
|
||||
for depth in [8, 16] {
|
||||
let mut s = session(depth);
|
||||
s.tools.background = [0.0, 0.0, 1.0, 1.0];
|
||||
let id = s.active().unwrap().active_layer.unwrap();
|
||||
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 10})).unwrap();
|
||||
let r = s.execute("edit.contentAwareScale", json!({"width": 10})).unwrap();
|
||||
assert_eq!(r["bounds"], json!([10, 10, 10, 10]), "{depth}-bit");
|
||||
let st = s.active().unwrap();
|
||||
assert!(st.doc.is_background(id), "{depth}-bit: still the Background");
|
||||
let px = |x, y| st.doc.layer(id).unwrap().surface().unwrap().rgba(x, y);
|
||||
for (x, y) in [(20, 10), (25, 15), (29, 19)] {
|
||||
assert_eq!(px(x, y), [0.0, 0.0, 1.0, 1.0], "{depth}-bit: ({x}, {y}) is vacated");
|
||||
}
|
||||
assert_eq!(px(12, 15), [1.0, 1.0, 1.0, 1.0], "{depth}-bit: the scaled pixels");
|
||||
assert_eq!(px(5, 5), [1.0, 1.0, 1.0, 1.0], "{depth}-bit: outside the selection");
|
||||
// A normal layer's vacated area is transparent.
|
||||
let mut s = session(depth);
|
||||
s.tools.background = [0.0, 0.0, 1.0, 1.0];
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 10})).unwrap();
|
||||
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("edit.contentAwareScale", json!({"width": 10})).unwrap();
|
||||
assert_eq!(px_rgba(&s, 25, 15)[3], 0.0, "{depth}-bit: a layer's hole is transparent");
|
||||
assert_eq!(px_rgba(&s, 12, 15), [1.0, 0.0, 0.0, 1.0], "{depth}-bit");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_aware_scale_params() {
|
||||
let mut s = session(8);
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_algo::resample::{Resample, translate_surface};
|
||||
use photocraft_algo::resample::{Resample, resize_surface, translate_surface};
|
||||
use photocraft_color::{ColorMode, PixelFormat};
|
||||
use photocraft_doc::{Affine, Document, Layer, LayerContent, LayerId, SmartObject, SmartSource};
|
||||
use photocraft_geom::Rect;
|
||||
@@ -25,6 +25,7 @@ mod export;
|
||||
mod info;
|
||||
mod open;
|
||||
mod paths;
|
||||
mod place_steps;
|
||||
mod processing;
|
||||
mod raw_open;
|
||||
mod save;
|
||||
@@ -47,7 +48,7 @@ pub use info::{CAMERA_FIELDS, camera_data, read_file_info, write_file_info};
|
||||
use info::{exposure_text, find_element};
|
||||
pub(crate) use open::{BatchOpen, batch_open_notice, batch_open_params, remember_batch_open};
|
||||
pub use open::{PLACE_EMBEDDED, open_bytes_as, open_bytes_as_with_options, place_bytes, raw_defaults};
|
||||
pub(crate) use open::{PlaceInput, apply_place, import, import_with_options, prepare_place, tag_exr_colorspace};
|
||||
pub(crate) use open::{PlaceInput, apply_place, import, import_with_options, tag_exr_colorspace};
|
||||
use open::{approve_memory, close_all, close_others, open_as, place, revert};
|
||||
use paths::is_file;
|
||||
#[cfg(test)]
|
||||
@@ -57,6 +58,7 @@ pub use paths::{
|
||||
template_name, untitled_name,
|
||||
};
|
||||
pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, read_file, read_file_limited, sanitize, stem, write_file};
|
||||
pub(crate) use place_steps::PlaceSteps;
|
||||
use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatten_all_masks, image_processor, load_files_into_stack};
|
||||
use save::save_a_copy;
|
||||
pub(crate) use save::{SaveOpts, encode, save_doc};
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
use super::paths::{file_name, read_file, stem, template_name};
|
||||
use super::{
|
||||
Affine, Arc, Document, EngineError, Layer, LayerContent, LayerId, PixelFormat, Resample, Result, Session, SmartObject, SmartSource, Value, f64_param, json,
|
||||
str_param, translate_surface,
|
||||
};
|
||||
use crate::jobs::JobCtx;
|
||||
use super::{Arc, Document, EngineError, Layer, LayerContent, LayerId, PixelFormat, PlaceSteps, Result, Session, Value, json, str_param};
|
||||
|
||||
/// Input and successfully opened document identities of one Override Open scratch session.
|
||||
pub(crate) struct BatchOpen {
|
||||
@@ -287,7 +283,8 @@ pub(super) fn approve_memory(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// does not keep the tile share), and the import re-checks the exact split before decoding.
|
||||
let budget = photocraft_io::memory::resolve_budget_with_scratch(photocraft_io::memory::MemorySnapshot::current(), None, u64::MAX);
|
||||
if preflight.required > budget.hard_limit {
|
||||
return Err(EngineError::PsdHardBudget { name: preflight.name, required: preflight.required, limit: budget.hard_limit });
|
||||
let free_memory = budget.refusal_free_memory(preflight.required);
|
||||
return Err(EngineError::PsdHardBudget { name: preflight.name, required: preflight.required, limit: budget.hard_limit, free_memory });
|
||||
}
|
||||
let started = s.start_open_approved_with_background(
|
||||
&preflight.name,
|
||||
@@ -325,46 +322,49 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec<u8>, linked: Option<S
|
||||
/// Run a place: in the background when the command was started with [`Session::start`].
|
||||
fn place_input(s: &mut Session, input: PlaceInput) -> Result<Value> {
|
||||
let label = input.job_label();
|
||||
crate::jobs::run(s, &label, true, move |ctx| prepare_place(input, ctx), apply_place)
|
||||
crate::jobs::run_stepped(s, &label, true, PlaceSteps::new(input, s.cooperative_jobs()), apply_place)
|
||||
}
|
||||
|
||||
/// The file a place reads.
|
||||
enum PlaceFile {
|
||||
pub(super) enum PlaceFile {
|
||||
/// Its contents, already read (a dropped or picked file with no path, a script's bytes).
|
||||
Bytes(Vec<u8>),
|
||||
/// Its path, read by [`prepare_place`]: on the job's worker when the place runs in the
|
||||
Bytes(Arc<Vec<u8>>),
|
||||
/// Its path, read by [`PlaceSteps`]: on the job's worker when the place runs in the
|
||||
/// background, so a large file doesn't hold up the window while it is read.
|
||||
Path(String),
|
||||
}
|
||||
|
||||
/// Everything a place reads from the session, taken up front so [`prepare_place`] can run on a
|
||||
/// Everything a place reads from the session, taken up front so [`PlaceSteps`] can run on a
|
||||
/// worker that never sees the [`Session`].
|
||||
pub(crate) struct PlaceInput {
|
||||
name: String,
|
||||
file: PlaceFile,
|
||||
linked: Option<String>,
|
||||
params: Value,
|
||||
canvas: (f64, f64),
|
||||
fmt: PixelFormat,
|
||||
opts: photocraft_io::ImportOptions,
|
||||
pub(super) name: String,
|
||||
pub(super) file: PlaceFile,
|
||||
pub(super) linked: Option<String>,
|
||||
pub(super) params: Value,
|
||||
pub(super) canvas: (f64, f64),
|
||||
pub(super) fmt: PixelFormat,
|
||||
pub(super) opts: photocraft_io::ImportOptions,
|
||||
/// Preferences ▸ General ▸ Resize Image During Place, unless the params say otherwise.
|
||||
fit: bool,
|
||||
pub(super) fit: bool,
|
||||
/// Preferences ▸ General ▸ Always Create Smart Objects When Placing, unless the params say
|
||||
/// otherwise. A linked place is always a smart object.
|
||||
smart: bool,
|
||||
pub(super) smart: bool,
|
||||
/// The document as the job sees it, for rendering a vector source at its placement scale. A
|
||||
/// path isn't read yet, so whether it is a vector source is decided once it is.
|
||||
doc: Option<Arc<Document>>,
|
||||
pub(super) doc: Option<Arc<Document>>,
|
||||
/// The frame the image goes into: the active layer's, `"frame"` in the params, or none
|
||||
/// (`"frame": false`). Its image renders through a smart object.
|
||||
frame: Option<(LayerId, photocraft_doc::Frame)>,
|
||||
pub(super) frame: Option<(LayerId, photocraft_doc::Frame)>,
|
||||
}
|
||||
|
||||
impl PlaceInput {
|
||||
/// The input of a place of `bytes` already read (named `name`; `linked`: Place Linked to that path).
|
||||
pub(crate) fn new(s: &Session, name: &str, bytes: Vec<u8>, linked: Option<String>, p: &Value) -> Result<Self> {
|
||||
Self::with_file(s, name, PlaceFile::Bytes(bytes), linked, p)
|
||||
Self::with_file(s, name, PlaceFile::Bytes(Arc::new(bytes)), linked, p)
|
||||
}
|
||||
|
||||
/// The input of a place of `file`, with the destination (canvas or frame), preferences and
|
||||
/// import settings taken from the session up front.
|
||||
fn with_file(s: &Session, name: &str, file: PlaceFile, linked: Option<String>, p: &Value) -> Result<Self> {
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let prefs = s.prefs();
|
||||
@@ -430,115 +430,15 @@ impl PlaceInput {
|
||||
|
||||
/// A place decoded, flattened and fitted, ready to be inserted by [`apply_place`].
|
||||
pub(crate) struct Prepared {
|
||||
content: LayerContent,
|
||||
layer_name: String,
|
||||
pub(super) content: LayerContent,
|
||||
pub(super) layer_name: String,
|
||||
/// The history step's name.
|
||||
label: &'static str,
|
||||
scale: f64,
|
||||
bounds: [f64; 4],
|
||||
smart: bool,
|
||||
pub(super) label: &'static str,
|
||||
pub(super) scale: f64,
|
||||
pub(super) bounds: [f64; 4],
|
||||
pub(super) smart: bool,
|
||||
/// The frame the layer fills, if any (it becomes the frame's content instead of a new layer).
|
||||
frame: Option<LayerId>,
|
||||
}
|
||||
|
||||
/// The heavy part of a place: read (a path), decode, flatten, resize and translate (and render a
|
||||
/// vector source at its placement scale). Touches no [`Session`], so it can run on a worker; `ctx`
|
||||
/// reports progress and stops it between stages when cancelled.
|
||||
pub(crate) fn prepare_place(input: PlaceInput, ctx: &JobCtx) -> Result<Prepared> {
|
||||
let PlaceInput { name, file, linked, params: p, canvas: (cw, ch), fmt, opts, fit, smart, doc, frame } = input;
|
||||
let bytes = match file {
|
||||
PlaceFile::Bytes(bytes) => bytes,
|
||||
PlaceFile::Path(path) => {
|
||||
ctx.progress(0.0, "Reading");
|
||||
let bytes = read_file(&path)?;
|
||||
ctx.check()?;
|
||||
bytes
|
||||
}
|
||||
};
|
||||
// Refuse before decoding if the operation cannot fit.
|
||||
crate::memory_gate::ensure(&format!("place \u{201c}{}\u{201d}", file_name(&name)), crate::memory_gate::place_need(&bytes, fmt.bytes_per_pixel()))?;
|
||||
let doc = doc.filter(|_| frame.is_some() || photocraft_io::is_svg_input(&name, &bytes));
|
||||
let imported = ctx.stage(0.0, 0.6, "Decoding", |ctl| photocraft_io::import_with_options_and_interrupt(&name, &bytes, &opts, ctl)).map_err(|e| match e {
|
||||
photocraft_io::IoError::Cancelled => EngineError::Cancelled,
|
||||
e => crate::error::io_open_error(&name, e),
|
||||
})?;
|
||||
if imported.preview_only {
|
||||
return Err(EngineError::Other(format!(
|
||||
"{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here"
|
||||
)));
|
||||
}
|
||||
ctx.check()?;
|
||||
let src = imported.document;
|
||||
let (w, h) = (src.size.width as f64, src.size.height as f64);
|
||||
let scale = match f64_param(&p, "scale") {
|
||||
Some(k) => (k / 100.0).max(1e-4),
|
||||
None if frame.is_some() && fit => (cw / w).max(ch / h),
|
||||
None if fit && (w > cw || h > ch) => (cw / w).min(ch / h),
|
||||
None => 1.0,
|
||||
};
|
||||
let center = match p.get("center").and_then(Value::as_array) {
|
||||
Some(c) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)),
|
||||
_ => (cw / 2.0, ch / 2.0),
|
||||
};
|
||||
let (dx, dy) = ((center.0 - w * scale / 2.0).round(), (center.1 - h * scale / 2.0).round());
|
||||
// A frame's image renders through its smart object below, which refuses a placement past the
|
||||
// memory budget; resampling it to the frame's size first would allocate that surface twice.
|
||||
let px = if frame.is_none() {
|
||||
ctx.progress(0.6, "Flattening");
|
||||
super::check_flattenable(&src, "file.place")?;
|
||||
let bounds = src.bounds();
|
||||
let mut px = ctx
|
||||
.stage(0.6, 0.7, "Flattening", |ctl| photocraft_compose::composite_to_surface_with_interrupt(&src, bounds, fmt, None, ctl))
|
||||
.map_err(|_| EngineError::Cancelled)?;
|
||||
ctx.check()?;
|
||||
if (scale - 1.0).abs() > 1e-9 {
|
||||
ctx.progress(0.7, "Resizing");
|
||||
px = ctx
|
||||
.stage(0.7, 0.9, "Resizing", |ctl| photocraft_algo::resample::resize_surface_with_interrupt(&px, scale, scale, Resample::Bicubic, ctl))
|
||||
.map_err(|_| EngineError::Cancelled)?;
|
||||
ctx.check()?;
|
||||
}
|
||||
Some(translate_surface(&px, dx as i32, dy as i32))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
drop(src);
|
||||
let placement = frame
|
||||
.as_ref()
|
||||
.map_or(Affine { m: [scale, 0.0, 0.0, scale, dx, dy] }, |(_, f)| f.transform.mul(&Affine { m: [scale / cw, 0.0, 0.0, scale / ch, dx / cw, dy / ch] }));
|
||||
let corners = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)].map(|(x, y)| placement.apply(photocraft_geom::Point::new(x, y)));
|
||||
let bounds = [
|
||||
corners.iter().map(|q| q.x).fold(f64::INFINITY, f64::min),
|
||||
corners.iter().map(|q| q.y).fold(f64::INFINITY, f64::min),
|
||||
corners.iter().map(|q| q.x).fold(f64::NEG_INFINITY, f64::max),
|
||||
corners.iter().map(|q| q.y).fold(f64::NEG_INFINITY, f64::max),
|
||||
];
|
||||
// A frame's image is always a smart object.
|
||||
let smart = smart || frame.is_some();
|
||||
let label = if linked.is_some() { "Place Linked" } else { PLACE_EMBEDDED };
|
||||
let content = if smart {
|
||||
let source = match linked {
|
||||
Some(path) => SmartSource::Linked { path },
|
||||
None => SmartSource::Embedded { file_name: file_name(&name), bytes: Arc::new(bytes) },
|
||||
};
|
||||
let mut so = SmartObject::new(source, placement, px);
|
||||
// A vector source (SVG) and a frame's image render at their placement scale instead of as
|
||||
// a resampled raster.
|
||||
if let Some(doc) = doc {
|
||||
ctx.progress(0.9, "Rendering");
|
||||
ctx.check()?;
|
||||
if let Some(sharp) = crate::smart_cmds::render(&doc, &so)? {
|
||||
so.cache = Some(sharp);
|
||||
}
|
||||
}
|
||||
if so.cache.is_none() {
|
||||
return Err(EngineError::Other(format!("{name}: the placed image could not be rendered")));
|
||||
}
|
||||
LayerContent::Smart(so)
|
||||
} else {
|
||||
LayerContent::Raster(px.ok_or_else(|| EngineError::Other(format!("{name}: a frame's image must be a smart object")))?)
|
||||
};
|
||||
Ok(Prepared { content, layer_name: stem(&name), label, scale, bounds, smart, frame: frame.map(|(id, _)| id) })
|
||||
pub(super) frame: Option<LayerId>,
|
||||
}
|
||||
|
||||
/// Insert the prepared layer as one undo step and report the place. Runs on the session's thread.
|
||||
|
||||
@@ -249,7 +249,7 @@ fn a_canvas_too_large_to_flatten_is_refused_as_before() {
|
||||
let before = steps(&s);
|
||||
match place_bytes(&mut s, "huge.pcraft", bytes.clone(), None, &json!({})) {
|
||||
Err(EngineError::BadParams { cmd, msg }) => {
|
||||
assert_eq!(cmd, "file.place");
|
||||
assert_eq!(cmd, "file.placeEmbedded");
|
||||
assert_eq!(msg, "the document's 40000×30000 canvas is too large to flatten");
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
@@ -260,3 +260,326 @@ fn a_canvas_too_large_to_flatten_is_refused_as_before() {
|
||||
assert!(err.contains("40000×30000 canvas is too large to flatten"), "{err}");
|
||||
assert_eq!(steps(&s), before, "nothing was placed");
|
||||
}
|
||||
|
||||
// ---------- place in steps, for a session with no worker threads (the web build) ----------
|
||||
|
||||
/// A pseudo-random PNG of `layout` and `sample`, so a wrong pixel anywhere shows and the file
|
||||
/// is big enough to take many rows.
|
||||
fn noise_png(w: u32, h: u32, layout: photocraft_codecs::ChannelLayout, sample: photocraft_codecs::SampleType, interlaced: bool) -> Vec<u8> {
|
||||
let len = w as usize * h as usize * layout.channels() * sample.bytes();
|
||||
let data: Vec<u8> = (0..len).map(|i| ((i.wrapping_mul(2_654_435_761) >> 13) ^ (i / 97)) as u8).collect();
|
||||
let img = photocraft_codecs::Image::from_raw(w, h, layout, sample, data).unwrap();
|
||||
photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &photocraft_codecs::EncodeOptions { png_interlaced: interlaced, ..Default::default() })
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A cooperative session whose polls each do one unit of work, so the polls a place needs do not
|
||||
/// depend on the machine's speed.
|
||||
fn stepping(w: u32, h: u32, depth: u32) -> Session {
|
||||
let mut s = session(w, h, depth);
|
||||
s.set_cooperative_jobs(true);
|
||||
s.set_job_step_budget(Duration::ZERO);
|
||||
s
|
||||
}
|
||||
|
||||
/// Polls until job `id` ends; returns its event and how many polls that took.
|
||||
fn poll_to_end(s: &mut Session, id: JobId) -> (JobEvent, usize) {
|
||||
for polls in 1..=1_000_000 {
|
||||
if let Some(e) = s.poll_jobs().into_iter().find(|e| e.id == id) {
|
||||
return (e, polls);
|
||||
}
|
||||
}
|
||||
panic!("job {id:?} never ended");
|
||||
}
|
||||
|
||||
/// A place a slice per poll equals the inline place: the same result, layer pixels, composite and
|
||||
/// one history step, for every kind of PNG, at every depth, for a smart object and a pixel layer,
|
||||
/// reduced to fit, left alone and enlarged.
|
||||
#[test]
|
||||
fn a_cooperative_place_equals_the_inline_place() {
|
||||
use photocraft_codecs::{ChannelLayout as L, SampleType as T};
|
||||
let dir = tmp("cooperative");
|
||||
let sources = [
|
||||
("rgb8.png", noise_png(320, 300, L::Rgb, T::U8, false)),
|
||||
("rgba16.png", noise_png(310, 301, L::Rgba, T::U16, false)),
|
||||
("gray8-interlaced.png", noise_png(300, 305, L::Gray, T::U8, true)),
|
||||
("graya8.png", noise_png(301, 300, L::GrayA, T::U8, false)),
|
||||
];
|
||||
for (file, bytes) in &sources {
|
||||
let path = join(&dir, file);
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
for depth in [8, 16, 32] {
|
||||
for smart in [true, false] {
|
||||
for scale in [None, Some(100), Some(180)] {
|
||||
let mut params = json!({"path": path, "smartObject": smart});
|
||||
if let Some(k) = scale {
|
||||
params["scale"] = json!(k);
|
||||
}
|
||||
let what = format!("{file} at {depth}-bit, smart {smart}, scale {scale:?}");
|
||||
let mut inline = session(150, 150, depth);
|
||||
let want = inline.execute("file.placeEmbedded", params.clone()).unwrap();
|
||||
|
||||
let mut s = stepping(150, 150, depth);
|
||||
let before = steps(&s);
|
||||
let id = job(s.start("file.placeEmbedded", params).unwrap());
|
||||
assert!(s.has_jobs(), "{what}");
|
||||
assert_eq!(steps(&s), before, "nothing is inserted before the job is applied");
|
||||
let (e, polls) = poll_to_end(&mut s, id);
|
||||
let JobOutcome::Done(got) = &e.outcome else { panic!("{what}: {e:?}") };
|
||||
assert!(polls > 3, "{what}: took {polls} polls");
|
||||
assert_eq!((e.command.as_str(), e.label.as_str()), ("file.placeEmbedded", &*format!("Placing {file}")));
|
||||
same_but_layer(got, &want);
|
||||
assert_eq!(steps(&s), before + 1, "{what}: one undo step");
|
||||
assert_eq!(s.active().unwrap().history.undo_label(), Some(PLACE_EMBEDDED));
|
||||
assert_eq!(layer_pixels(&s), layer_pixels(&inline), "{what}: layer pixels");
|
||||
assert_eq!(canvas_pixels(&s), canvas_pixels(&inline), "{what}: composite");
|
||||
if smart {
|
||||
// The embedded source is the file's bytes, shared with the decoder.
|
||||
let d = s.active().unwrap();
|
||||
let LayerContent::Smart(so) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("{what}") };
|
||||
assert!(matches!(&so.source, SmartSource::Embedded { bytes: b, .. } if **b == *bytes), "{what}");
|
||||
}
|
||||
assert!(s.undo(), "{what}");
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// With the real budget (8 ms a poll) the place ends the same, and Place Linked and bytes with no
|
||||
/// path take the same road.
|
||||
#[test]
|
||||
fn a_cooperative_place_with_the_default_budget_and_from_bytes() {
|
||||
let bytes = gradient_png(300, 320);
|
||||
let mut inline = session(120, 120, 16);
|
||||
let want = place_bytes(&mut inline, "drop.png", bytes.clone(), None, &json!({})).unwrap();
|
||||
|
||||
let mut s = session(120, 120, 16);
|
||||
s.set_cooperative_jobs(true);
|
||||
let id = job(s.start_place_bytes("drop.png", bytes.clone(), None, json!({})).unwrap());
|
||||
// The document is locked meanwhile, as for a worker.
|
||||
let refused = s.start_place_bytes("again.png", bytes.clone(), None, json!({})).unwrap_err().to_string();
|
||||
assert!(refused.contains("Placing drop.png"), "{refused}");
|
||||
let (e, _) = poll_to_end(&mut s, id);
|
||||
let JobOutcome::Done(got) = &e.outcome else { panic!("{e:?}") };
|
||||
same_but_layer(got, &want);
|
||||
assert_eq!(layer_pixels(&s), layer_pixels(&inline));
|
||||
assert_eq!(steps(&s), steps(&inline));
|
||||
|
||||
let dir = tmp("cooperative-linked");
|
||||
let path = join(&dir, "grad.png");
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
let id = job(s.start("file.placeLinked", json!({"path": path})).unwrap());
|
||||
assert!(matches!(poll_to_end(&mut s, id).0.outcome, JobOutcome::Done(_)));
|
||||
let d = s.active().unwrap();
|
||||
assert!(
|
||||
matches!(&d.doc.layer(d.active_layer.unwrap()).unwrap().content, LayerContent::Smart(so) if matches!(&so.source, SmartSource::Linked { path: p } if *p == path))
|
||||
);
|
||||
assert_eq!(d.history.undo_label(), Some("Place Linked"));
|
||||
}
|
||||
|
||||
/// An offset off the tile grid rebuilds the tiles the image touches, and a cooperative place does
|
||||
/// that a few tiles per poll rather than all of them in one: it takes at least a poll per source
|
||||
/// tile more than the same place on the grid, and ends with the same pixels as the inline place.
|
||||
#[test]
|
||||
fn a_cooperative_place_moves_its_pixels_a_few_tiles_per_poll() {
|
||||
let bytes = gradient_png(600, 520);
|
||||
let tiles = 3 * 3;
|
||||
let polls_at = |center: [i32; 2]| {
|
||||
let params = json!({"center": center, "smartObject": false});
|
||||
let mut inline = session(2000, 2000, 8);
|
||||
place_bytes(&mut inline, "drop.png", bytes.clone(), None, ¶ms).unwrap();
|
||||
let mut s = stepping(2000, 2000, 8);
|
||||
let id = job(s.start_place_bytes("drop.png", bytes.clone(), None, params).unwrap());
|
||||
let (e, polls) = poll_to_end(&mut s, id);
|
||||
assert!(matches!(e.outcome, JobOutcome::Done(_)), "{e:?}");
|
||||
assert_eq!(layer_pixels(&s), layer_pixels(&inline), "at {center:?}");
|
||||
polls
|
||||
};
|
||||
// The image lands at (256, 256), a whole number of tiles, or at (257, 3).
|
||||
let on_grid = polls_at([300 + 256, 260 + 256]);
|
||||
let off_grid = polls_at([300 + 257, 260 + 3]);
|
||||
assert!(off_grid >= on_grid + tiles, "{off_grid} polls off the grid, {on_grid} on it");
|
||||
}
|
||||
|
||||
/// `wait_job` runs a cooperative place to the end.
|
||||
#[test]
|
||||
fn wait_job_finishes_a_cooperative_place() {
|
||||
let bytes = gradient_png(300, 300);
|
||||
let mut inline = session(100, 100, 8);
|
||||
let want = place_bytes(&mut inline, "drop.png", bytes.clone(), None, &json!({})).unwrap();
|
||||
let mut s = stepping(100, 100, 8);
|
||||
let id = job(s.start_place_bytes("drop.png", bytes, None, json!({})).unwrap());
|
||||
s.poll_jobs();
|
||||
let got = s.wait_job(id).unwrap();
|
||||
same_but_layer(&got, &want);
|
||||
assert_eq!(layer_pixels(&s), layer_pixels(&inline));
|
||||
assert!(!s.has_jobs());
|
||||
}
|
||||
|
||||
/// Progress goes up through the stages and the status names them.
|
||||
#[test]
|
||||
fn a_cooperative_place_reports_its_progress() {
|
||||
let mut s = stepping(100, 100, 8);
|
||||
let id = job(s.start_place_bytes("drop.png", gradient_png(300, 300), None, json!({})).unwrap());
|
||||
let (mut last, mut messages) = (0.0f32, Vec::new());
|
||||
while s.job(id).is_some() {
|
||||
s.poll_jobs();
|
||||
if let Some(info) = s.job(id) {
|
||||
assert!(info.progress >= last && info.progress < 1.0, "{last} -> {}", info.progress);
|
||||
last = info.progress;
|
||||
if !info.message.is_empty() && messages.last() != Some(&info.message) {
|
||||
messages.push(info.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(last > 0.5, "{last}");
|
||||
assert_eq!(messages, ["Decoding", "Flattening", "Resizing", "Placing"]);
|
||||
}
|
||||
|
||||
/// Cancelling between polls leaves the document the very same one and unlocks it.
|
||||
#[test]
|
||||
fn cancelling_a_cooperative_place_between_polls_leaves_the_document_unchanged() {
|
||||
let mut s = stepping(100, 100, 8);
|
||||
let (doc, before) = (s.active().unwrap().doc.clone(), steps(&s));
|
||||
let id = job(s.start_place_bytes("drop.png", gradient_png(300, 300), None, json!({})).unwrap());
|
||||
for _ in 0..5 {
|
||||
assert!(s.poll_jobs().is_empty());
|
||||
}
|
||||
assert!(s.cancel_job(id));
|
||||
assert_eq!(wait_event(&mut s, id).outcome, JobOutcome::Cancelled);
|
||||
assert!(Arc::ptr_eq(&doc, &s.active().unwrap().doc));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert!(!s.active().unwrap().history.can_redo());
|
||||
assert!(s.active_job().is_none(), "the document is unlocked");
|
||||
assert!(matches!(s.wait_job(id), Err(EngineError::Cancelled)));
|
||||
}
|
||||
|
||||
/// A PNG that is damaged part-way through its image data fails the job, without a panic and with
|
||||
/// the document untouched; the rows before the damage are decoded first.
|
||||
#[test]
|
||||
fn a_cooperative_place_of_a_damaged_png_fails_cleanly() {
|
||||
use photocraft_codecs::{ChannelLayout as L, SampleType as T};
|
||||
let good = noise_png(320, 300, L::Rgb, T::U8, false);
|
||||
let mut flipped = good.clone();
|
||||
let mid = flipped.len() / 2;
|
||||
flipped[mid] ^= 0xFF;
|
||||
let cases = [
|
||||
("cut in half", good.get(..good.len() / 2).unwrap().to_vec()),
|
||||
("cut just after the header", good.get(..60).unwrap().to_vec()),
|
||||
("a damaged byte", flipped),
|
||||
("not a PNG", b"\x89PNG\r\n\x1a\nthen text".to_vec()),
|
||||
("empty", Vec::new()),
|
||||
];
|
||||
let mut s = stepping(100, 100, 8);
|
||||
let (doc, before) = (s.active().unwrap().doc.clone(), steps(&s));
|
||||
for (what, bytes) in cases {
|
||||
let Ok(Started::Job(id)) = s.start_place_bytes("bad.png", bytes, None, json!({})) else {
|
||||
// Refused before it started: also an error, not a panic.
|
||||
continue;
|
||||
};
|
||||
let (e, polls) = poll_to_end(&mut s, id);
|
||||
let JobOutcome::Failed(err) = &e.outcome else { panic!("{what}: {e:?}") };
|
||||
assert!(err.contains("bad.png"), "{what}: the file is named: {err}");
|
||||
if what == "cut in half" {
|
||||
assert!(polls > 20, "{what}: the rows before the cut are decoded first ({polls} polls)");
|
||||
}
|
||||
assert!(Arc::ptr_eq(&doc, &s.active().unwrap().doc), "{what}");
|
||||
assert_eq!(steps(&s), before, "{what}");
|
||||
assert!(s.active_job().is_none(), "{what}: unlocked");
|
||||
}
|
||||
}
|
||||
|
||||
/// The flatten in bands is the flatten in one go, for every colour model and depth.
|
||||
#[test]
|
||||
fn a_banded_flatten_equals_flattened_checked() {
|
||||
use super::place_steps::Flatten;
|
||||
use photocraft_codecs::{ChannelLayout as L, SampleType as T};
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
// Wide enough for two bands across, and several tile rows.
|
||||
let sources = [
|
||||
noise_png(2100, 600, L::Gray, T::U8, false),
|
||||
noise_png(700, 530, L::Rgb, T::U8, false),
|
||||
noise_png(300, 520, L::Rgba, T::U16, false),
|
||||
noise_png(260, 520, L::GrayA, T::U16, false),
|
||||
];
|
||||
let formats = [
|
||||
PixelFormat::new(ColorMode::Rgb, SampleType::U8, true),
|
||||
PixelFormat::new(ColorMode::Rgb, SampleType::U16, true),
|
||||
PixelFormat::new(ColorMode::Rgb, SampleType::F32, true),
|
||||
PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false),
|
||||
PixelFormat::new(ColorMode::Grayscale, SampleType::U16, true),
|
||||
];
|
||||
for bytes in &sources {
|
||||
let doc = photocraft_io::import("src.png", bytes).unwrap().document;
|
||||
for fmt in formats {
|
||||
let expected = flattened_checked(&doc, fmt, "file.placeEmbedded").unwrap();
|
||||
let mut flatten = Flatten::new(doc.clone(), true, fmt, "file.placeEmbedded").unwrap();
|
||||
let mut bands = 0;
|
||||
let got = loop {
|
||||
bands += 1;
|
||||
if let Some(px) = flatten.advance().unwrap() {
|
||||
break px;
|
||||
}
|
||||
};
|
||||
assert!(bands > 1, "{}x{}: {bands} bands", doc.size.width, doc.size.height);
|
||||
assert!(got == expected, "{}x{} {:?} {:?}: banded != whole", doc.size.width, doc.size.height, doc.mode, fmt);
|
||||
// Not banded is the plain flatten.
|
||||
let whole = Flatten::new(doc.clone(), false, fmt, "file.placeEmbedded").unwrap().advance().unwrap().unwrap();
|
||||
assert!(whole == expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An Indexed Color document (a palette PNG) flattens in bands to the same pixels.
|
||||
#[test]
|
||||
fn a_banded_flatten_of_a_palette_image_equals_flattened_checked() {
|
||||
use super::place_steps::Flatten;
|
||||
let pal = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [9, 9, 9]];
|
||||
let idx: Vec<u8> = (0..300 * 600).map(|i| ((i / 7 + i / 300) % 4) as u8).collect();
|
||||
let png = photocraft_codecs::encode_png_indexed(300, 600, &idx, &pal, Some(3), None, None).unwrap();
|
||||
let doc = photocraft_io::import("p.png", &png).unwrap().document;
|
||||
assert!(doc.color_table.is_some());
|
||||
let fmt = doc.pixel_format();
|
||||
let expected = flattened_checked(&doc, fmt, "file.placeEmbedded").unwrap();
|
||||
let mut flatten = Flatten::new(doc, true, fmt, "file.placeEmbedded").unwrap();
|
||||
let got = loop {
|
||||
if let Some(px) = flatten.advance().unwrap() {
|
||||
break px;
|
||||
}
|
||||
};
|
||||
assert!(got == expected);
|
||||
}
|
||||
|
||||
/// A canvas too large to flatten is refused before any band is rendered.
|
||||
#[test]
|
||||
fn a_banded_flatten_keeps_the_size_limit() {
|
||||
use super::place_steps::Flatten;
|
||||
let doc = Document::new("huge", photocraft_geom::Size::new(40_000, 40_000), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);
|
||||
let fmt = doc.pixel_format();
|
||||
assert!(Flatten::new(doc, true, fmt, "file.placeEmbedded").is_err());
|
||||
}
|
||||
|
||||
/// The size refusal names the command that was run, embedded or linked, not a made-up id.
|
||||
#[test]
|
||||
fn the_flatten_size_error_names_the_place_command() {
|
||||
use super::place_steps::Flatten;
|
||||
let huge = || Document::new("huge", photocraft_geom::Size::new(40_000, 40_000), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);
|
||||
let fmt = huge().pixel_format();
|
||||
for command in ["file.placeEmbedded", "file.placeLinked"] {
|
||||
match Flatten::new(huge(), true, fmt, command) {
|
||||
Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, command),
|
||||
other => panic!("{:?}", other.map(|_| ())),
|
||||
}
|
||||
}
|
||||
// Through a whole place: a linked one reports file.placeLinked.
|
||||
let bytes = photocraft_format::save_to_bytes(&huge(), &Default::default()).unwrap();
|
||||
let mut s = session(100, 100, 8);
|
||||
s.set_cooperative_jobs(true);
|
||||
s.set_job_step_budget(Duration::ZERO);
|
||||
let id = job(s.start_place_bytes("huge.pcraft", bytes, Some("huge.pcraft".into()), json!({})).unwrap());
|
||||
let (e, _) = poll_to_end(&mut s, id);
|
||||
let JobOutcome::Failed(err) = &e.outcome else { panic!("{e:?}") };
|
||||
assert!(err.contains("file.placeLinked"), "{err}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Place in resumable steps (#10031): decode, flatten, resize and translate, each in pieces small
|
||||
//! enough to run between two frames where there are no worker threads (the web build).
|
||||
//!
|
||||
//! Every piece computes what the one-shot code computes, so the placed layer is the same whether
|
||||
//! a worker thread, a [`PlaceSteps`] driven to the end, or a frame-by-frame [`Session::poll_jobs`]
|
||||
//! did the work. `fine` (a cooperative session) cuts the work into pieces; without it each stage
|
||||
//! is one unit and native code keeps its parallel resize and flatten.
|
||||
|
||||
use photocraft_algo::resample::ResizeSteps;
|
||||
use photocraft_geom::{Rect, TILE_SIZE};
|
||||
use photocraft_io::PngImport;
|
||||
use photocraft_raster::{Surface, TranslateSteps};
|
||||
use web_time::Instant;
|
||||
|
||||
use super::open::{PLACE_EMBEDDED, PlaceFile, PlaceInput, Prepared};
|
||||
use super::paths::{file_name, read_file, stem};
|
||||
use super::{
|
||||
Affine, Arc, Document, EngineError, LayerContent, Resample, Result, SmartObject, SmartSource, Value, check_flattenable, f64_param, flattened_checked,
|
||||
resize_surface, translate_surface,
|
||||
};
|
||||
use crate::jobs::{JobCtx, StepWork};
|
||||
|
||||
/// Pixels a flatten band covers at most: four tiles of a tile row (about 5 ms on one core).
|
||||
const BAND_PIXELS: i64 = 4 * (TILE_SIZE as i64) * (TILE_SIZE as i64);
|
||||
|
||||
/// A place as a [`StepWork`]; its result is what [`super::open::apply_place`] inserts.
|
||||
pub(crate) struct PlaceSteps {
|
||||
input: PlaceInput,
|
||||
/// The file's contents, once read (a path is read by the first step).
|
||||
bytes: Arc<Vec<u8>>,
|
||||
/// Cut the work into small pieces (for a session without threads).
|
||||
fine: bool,
|
||||
stage: Stage,
|
||||
/// Where the placed image lands, known once it is decoded.
|
||||
plan: Plan,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Plan {
|
||||
w: f64,
|
||||
h: f64,
|
||||
scale: f64,
|
||||
dx: f64,
|
||||
dy: f64,
|
||||
}
|
||||
|
||||
enum Stage {
|
||||
/// Nothing done yet.
|
||||
Decode,
|
||||
/// A plain PNG, a few rows at a time.
|
||||
DecodePng(Box<PngImport>),
|
||||
Flatten(Box<Flatten>),
|
||||
Resize(Box<ResizeSteps>),
|
||||
/// The fitted pixels being moved to where they land, a few tiles at a time.
|
||||
Translate(Box<TranslateSteps>),
|
||||
/// The pixels in place (none for a frame's image, which renders from its source), to wrap in
|
||||
/// a layer.
|
||||
Finish(Option<Surface>),
|
||||
Spent,
|
||||
}
|
||||
|
||||
impl PlaceSteps {
|
||||
/// `fine` cuts the work into pieces of a few milliseconds, as a session without worker
|
||||
/// threads needs; without it each stage is one unit of work.
|
||||
pub(crate) fn new(input: PlaceInput, fine: bool) -> Self {
|
||||
Self { input, bytes: Arc::new(Vec::new()), fine, stage: Stage::Decode, plan: Plan::default() }
|
||||
}
|
||||
|
||||
/// An import error as the engine reports it: a cancel stays one and a refused memory budget
|
||||
/// keeps its typed fields.
|
||||
fn io_error(&self, e: photocraft_io::IoError) -> EngineError {
|
||||
match e {
|
||||
photocraft_io::IoError::Cancelled => EngineError::Cancelled,
|
||||
// Typed, as the one-shot place reports it: a refused memory budget keeps its fields.
|
||||
e => crate::error::io_open_error(&self.input.name, e),
|
||||
}
|
||||
}
|
||||
|
||||
/// One unit of work; `Some` when the place is prepared.
|
||||
fn advance(&mut self, ctx: &JobCtx, deadline: Instant) -> Result<Option<Prepared>> {
|
||||
match std::mem::replace(&mut self.stage, Stage::Spent) {
|
||||
Stage::Decode => {
|
||||
self.read(ctx)?;
|
||||
let input = &self.input;
|
||||
let bytes = &self.bytes;
|
||||
let png = if self.fine { PngImport::new(&input.name, bytes).map_err(|e| self.io_error(e))? } else { None };
|
||||
match png {
|
||||
Some(png) => self.stage = Stage::DecodePng(Box::new(png)),
|
||||
None => {
|
||||
let imported = ctx
|
||||
.stage(0.0, 0.6, "Decoding", |ctl| photocraft_io::import_with_options_and_interrupt(&input.name, bytes, &input.opts, ctl))
|
||||
.map_err(|e| self.io_error(e))?;
|
||||
self.decoded(imported, false, ctx)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Stage::DecodePng(mut png) => {
|
||||
ctx.progress(0.55 * png.progress(), "Decoding");
|
||||
match png.step(&mut || Instant::now() < deadline).map_err(|e| self.io_error(e))? {
|
||||
Some(imported) => self.decoded(imported, true, ctx)?,
|
||||
None => self.stage = Stage::DecodePng(png),
|
||||
}
|
||||
}
|
||||
Stage::Flatten(mut flatten) => {
|
||||
ctx.progress(0.6 + 0.1 * flatten.progress(), "Flattening");
|
||||
match flatten.advance()? {
|
||||
Some(px) => self.flattened(px, ctx),
|
||||
None => self.stage = Stage::Flatten(flatten),
|
||||
}
|
||||
}
|
||||
Stage::Resize(mut resize) => {
|
||||
ctx.progress(0.7 + 0.2 * resize.progress(), "Resizing");
|
||||
match resize.step(&mut || Instant::now() < deadline) {
|
||||
Some(px) => self.fitted(px),
|
||||
None => self.stage = Stage::Resize(resize),
|
||||
}
|
||||
}
|
||||
Stage::Translate(mut shift) => {
|
||||
ctx.progress(0.9 + 0.05 * shift.progress(), "Placing");
|
||||
self.stage = match shift.step(&mut || Instant::now() < deadline) {
|
||||
Some(px) => Stage::Finish(Some(px)),
|
||||
None => Stage::Translate(shift),
|
||||
};
|
||||
}
|
||||
Stage::Finish(px) => return self.finish(px, ctx).map(Some),
|
||||
Stage::Spent => return Err(EngineError::Other("internal error: the place was already prepared".into())),
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Gets the file's bytes (reading a path) and refuses a place that cannot fit in memory,
|
||||
/// before anything is decoded.
|
||||
fn read(&mut self, ctx: &JobCtx) -> Result<()> {
|
||||
self.bytes = match &self.input.file {
|
||||
PlaceFile::Bytes(bytes) => Arc::clone(bytes),
|
||||
PlaceFile::Path(path) => {
|
||||
ctx.progress(0.0, "Reading");
|
||||
let bytes = read_file(path)?;
|
||||
ctx.check()?;
|
||||
Arc::new(bytes)
|
||||
}
|
||||
};
|
||||
let (name, fmt) = (&self.input.name, self.input.fmt);
|
||||
crate::memory_gate::ensure(&format!("place \u{201c}{}\u{201d}", file_name(name)), crate::memory_gate::place_need(&self.bytes, fmt.bytes_per_pixel()))?;
|
||||
// A path isn't read when the input is made, so whether it is a vector source is decided now.
|
||||
let vector = self.input.frame.is_some() || photocraft_io::is_svg_input(name, &self.bytes);
|
||||
self.input.doc = self.input.doc.take().filter(|_| vector);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The file is decoded: where it lands, then on to flattening. `banded`: the document is a
|
||||
/// plain image, which flattens band by band.
|
||||
fn decoded(&mut self, imported: photocraft_io::ImportResult, banded: bool, ctx: &JobCtx) -> Result<()> {
|
||||
if imported.preview_only {
|
||||
return Err(EngineError::Other(format!(
|
||||
"{}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here",
|
||||
self.input.name
|
||||
)));
|
||||
}
|
||||
let src = imported.document;
|
||||
let (w, h) = (src.size.width as f64, src.size.height as f64);
|
||||
let (cw, ch) = self.input.canvas;
|
||||
let p = &self.input.params;
|
||||
let scale = match f64_param(p, "scale") {
|
||||
Some(k) => (k / 100.0).max(1e-4),
|
||||
None if self.input.frame.is_some() && self.input.fit => (cw / w).max(ch / h),
|
||||
None if self.input.fit && (w > cw || h > ch) => (cw / w).min(ch / h),
|
||||
None => 1.0,
|
||||
};
|
||||
let center = match p.get("center").and_then(Value::as_array) {
|
||||
Some(c) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)),
|
||||
_ => (cw / 2.0, ch / 2.0),
|
||||
};
|
||||
let (dx, dy) = ((center.0 - w * scale / 2.0).round(), (center.1 - h * scale / 2.0).round());
|
||||
self.plan = Plan { w, h, scale, dx, dy };
|
||||
// A frame's image renders through its smart object, which refuses a placement past the
|
||||
// memory budget; resampling it to the frame's size first would allocate that surface twice.
|
||||
if self.input.frame.is_some() {
|
||||
self.stage = Stage::Finish(None);
|
||||
return Ok(());
|
||||
}
|
||||
ctx.progress(0.6, "Flattening");
|
||||
self.stage = Stage::Flatten(Box::new(Flatten::new(src, banded && self.fine, self.input.fmt, self.input.command())?));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The image is flattened: on to resizing it to fit, if it needs that.
|
||||
fn flattened(&mut self, px: Surface, ctx: &JobCtx) {
|
||||
let scale = self.plan.scale;
|
||||
if (scale - 1.0).abs() <= 1e-9 {
|
||||
self.fitted(px);
|
||||
} else if self.fine {
|
||||
self.stage = Stage::Resize(Box::new(ResizeSteps::new(px, scale, scale, Resample::Bicubic, None)));
|
||||
} else {
|
||||
ctx.progress(0.7, "Resizing");
|
||||
self.fitted(resize_surface(&px, scale, scale, Resample::Bicubic));
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels are fitted: on to moving them to where they land. A cooperative session does
|
||||
/// that a few target tiles at a time (an offset off the tile grid rebuilds nearly every tile
|
||||
/// the image touches); otherwise it is one [`translate_surface`].
|
||||
fn fitted(&mut self, px: Surface) {
|
||||
let (dx, dy) = (self.plan.dx as i32, self.plan.dy as i32);
|
||||
self.stage = if self.fine {
|
||||
let content = px.content_bounds();
|
||||
Stage::Translate(Box::new(TranslateSteps::new(px, dx, dy, content)))
|
||||
} else {
|
||||
Stage::Finish(Some(translate_surface(&px, dx, dy)))
|
||||
};
|
||||
}
|
||||
|
||||
/// Wraps the pixels, already in place, in the layer's content.
|
||||
fn finish(&mut self, px: Option<Surface>, ctx: &JobCtx) -> Result<Prepared> {
|
||||
let Plan { w, h, scale, dx, dy } = self.plan;
|
||||
let input = &self.input;
|
||||
let (cw, ch) = input.canvas;
|
||||
let placement = input.frame.as_ref().map_or(Affine { m: [scale, 0.0, 0.0, scale, dx, dy] }, |(_, f)| {
|
||||
f.transform.mul(&Affine { m: [scale / cw, 0.0, 0.0, scale / ch, dx / cw, dy / ch] })
|
||||
});
|
||||
let corners = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)].map(|(x, y)| placement.apply(photocraft_geom::Point::new(x, y)));
|
||||
let bounds = [
|
||||
corners.iter().map(|q| q.x).fold(f64::INFINITY, f64::min),
|
||||
corners.iter().map(|q| q.y).fold(f64::INFINITY, f64::min),
|
||||
corners.iter().map(|q| q.x).fold(f64::NEG_INFINITY, f64::max),
|
||||
corners.iter().map(|q| q.y).fold(f64::NEG_INFINITY, f64::max),
|
||||
];
|
||||
let label = if input.linked.is_some() { "Place Linked" } else { PLACE_EMBEDDED };
|
||||
// A frame's image is always a smart object.
|
||||
let smart = input.smart || input.frame.is_some();
|
||||
let content = if smart {
|
||||
let source = match &input.linked {
|
||||
Some(path) => SmartSource::Linked { path: path.clone() },
|
||||
None => SmartSource::Embedded { file_name: file_name(&input.name), bytes: Arc::clone(&self.bytes) },
|
||||
};
|
||||
let mut so = SmartObject::new(source, placement, px);
|
||||
// A vector source (SVG) or a frame's image renders at its placement scale instead of
|
||||
// as a resampled raster.
|
||||
if let Some(doc) = &input.doc {
|
||||
ctx.progress(0.9, "Rendering");
|
||||
ctx.check()?;
|
||||
if let Some(sharp) = crate::smart_cmds::render(doc, &so)? {
|
||||
so.cache = Some(sharp);
|
||||
}
|
||||
}
|
||||
if so.cache.is_none() {
|
||||
return Err(EngineError::Other(format!("{}: the placed image could not be rendered", input.name)));
|
||||
}
|
||||
LayerContent::Smart(so)
|
||||
} else {
|
||||
let px = px.ok_or_else(|| EngineError::Other(format!("{}: a frame's image must be a smart object", input.name)))?;
|
||||
LayerContent::Raster(px)
|
||||
};
|
||||
Ok(Prepared { content, layer_name: stem(&input.name), label, scale, bounds, smart, frame: input.frame.as_ref().map(|(id, _)| *id) })
|
||||
}
|
||||
}
|
||||
|
||||
impl StepWork<Prepared> for PlaceSteps {
|
||||
/// Runs units of work until `deadline` (at least one), checking for a cancel between them.
|
||||
fn step(&mut self, ctx: &JobCtx, deadline: Instant) -> Result<Option<Prepared>> {
|
||||
loop {
|
||||
ctx.check()?;
|
||||
if let Some(prepared) = self.advance(ctx, deadline)? {
|
||||
return Ok(Some(prepared));
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The decoded document being flattened to the surface it is resized from.
|
||||
pub(super) struct Flatten {
|
||||
doc: Document,
|
||||
fmt: photocraft_color::PixelFormat,
|
||||
/// The place command, for the size error.
|
||||
command: &'static str,
|
||||
/// Flatten band by band; otherwise in one go.
|
||||
banded: bool,
|
||||
bounds: Rect,
|
||||
/// The next band's top left corner.
|
||||
at: (i32, i32),
|
||||
/// Width of a band, a whole number of tiles.
|
||||
cols: i32,
|
||||
out: Option<Surface>,
|
||||
}
|
||||
|
||||
impl Flatten {
|
||||
/// `command` is the place command (`file.placeEmbedded` or `file.placeLinked`), named in the
|
||||
/// error a canvas past the compositor's limit gives.
|
||||
pub(super) fn new(doc: Document, banded: bool, fmt: photocraft_color::PixelFormat, command: &'static str) -> Result<Self> {
|
||||
check_flattenable(&doc, command)?;
|
||||
let bounds = doc.bounds();
|
||||
// Bands hold whole tiles, so each tile is written by one band and can move as it is. A
|
||||
// document that does not start on the tile grid (none does) flattens in one go.
|
||||
let banded = banded && bounds.x0.rem_euclid(TILE_SIZE) == 0 && bounds.y0.rem_euclid(TILE_SIZE) == 0;
|
||||
let cols = i32::try_from(BAND_PIXELS / i64::from(TILE_SIZE) / i64::from(TILE_SIZE)).unwrap_or(1).max(1) * TILE_SIZE;
|
||||
Ok(Self { doc, fmt, command, banded, bounds, at: (bounds.x0, bounds.y0), cols, out: None })
|
||||
}
|
||||
|
||||
/// How much of the flatten is done, `0.0..=1.0`.
|
||||
fn progress(&self) -> f32 {
|
||||
let rows = i64::from(self.bounds.height()).max(1);
|
||||
(i64::from(self.at.1.saturating_sub(self.bounds.y0)) as f32 / rows as f32).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Flattens the next band (the whole document if not banded); `Some` with the surface once
|
||||
/// the last one is in.
|
||||
pub(super) fn advance(&mut self) -> Result<Option<Surface>> {
|
||||
if !self.banded {
|
||||
return flattened_checked(&self.doc, self.fmt, self.command).map(Some);
|
||||
}
|
||||
let (x, y) = self.at;
|
||||
// A band is part of one tile row, at most `cols` wide.
|
||||
let y1 = (y.div_euclid(TILE_SIZE).saturating_add(1).saturating_mul(TILE_SIZE)).min(self.bounds.y1);
|
||||
let x1 = x.saturating_add(self.cols).min(self.bounds.x1);
|
||||
let band = photocraft_compose::composite_to_surface(&self.doc, Rect::new(x, y, x1, y1), self.fmt, None);
|
||||
// The band's tiles move into the result as they are, with no copy of their pixels.
|
||||
let out = self.out.get_or_insert_with(|| Surface::with_default(self.fmt, &band.default_pixel()));
|
||||
out.put_tiles(band.tiles().map(|(c, t)| (*c, Arc::clone(t))));
|
||||
self.at = if x1 >= self.bounds.x1 { (self.bounds.x0, y1) } else { (x1, y) };
|
||||
Ok(if self.at.1 >= self.bounds.y1 { Some(self.out.take().unwrap_or_else(|| Surface::new(self.fmt))) } else { None })
|
||||
}
|
||||
}
|
||||
@@ -3323,10 +3323,26 @@ fn reveal_in_finder_on_windows_passes_the_clicked_tabs_saved_path() {
|
||||
s.execute("file.new", json!({"width": 8, "height": 8, "name": "other"})).unwrap();
|
||||
|
||||
let r = s.execute("file.revealInFinder", json!({"document": 0, "dryRun": true})).unwrap();
|
||||
assert_eq!(r["program"], "explorer");
|
||||
// The Windows Explorer by full path: a bare name would first find an explorer.exe in the app's folder.
|
||||
let explorer = crate::layer_menu_cmds::windows_root(std::env::var_os("SystemRoot")).join("explorer.exe");
|
||||
assert_eq!(r["program"], json!(explorer.to_string_lossy()));
|
||||
assert_eq!(r["args"], json!(["/select,", r"C:\项目 图片\海报 🖼.png"]));
|
||||
}
|
||||
|
||||
/// Windows tools run from the Windows folder `SystemRoot` names, and from `C:\Windows` when it is
|
||||
/// unset or relative (which would resolve against the working directory).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_windows_folder_falls_back_when_system_root_is_unset_or_relative() {
|
||||
use crate::layer_menu_cmds::windows_root;
|
||||
use std::path::PathBuf;
|
||||
assert_eq!(windows_root(Some(r"D:\WinNT".into())), PathBuf::from(r"D:\WinNT"));
|
||||
assert_eq!(windows_root(None), PathBuf::from(r"C:\Windows"));
|
||||
assert_eq!(windows_root(Some(r"Windows".into())), PathBuf::from(r"C:\Windows"));
|
||||
assert_eq!(windows_root(Some(r"\Windows".into())), PathBuf::from(r"C:\Windows"));
|
||||
assert_eq!(windows_root(Some("".into())), PathBuf::from(r"C:\Windows"));
|
||||
}
|
||||
|
||||
/// "Include All Subfolders" (AUTO-219-5, #3753): Batch and Image Processor take the images in
|
||||
/// subfolders too, each result keeping its subfolder under the output folder (so same-named files
|
||||
/// don't collide), and skip the output folder when it sits inside the input folder.
|
||||
@@ -4075,7 +4091,7 @@ fn approve_memory_releases_the_preflight_when_the_hard_limit_refuses_it() {
|
||||
photocraft_io::memory::with_mock_memory(snap_low, || {
|
||||
let err = s.execute("file.approveMemory", json!({"id": id, "approve": true, "background": false})).unwrap_err();
|
||||
match &err {
|
||||
EngineError::PsdHardBudget { name, required, limit } => {
|
||||
EngineError::PsdHardBudget { name, required, limit, .. } => {
|
||||
assert_eq!(name, "ram_drop.psd");
|
||||
assert_eq!((*required, *limit), (8 * gb, expected_limit));
|
||||
}
|
||||
@@ -4104,7 +4120,7 @@ fn open_as_and_place_keep_the_typed_hard_budget_fields() {
|
||||
let mut s = Session::new();
|
||||
let err = s.execute("file.openAs", json!({"path": path.clone(), "approveHighMemory": true})).unwrap_err();
|
||||
match &err {
|
||||
EngineError::PsdHardBudget { name, required, limit } => {
|
||||
EngineError::PsdHardBudget { name, required, limit, .. } => {
|
||||
assert_eq!(name, &path);
|
||||
assert!(*required > hard && *limit == hard);
|
||||
}
|
||||
|
||||
@@ -1092,8 +1092,14 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"bottomRight" => buf.px.last().copied(),
|
||||
_ => None,
|
||||
};
|
||||
// Transparency is judged on the image as stored at its depth: alpha under half a step rounds to 0.
|
||||
let half_step = match d.doc.depth {
|
||||
SampleType::U8 => Some(0.5 / 255.0),
|
||||
SampleType::U16 => Some(0.5 / 65535.0),
|
||||
SampleType::F32 => None,
|
||||
};
|
||||
let differs = |q: [f32; 4]| match reference {
|
||||
None => q[3] > 0.0,
|
||||
None => half_step.map_or(q[3] > 0.0, |h| q[3] >= h),
|
||||
Some(r) => (0..4).any(|c| (q[c] * q[3] - r[c] * r[3]).abs() > 0.5 / 255.0 || (c == 3 && (q[3] - r[3]).abs() > 0.5 / 255.0)),
|
||||
};
|
||||
let mut b = Rect::EMPTY;
|
||||
|
||||
@@ -988,6 +988,28 @@ fn trim_based_on_top_left_colour() {
|
||||
assert_eq!(doc(&s).size, Size::new(10, 10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_transparent_drops_alpha_that_rounds_to_zero_at_the_depth() {
|
||||
// A faint pixel at (0, 0) on a 40 % layer: alpha 1 step × 0.4 rounds to 0 at 8 and 16 bits
|
||||
// (the stored image is transparent there), so Trim keeps only the opaque square. A 1/255
|
||||
// pixel is 0.4 × 257 ≈ 103 steps at 16 bits and any alpha is content at 32 bits: kept.
|
||||
for (depth, faint, keeps) in [(8, 1.0 / 255.0, false), (16, 1.0 / 65535.0, false), (16, 1.0 / 255.0, true), (32, 1.0 / 65535.0, true)] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth, "background": "transparent"})).unwrap();
|
||||
s.edit("paint", |doc, _| {
|
||||
let surf = doc.layers[0].surface_mut().unwrap();
|
||||
surf.fill_rect(Rect::new(40, 40, 50, 50), &[1.0, 0.0, 0.0, 1.0]);
|
||||
surf.fill_rect(Rect::new(0, 0, 1, 1), &[1.0, 0.0, 0.0, faint]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("layer.setProps", json!({"layer": doc(&s).layers[0].id.0, "opacity": 0.4})).unwrap();
|
||||
let r = s.execute("image.trim", json!({"basedOn": "transparent"})).unwrap();
|
||||
let want = if keeps { json!({"x": 0, "y": 0, "width": 50, "height": 50}) } else { json!({"x": 40, "y": 40, "width": 10, "height": 10}) };
|
||||
assert_eq!(r, want, "{depth}-bit, faint alpha {faint}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thirty_two_bit_holds_linear_light() {
|
||||
// Photoshop 27.11: an 8-bit sRGB grey 128 becomes 0.2159 in 32 bits (and 32 → 0.0144),
|
||||
|
||||
@@ -8,10 +8,11 @@
|
||||
//! document. Pixels are converted to the destination's colour profile (Color Settings' intent and
|
||||
//! black point compensation) and bit depth, as Photoshop converts dragged layers.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
|
||||
use photocraft_color::ColorMode;
|
||||
use photocraft_doc::{Document, Layer, LayerContent, LayerId, SmartContentsId};
|
||||
use photocraft_doc::text_styles::{CharacterStyleDef, ParagraphStyleDef};
|
||||
use photocraft_doc::{Document, Layer, LayerContent, LayerId, SmartContentsId, TextStyles};
|
||||
use photocraft_geom::Rect;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -122,11 +123,76 @@ pub(crate) fn adapt_copies(s: &Session, copies: &mut Document, dest: &Document)
|
||||
// application (24 pt at 72 ppi becomes 5.76 pt at 300 ppi, with no transform). Left at the
|
||||
// source's, a copy re-laid out at the destination's resolution on its next edit (#9560).
|
||||
crate::canvas_geom::retarget_type_resolution(copies, dest.resolution_dpi);
|
||||
adopt_text_styles(copies, &dest.text_styles)?;
|
||||
let new_canvas = copies.bounds() != dest.bounds();
|
||||
prepare_shapes(&mut copies.layers, dest, new_canvas);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Points the copies' type at `dest`'s character and paragraph styles, as the reference
|
||||
/// application does: a style is matched by name and the destination's definition wins (a copy
|
||||
/// whose rewritten size differs from it shows a local override), and a style `dest` lacks comes
|
||||
/// along (already scaled by [`crate::canvas_geom::retarget_type_resolution`]) under a fresh id.
|
||||
/// Afterwards `copies.text_styles` holds just the styles to add; [`land_text_styles`] adds them.
|
||||
fn adopt_text_styles(copies: &mut Document, dest: &TextStyles) -> Result<()> {
|
||||
let src = std::mem::take(&mut copies.text_styles);
|
||||
let mut used = (BTreeSet::new(), BTreeSet::new());
|
||||
crate::image_cmds::for_each_layer(&mut copies.layers, &mut |l| {
|
||||
if let LayerContent::Text(t) = &l.content {
|
||||
used.0.extend(t.runs.iter().filter_map(|r| r.style.style_sheet));
|
||||
used.1.extend(t.paragraphs.iter().filter_map(|p| p.style.style_sheet));
|
||||
}
|
||||
});
|
||||
let full = || EngineError::Other("no free text style id".into());
|
||||
let (mut chars, mut paras) = (HashMap::new(), HashMap::new());
|
||||
let mut next = dest.next_char_id();
|
||||
for id in used.0 {
|
||||
let Some(def) = src.char_style(id) else { continue };
|
||||
let to = match dest.character.iter().find(|d| d.name == def.name) {
|
||||
Some(d) => d.id,
|
||||
None => {
|
||||
let fresh = next.ok_or_else(full)?;
|
||||
next = fresh.checked_add(1);
|
||||
copies.text_styles.character.push(CharacterStyleDef { id: fresh, ..def.clone() });
|
||||
fresh
|
||||
}
|
||||
};
|
||||
chars.insert(id, to);
|
||||
}
|
||||
let mut next = dest.next_para_id();
|
||||
for id in used.1 {
|
||||
// Basic Paragraph (id 0) is implicit; every document has its own.
|
||||
let Some(def) = src.para_style(id).filter(|_| id != 0) else { continue };
|
||||
let to = match dest.paragraph.iter().find(|d| d.name == def.name) {
|
||||
Some(d) => d.id,
|
||||
None => {
|
||||
let fresh = next.ok_or_else(full)?;
|
||||
next = fresh.checked_add(1);
|
||||
copies.text_styles.paragraph.push(ParagraphStyleDef { id: fresh, ..def.clone() });
|
||||
fresh
|
||||
}
|
||||
};
|
||||
paras.insert(id, to);
|
||||
}
|
||||
crate::image_cmds::for_each_layer(&mut copies.layers, &mut |l| {
|
||||
if let LayerContent::Text(t) = &mut l.content {
|
||||
for r in &mut t.runs {
|
||||
r.style.style_sheet = r.style.style_sheet.and_then(|id| chars.get(&id).copied());
|
||||
}
|
||||
for p in &mut t.paragraphs {
|
||||
p.style.style_sheet = p.style.style_sheet.and_then(|id| paras.get(&id).copied());
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds the styles [`adopt_text_styles`] left in `styles` to `doc`.
|
||||
pub(crate) fn land_text_styles(doc: &mut Document, styles: TextStyles) {
|
||||
doc.text_styles.character.extend(styles.character);
|
||||
doc.text_styles.paragraph.extend(styles.paragraph);
|
||||
}
|
||||
|
||||
/// Moves every layer of `copies` by whole pixels (content, masks, vectors and smart placement).
|
||||
pub(crate) fn translate_copies(copies: &mut Document, destination: &Document, dx: i32, dy: i32) {
|
||||
if dx != 0 || dy != 0 {
|
||||
@@ -181,6 +247,7 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
copies.icc_profile = sdoc.icc_profile.clone();
|
||||
// Type re-lays out at the source's resolution, so it keeps its size in pixels.
|
||||
copies.resolution_dpi = sdoc.resolution_dpi;
|
||||
copies.text_styles.clone_from(&sdoc.text_styles);
|
||||
for id in &ids {
|
||||
let src_layer = sdoc.layer(*id).ok_or(EngineError::NoLayer(*id))?;
|
||||
let mut l = src_layer.duplicate();
|
||||
@@ -219,10 +286,12 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (dx, dy) = (dx.round() as i32, dy.round() as i32);
|
||||
translate_copies(&mut copies, &ddoc, dx, dy);
|
||||
let patterns: Vec<_> = sdoc.patterns.iter().filter(|pat| !ddoc.patterns.iter().any(|d| d.id == pat.id)).cloned().collect();
|
||||
let styles = std::mem::take(&mut copies.text_styles);
|
||||
s.set_active(dest);
|
||||
let label = if ids.len() == 1 { "Duplicate Layer" } else { "Duplicate Layers" };
|
||||
let edited = s.edit(label, |doc, active| {
|
||||
doc.patterns.extend(patterns);
|
||||
land_text_styles(doc, styles);
|
||||
let mut above = *active;
|
||||
let mut new = Vec::with_capacity(copies.layers.len());
|
||||
// The first copy goes where a new layer would; the rest stack above it.
|
||||
@@ -279,6 +348,7 @@ pub(crate) fn duplicate_to_new_document(s: &mut Session, p: &Value) -> Result<Va
|
||||
nd.icc_profile.clone_from(&sdoc.icc_profile);
|
||||
nd.patterns.clone_from(&sdoc.patterns);
|
||||
nd.global_light = sdoc.global_light;
|
||||
nd.text_styles.clone_from(&sdoc.text_styles);
|
||||
// A name other than the copy's own was typed (#9023).
|
||||
let mut typed = None;
|
||||
for id in &ids {
|
||||
@@ -304,6 +374,10 @@ pub(crate) fn duplicate_to_new_document(s: &mut Session, p: &Value) -> Result<Va
|
||||
sm.contents_id = *contents.entry(sm.contents_id).or_insert_with(SmartContentsId::fresh);
|
||||
}
|
||||
}
|
||||
// The new document gets the styles its type uses.
|
||||
adopt_text_styles(&mut nd, &TextStyles::default())?;
|
||||
// Its own Basic Paragraph is the source's: type that inherits from it must not gain overrides.
|
||||
nd.text_styles.basic.clone_from(&sdoc.text_styles.basic);
|
||||
let new_ids: Vec<LayerId> = nd.layers.iter().map(|l| l.id).collect();
|
||||
let index = s.add_document(nd, None);
|
||||
if let (Some(name), [id]) = (typed, new_ids.as_slice()) {
|
||||
|
||||
@@ -500,3 +500,166 @@ fn retargeting_type_survives_bad_resolutions() {
|
||||
crate::canvas_geom::retarget_type_resolution(&mut d, f32::MAX);
|
||||
assert!(size(&d).is_finite() && size(&d) > 0.0, "{}", size(&d));
|
||||
}
|
||||
|
||||
/// Document 0 at 72 ppi with "Hello" in Paragraph Style 1 (24 pt) and "He" also in Character
|
||||
/// Style 1 (24 pt, underlined); document 1 at 300 ppi, its own styles made by `dest`.
|
||||
fn styled_type_docs(dest: impl FnOnce(&mut Session)) -> (Session, LayerId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 72})).unwrap();
|
||||
let t = s.execute("type.create", json!({"text": "Hello", "size": 12, "x": 100, "y": 100})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("type.paragraphStyle.new", json!({"attrs": {"size": 24}, "fromSelection": false, "apply": true, "layer": t})).unwrap();
|
||||
s.execute("type.characterStyle.new", json!({"attrs": {"size": 24, "underline": true}, "fromSelection": false, "apply": true, "layer": t, "range": [0, 2]}))
|
||||
.unwrap();
|
||||
s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 300})).unwrap();
|
||||
dest(&mut s);
|
||||
s.set_active(0);
|
||||
s.execute("layer.select", json!({"layer": t})).unwrap();
|
||||
(s, LayerId(t))
|
||||
}
|
||||
|
||||
/// The styles panel state of `range` in layer `id` of document 1.
|
||||
fn styles_of(s: &mut Session, id: LayerId, range: [usize; 2]) -> (Value, Value) {
|
||||
s.set_active(1);
|
||||
let c = s.execute("type.characterStyle.list", json!({"layer": id.0, "range": range})).unwrap();
|
||||
let p = s.execute("type.paragraphStyle.list", json!({"layer": id.0, "range": range})).unwrap();
|
||||
(c, p)
|
||||
}
|
||||
|
||||
/// #10500: type copied to a document of another resolution brings the styles it uses, as in
|
||||
/// the reference application (measured with Duplicate Layer from 72 to 300 ppi): a style the
|
||||
/// destination lacks arrives under its name, scaled like the text (24 pt → 5.76 pt), so the
|
||||
/// copy has no override; it never takes over an unrelated destination style with the same id.
|
||||
#[test]
|
||||
fn copied_type_brings_its_styles_scaled() {
|
||||
for paste in [false, true] {
|
||||
let (mut s, _) = styled_type_docs(|s| {
|
||||
s.execute("type.characterStyle.new", json!({"name": "Unrelated", "attrs": {"size": 50}, "fromSelection": false})).unwrap();
|
||||
s.execute("type.paragraphStyle.new", json!({"name": "Unrelated", "attrs": {"size": 50}, "fromSelection": false})).unwrap();
|
||||
});
|
||||
let id = if paste {
|
||||
s.execute("edit.copy", json!({})).unwrap();
|
||||
s.set_active(1);
|
||||
LayerId(s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap()["layer"].as_u64().unwrap())
|
||||
} else {
|
||||
copied(&s.execute("layer.copyToDocument", json!({"document": 1})).unwrap())
|
||||
};
|
||||
assert!(close(text(&s, 1, id).runs[0].style.size_pt, 5.76), "paste {paste}");
|
||||
let (c, p) = styles_of(&mut s, id, [0, 2]);
|
||||
let names = |v: &Value| v["styles"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap().to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(names(&c), ["None", "Unrelated", "Character Style 1"], "paste {paste}");
|
||||
assert_eq!(names(&p), ["Basic Paragraph", "Unrelated", "Paragraph Style 1"], "paste {paste}");
|
||||
let (cs, ps) = (&c["styles"][2], &p["styles"][2]);
|
||||
assert!(close(cs["attrs"]["size_pt"].as_f64().unwrap() as f32, 5.76), "{cs}");
|
||||
assert!(close(ps["characterAttrs"]["size_pt"].as_f64().unwrap() as f32, 5.76), "{ps}");
|
||||
assert_eq!((&c["current"]["character"], &c["current"]["characterOverride"]), (&cs["id"], &json!(false)), "paste {paste}");
|
||||
assert_eq!((&p["current"]["paragraph"], &p["current"]["paragraphOverride"]), (&ps["id"], &json!(false)), "paste {paste}");
|
||||
// The source keeps its 24 pt styles.
|
||||
assert_eq!(doc(&s, 0).text_styles.character[0].attrs["size_pt"], json!(24.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// A destination that already has a style of the same name keeps its definition (24 pt), and
|
||||
/// the copy, at 5.76 pt, shows a local override ("+"), as in the reference application.
|
||||
#[test]
|
||||
fn copied_type_uses_the_destinations_same_named_style() {
|
||||
let (mut s, _) = styled_type_docs(|s| {
|
||||
s.execute("type.characterStyle.new", json!({"name": "Filler", "fromSelection": false})).unwrap();
|
||||
s.execute("type.characterStyle.new", json!({"name": "Character Style 1", "attrs": {"size": 24, "underline": true}, "fromSelection": false})).unwrap();
|
||||
});
|
||||
let id = copied(&s.execute("layer.copyToDocument", json!({"document": 1})).unwrap());
|
||||
let (c, _) = styles_of(&mut s, id, [0, 2]);
|
||||
assert_eq!(c["styles"].as_array().unwrap().len(), 3, "no second Character Style 1: {c}");
|
||||
let existing = &c["styles"][2];
|
||||
assert_eq!(existing["attrs"]["size_pt"], json!(24.0));
|
||||
assert_eq!((&c["current"]["character"], &c["current"]["characterOverride"]), (&existing["id"], &json!(true)));
|
||||
assert!(close(text(&s, 1, id).runs[0].style.size_pt, 5.76));
|
||||
}
|
||||
|
||||
/// Duplicate Layer › New Document brings the styles the type uses (at the same size).
|
||||
#[test]
|
||||
fn type_duplicated_to_a_new_document_keeps_its_styles() {
|
||||
let (mut s, t) = styled_type_docs(|_| {});
|
||||
let r = s.execute("layer.duplicate", json!({"document": "new"})).unwrap();
|
||||
let (i, id) = (r["document"].as_u64().unwrap() as usize, LayerId(r["layer"].as_u64().unwrap()));
|
||||
s.set_active(i);
|
||||
let c = s.execute("type.characterStyle.list", json!({"layer": id.0, "range": [0, 2]})).unwrap();
|
||||
let p = s.execute("type.paragraphStyle.list", json!({"layer": id.0, "range": [0, 2]})).unwrap();
|
||||
assert_eq!(c["styles"][1]["name"], "Character Style 1");
|
||||
assert_eq!(c["styles"][1]["attrs"]["size_pt"], json!(24.0));
|
||||
assert_eq!((&c["current"]["character"], &c["current"]["characterOverride"]), (&c["styles"][1]["id"], &json!(false)));
|
||||
assert_eq!((&p["current"]["paragraph"], &p["current"]["paragraphOverride"]), (&p["styles"][1]["id"], &json!(false)));
|
||||
assert_eq!(text(&s, i, id).runs, text(&s, 0, t).runs);
|
||||
}
|
||||
|
||||
/// Document 0 (RGB, 72 ppi) with "Hello" whose "He" is in Character Style 1 (red); document 1
|
||||
/// (CMYK, 72 ppi). The type layer is selected in document 0.
|
||||
fn red_styled_type_docs() -> (Session, LayerId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 200, "height": 100, "resolution": 72})).unwrap();
|
||||
let t = s.execute("type.create", json!({"text": "Hello", "size": 12, "x": 20, "y": 50})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("type.characterStyle.new", json!({"attrs": {"color": "#ff0000"}, "fromSelection": false, "apply": true, "layer": t, "range": [0, 2]})).unwrap();
|
||||
s.execute("file.new", json!({"width": 200, "height": 100, "resolution": 72, "mode": "cmyk"})).unwrap();
|
||||
s.set_active(0);
|
||||
s.execute("layer.select", json!({"layer": t})).unwrap();
|
||||
(s, LayerId(t))
|
||||
}
|
||||
|
||||
/// The colour Character Style 1 of document `i` sets, and whether "He" of `id` overrides it.
|
||||
fn style_color(s: &mut Session, i: usize, id: LayerId) -> (photocraft_color::Color, bool) {
|
||||
s.set_active(i);
|
||||
let c = s.execute("type.characterStyle.list", json!({"layer": id.0, "range": [0, 2]})).unwrap();
|
||||
let style = c["styles"].as_array().unwrap().iter().find(|x| x["name"] == "Character Style 1").unwrap();
|
||||
(serde_json::from_value(style["attrs"]["color"].clone()).unwrap(), c["current"]["characterOverride"].as_bool().unwrap())
|
||||
}
|
||||
|
||||
/// Type copied to a document of another colour mode converts its run colours, and the style it
|
||||
/// brings converts with the same transform: the run matches its style (no override), so a later
|
||||
/// change to the style's colour still reaches it. Converting the document itself (Image › Mode,
|
||||
/// Convert to Profile with and without dither) keeps its styles in step the same way.
|
||||
#[test]
|
||||
fn copied_type_styles_convert_their_colours_with_the_type() {
|
||||
let (mut s, _) = red_styled_type_docs();
|
||||
let id = copied(&s.execute("layer.copyToDocument", json!({"document": 1})).unwrap());
|
||||
let run = text(&s, 1, id).runs[0].style.color;
|
||||
assert_eq!(run.mode, ColorMode::Cmyk, "the run converted");
|
||||
let (style, over) = style_color(&mut s, 1, id);
|
||||
assert_eq!(style, run, "the copied style converted with the run");
|
||||
assert!(!over, "no false override");
|
||||
for (cmd, p) in [
|
||||
("image.mode.cmyk", json!({})),
|
||||
("edit.convertToProfile", json!({"profile": "coated-cmyk", "dither": false})),
|
||||
("edit.convertToProfile", json!({"profile": "coated-cmyk", "dither": true})),
|
||||
("edit.convertToProfile", json!({"profile": "lab-d50"})),
|
||||
] {
|
||||
let (mut s, t) = red_styled_type_docs();
|
||||
s.execute(cmd, p.clone()).unwrap();
|
||||
let run = text(&s, 0, t).runs[0].style.color;
|
||||
assert_ne!(run.mode, ColorMode::Rgb, "{cmd} {p}: the run converted");
|
||||
let (style, over) = style_color(&mut s, 0, t);
|
||||
assert_eq!(style, run, "{cmd} {p}: the style converted with the run");
|
||||
assert!(!over, "{cmd} {p}: no false override");
|
||||
}
|
||||
}
|
||||
|
||||
/// Duplicate Layer › New Document keeps the source's Basic Paragraph: type that inherits its
|
||||
/// size from it has no override there, and Clear Override leaves it as it was.
|
||||
#[test]
|
||||
fn type_duplicated_to_a_new_document_keeps_the_sources_basic_paragraph() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
let t = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 12, "x": 20, "y": 50})).unwrap()["layer"].as_u64().unwrap());
|
||||
s.execute("type.paragraphStyle.set", json!({"id": 0, "attrs": {"size": 30}})).unwrap();
|
||||
assert!(close(text(&s, 0, t).runs[0].style.size_pt, 30.0), "the type inherits Basic Paragraph");
|
||||
let basic = doc(&s, 0).text_styles.basic.clone();
|
||||
s.execute("layer.select", json!({"layer": t.0})).unwrap();
|
||||
let r = s.execute("layer.duplicate", json!({"document": "new"})).unwrap();
|
||||
let (i, id) = (r["document"].as_u64().unwrap() as usize, LayerId(r["layer"].as_u64().unwrap()));
|
||||
assert_eq!(doc(&s, i).text_styles.basic, basic);
|
||||
s.set_active(i);
|
||||
let c = s.execute("type.characterStyle.list", json!({"layer": id.0})).unwrap();
|
||||
let p = s.execute("type.paragraphStyle.list", json!({"layer": id.0})).unwrap();
|
||||
assert_eq!((&c["current"]["characterOverride"], &p["current"]["paragraphOverride"]), (&json!(false), &json!(false)), "{c} {p}");
|
||||
s.execute("type.paragraphStyle.clearOverride", json!({"layer": id.0})).unwrap();
|
||||
s.execute("type.characterStyle.clearOverride", json!({"layer": id.0})).unwrap();
|
||||
assert!(close(text(&s, i, id).runs[0].style.size_pt, 30.0), "{}", text(&s, i, id).runs[0].style.size_pt);
|
||||
}
|
||||
|
||||
@@ -434,8 +434,8 @@ pub(crate) fn reveal(path: &str, dry_run: bool) -> Result<Value> {
|
||||
if dry_run {
|
||||
return Ok(json!({"program": program, "args": args}));
|
||||
}
|
||||
ensure_folder(program, &args)?;
|
||||
spawn(program, &args)?;
|
||||
ensure_folder(&program, &args)?;
|
||||
spawn(&program, &args)?;
|
||||
Ok(json!({"path": path}))
|
||||
}
|
||||
|
||||
@@ -453,8 +453,28 @@ fn ensure_folder(program: &str, args: &[String]) -> Result<()> {
|
||||
}
|
||||
|
||||
/// The file-manager invocation that selects `path` on this platform.
|
||||
pub fn reveal_command(path: &str) -> Result<(&'static str, Vec<String>)> {
|
||||
reveal_command_on(std::env::consts::OS, path)
|
||||
pub fn reveal_command(path: &str) -> Result<(String, Vec<String>)> {
|
||||
let (program, args) = reveal_command_on(std::env::consts::OS, path)?;
|
||||
Ok((system_program(program), args))
|
||||
}
|
||||
|
||||
/// Windows tools run by full path: by bare name, Windows first looks in the app's own folder, so
|
||||
/// an `explorer.exe` lying next to a portable PhotoCraft would start instead (#9666).
|
||||
#[cfg(windows)]
|
||||
fn system_program(program: &str) -> String {
|
||||
windows_root(std::env::var_os("SystemRoot")).join(format!("{program}.exe")).to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// The Windows folder for the `SystemRoot` value `system_root`: `C:\Windows` when it is unset or
|
||||
/// not an absolute path (a relative one would resolve against the working directory).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn windows_root(system_root: Option<std::ffi::OsString>) -> std::path::PathBuf {
|
||||
system_root.map(std::path::PathBuf::from).filter(|p| p.is_absolute()).unwrap_or_else(|| std::path::PathBuf::from(r"C:\Windows"))
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn system_program(program: &str) -> String {
|
||||
program.to_string()
|
||||
}
|
||||
|
||||
/// [`reveal_command`] on the platform `os` (a `std::env::consts::OS` value).
|
||||
|
||||
@@ -389,7 +389,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"layer.smartFilter.setParams",
|
||||
"Edit Smart Filter",
|
||||
&[],
|
||||
r##"{"layer":id?,"index":u32?,"params":{…} (merged)}"##,
|
||||
r##"{"layer":id?,"index":u32?,"params":{…} (merged),"replace":bool=false (params replace the stored ones instead)}"##,
|
||||
has_smart_filters,
|
||||
set_filter_params
|
||||
),
|
||||
|
||||
@@ -170,7 +170,9 @@ fn edited_shape_params(s: &Session, previous: &Value, patch: &Value) -> Result<V
|
||||
|
||||
pub(super) fn set_filter_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "layer.smartFilter.setParams";
|
||||
let new = p.get("params").cloned().ok_or_else(|| bad(CMD, "pass `params` (merged into the filter's parameters)"))?;
|
||||
let new = p.get("params").cloned().ok_or_else(|| bad(CMD, "pass `params` (merged into the filter's parameters, or replacing them with `replace`)"))?;
|
||||
// An editor holding all of a filter's settings replaces them, so a key it removed stops applying.
|
||||
let replace = p.get("replace").and_then(Value::as_bool).unwrap_or(false);
|
||||
let authorize = s.authorize;
|
||||
// A Displace given another open document as its map embeds that one in place of the old
|
||||
// (#7423). It is read here, before the edit, from the session; the request is authorized
|
||||
@@ -183,7 +185,9 @@ pub(super) fn set_filter_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
|
||||
let sm = smart(doc, layer_param(s, p)?)?;
|
||||
let f = sm.smart_filters.get(filter_index(CMD, p, sm)?).ok_or_else(|| bad(CMD, "no smart filter at this index"))?;
|
||||
let shape_params = if f.command == "filter.blur.shapeBlur" { Some(edited_shape_params(s, &f.params, &new)?) } else { None };
|
||||
let nothing = json!({});
|
||||
let previous = if replace { ¬hing } else { &f.params };
|
||||
let shape_params = if f.command == "filter.blur.shapeBlur" { Some(edited_shape_params(s, previous, &new)?) } else { None };
|
||||
(f.command == DISPLACE, shape_params)
|
||||
};
|
||||
let new_map = if displace && new_map_asked {
|
||||
@@ -209,6 +213,8 @@ pub(super) fn set_filter_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
if let Some(params) = shape_params {
|
||||
f.params = params;
|
||||
} else if replace {
|
||||
f.params = new;
|
||||
} else {
|
||||
match (&mut f.params, new) {
|
||||
(Value::Object(old), Value::Object(n)) => old.extend(n),
|
||||
|
||||
@@ -1397,3 +1397,40 @@ fn native_digest_cache_misses_after_copy_on_write_and_keeps_recently_used_source
|
||||
drop(newest);
|
||||
assert!(weak.upgrade().is_none());
|
||||
}
|
||||
|
||||
/// `replace` makes `params` the filter's whole settings, so a key the edit left out stops
|
||||
/// applying; without it the params merge, as partial edits rely on. Either way it is one undo.
|
||||
#[test]
|
||||
fn set_params_replace_drops_the_keys_it_leaves_out() {
|
||||
let mut s = session(8);
|
||||
paint(&mut s);
|
||||
convert(&mut s);
|
||||
s.execute("image.adjustments.channelMixer", json!({"monochrome": true, "gray": [30, 30, 40, 0]})).unwrap();
|
||||
let params = |s: &Session| active_smart(s).smart_filters[0].params.clone();
|
||||
|
||||
s.execute("layer.smartFilter.setParams", json!({"params": {"monochrome": false}})).unwrap();
|
||||
assert_eq!(params(&s), json!({"monochrome": false, "gray": [30, 30, 40, 0]}), "merged by default");
|
||||
|
||||
let edit = json!({"monochrome": false, "red": [70, 30, 0, 0]});
|
||||
s.execute("layer.smartFilter.setParams", json!({"params": edit, "replace": true})).unwrap();
|
||||
assert_eq!(params(&s), edit, "replaced");
|
||||
|
||||
s.undo();
|
||||
assert_eq!(params(&s), json!({"monochrome": false, "gray": [30, 30, 40, 0]}));
|
||||
}
|
||||
|
||||
/// `replace` also holds for Shape Blur, whose settings otherwise merge before its shape resolves.
|
||||
#[test]
|
||||
fn set_params_replace_drops_a_shape_blur_radius_it_leaves_out() {
|
||||
let mut s = session(8);
|
||||
paint(&mut s);
|
||||
convert(&mut s);
|
||||
s.execute("filter.blur.shapeBlur", json!({"radius": 5, "shape": "circle"})).unwrap();
|
||||
let params = |s: &Session| active_smart(s).smart_filters[0].params.clone();
|
||||
|
||||
s.execute("layer.smartFilter.setParams", json!({"params": {"shape": "circle"}})).unwrap();
|
||||
assert_eq!(params(&s)["radius"], json!(5), "merged by default");
|
||||
|
||||
s.execute("layer.smartFilter.setParams", json!({"params": {"shape": "circle"}, "replace": true})).unwrap();
|
||||
assert!(params(&s).get("radius").is_none(), "replaced: {}", params(&s));
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ pub(crate) use paths::{is_work, path_mut};
|
||||
pub(crate) use shape::{bake_path, map_path, map_shape, shift_shape, with_shape};
|
||||
use shape::{
|
||||
can_paste_shape_fill, can_paste_shape_stroke, combine_shapes, copy_shape_fill, copy_shape_stroke, has_shape_fill, has_shape_stroke, merge_components,
|
||||
paste_shape_fill, paste_shape_stroke, selection_to_shape, shape_create, shape_edit, shape_info, shape_rasterize,
|
||||
paste_shape_fill, paste_shape_stroke, path_to_shape, selection_to_shape, shape_create, shape_edit, shape_info, shape_rasterize,
|
||||
};
|
||||
pub use shape::{preview_shape_stroke, refresh_shape, shape_path, transform_shape, translate_vectors};
|
||||
use vector_mask::{toggle_vector_mask, vector_mask_add, vector_mask_delete, vector_mask_edit, vector_mask_info, vector_mask_rasterize, with};
|
||||
@@ -230,6 +230,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
run: |s, p| path_to_selection_with_mode(s, p, "subtract"),
|
||||
journal: true,
|
||||
},
|
||||
spec!(
|
||||
"path.toShape",
|
||||
"Make Shape from Path",
|
||||
[],
|
||||
leak(format!(
|
||||
r##"{{"name":str|"work"|"layer"="work" (the Work Path becomes the shape's path; a saved path stays) | "path":{{subpaths}} (inline; not with name),"consumeWorkPath":bool=false (with path: it was drawn into the Work Path, which goes),{fill}=foreground,{stroke}=none,"layerName":str?}} → shape.info"##
|
||||
)),
|
||||
has_doc,
|
||||
path_to_shape
|
||||
),
|
||||
spec!("select.toWorkPath", "Make Work Path", [], r##"{"tolerance":0.5..10 px=2} → {subpaths,knots}"##, has_selection, select_to_work_path),
|
||||
spec!(
|
||||
"path.fill",
|
||||
|
||||
@@ -432,16 +432,7 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let l = live_from_params(CMD, kind, p, None)?;
|
||||
(vector::shapes::live_path(&l), Some(l))
|
||||
};
|
||||
let fg = s.tools.foreground;
|
||||
let fgc = Color::rgba(fg[0], fg[1], fg[2], fg[3]);
|
||||
let fill = match p.get("fill") {
|
||||
Some(v) => parse_fill(v).map_err(|e| bad(CMD, e))?,
|
||||
None => Some(Fill::Solid(fgc)),
|
||||
};
|
||||
let stroke = match p.get("stroke") {
|
||||
Some(v) => parse_stroke(v, None, fgc).map_err(|e| bad(CMD, e))?,
|
||||
None => None,
|
||||
};
|
||||
let (fill, stroke) = new_fill_stroke(s, CMD, p)?;
|
||||
vector::flatten::validate_shape(&path, stroke.as_ref()).map_err(|e| bad(CMD, e))?;
|
||||
// Add to an existing shape layer with a path operation (Shape tool in combine/subtract… mode).
|
||||
if let Some(target) = p.get("addTo").and_then(Value::as_u64) {
|
||||
@@ -471,6 +462,72 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
shape_info(s, id)
|
||||
}
|
||||
|
||||
/// A new shape layer's `fill` (default the foreground colour) and `stroke` (default none).
|
||||
fn new_fill_stroke(s: &Session, cmd: &str, p: &Value) -> Result<(Option<Fill>, Option<photocraft_doc::ShapeStroke>)> {
|
||||
let fg = s.tools.foreground;
|
||||
let fgc = Color::rgba(fg[0], fg[1], fg[2], fg[3]);
|
||||
let fill = match p.get("fill") {
|
||||
Some(v) => parse_fill(v).map_err(|e| bad(cmd, e))?,
|
||||
None => Some(Fill::Solid(fgc)),
|
||||
};
|
||||
let stroke = match p.get("stroke") {
|
||||
Some(v) => parse_stroke(v, None, fgc).map_err(|e| bad(cmd, e))?,
|
||||
None => None,
|
||||
};
|
||||
Ok((fill, stroke))
|
||||
}
|
||||
|
||||
/// The Pen options bar's Make: Shape: a new shape layer, as one History step, from the work path
|
||||
/// or a saved path (`name`), or from an inline `path` (a Pen path still being drawn). The Work
|
||||
/// Path becomes the shape's path, so it is gone afterwards; a saved path stays. An inline `path`
|
||||
/// leaves the document's paths alone unless `consumeWorkPath` says it was drawn into the Work
|
||||
/// Path. Unlike the other path commands, `"work"` never falls back to the active layer's path:
|
||||
/// that would duplicate the selected shape or vector mask.
|
||||
pub(super) fn path_to_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "path.toShape";
|
||||
let name = match p.get("name") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(n)) => Some(n.as_str()),
|
||||
Some(_) => return Err(bad(CMD, "`name` must be a path name: \"work\", \"layer\" or a saved path's name")),
|
||||
};
|
||||
let consume_flag = match p.get("consumeWorkPath") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(_) => return Err(bad(CMD, "`consumeWorkPath` must be true or false")),
|
||||
};
|
||||
let (path, consume_work) = match p.get("path").filter(|v| !v.is_null()) {
|
||||
Some(_) if name.is_some() => return Err(bad(CMD, "give `name` or `path`, not both")),
|
||||
Some(v) => (parse_path(v).map_err(|e| bad(CMD, e))?, consume_flag),
|
||||
None if super::is_work(name) => {
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
(d.doc.work_path.clone().ok_or_else(|| bad(CMD, "there is no Work Path"))?, true)
|
||||
}
|
||||
None => (super::resolve_path(s, name)?, false),
|
||||
};
|
||||
if !path.subpaths.iter().any(|sp| sp.knots.len() >= 2) {
|
||||
return Err(bad(CMD, "the path has no segment to make a shape from"));
|
||||
}
|
||||
let (fill, stroke) = new_fill_stroke(s, CMD, p)?;
|
||||
vector::flatten::validate_shape(&path, stroke.as_ref()).map_err(|e| bad(CMD, e))?;
|
||||
let layer_name = match p.get("layerName") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(n)) if !n.trim().is_empty() => Some(n.clone()),
|
||||
Some(_) => return Err(bad(CMD, "`layerName` must be a name that isn't empty")),
|
||||
};
|
||||
let mut sh = ShapeLayer { path, fill, stroke, ..Default::default() };
|
||||
let id = s.edit("New Shape Layer", |doc, active| {
|
||||
refresh_shape(doc, &mut sh);
|
||||
let name = layer_name.unwrap_or_else(|| doc.next_layer_name(default_name("path")));
|
||||
let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Shape(sh)), crate::layer_place::Place::AutoEditable);
|
||||
if consume_work {
|
||||
doc.work_path = None;
|
||||
}
|
||||
*active = Some(id);
|
||||
Ok(id)
|
||||
})?;
|
||||
shape_info(s, id)
|
||||
}
|
||||
|
||||
pub(super) fn shape_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "shape.edit";
|
||||
let id = layer_id(s, p)?;
|
||||
|
||||
@@ -403,6 +403,114 @@ fn path_to_selection_matches_analytic_shape() {
|
||||
assert!(m[100 * 200 + 160] > 0.2 && m[100 * 200 + 160] < 0.8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_to_shape_makes_a_shape_layer_from_the_work_path_in_one_step() {
|
||||
let mut s = session(80, 80, 8);
|
||||
let square = json!({"subpaths": [{"knots": [[10, 10], [50, 10], [50, 50], [10, 50]]}]});
|
||||
s.execute("path.set", json!({"path": square})).unwrap();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let info = s.execute("path.toShape", json!({"fill": "#ff0000"})).unwrap();
|
||||
let id = LayerId(info["layer"].as_u64().unwrap());
|
||||
let d = doc(&s);
|
||||
let LayerContent::Shape(sh) = &d.layer(id).unwrap().content else { panic!("not a shape layer") };
|
||||
assert_eq!(sh.path.subpaths[0].knots.len(), 4);
|
||||
assert_eq!(sh.fill, Some(Fill::Solid(Color::rgba(1.0, 0.0, 0.0, 1.0))));
|
||||
// The Work Path became the shape's path.
|
||||
assert!(d.work_path.is_none());
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(id));
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history + 1);
|
||||
s.undo();
|
||||
assert!(doc(&s).layer(id).is_none());
|
||||
assert!(doc(&s).work_path.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_to_shape_keeps_a_saved_path() {
|
||||
let mut s = session(80, 80, 8);
|
||||
let tri = json!({"subpaths": [{"knots": [[10, 10], [50, 10], [30, 50]]}]});
|
||||
s.execute("path.set", json!({"name": "Tri", "path": tri})).unwrap();
|
||||
let info = s.execute("path.toShape", json!({"name": "Tri", "layerName": "Roof"})).unwrap();
|
||||
assert_eq!(info["name"], "Roof");
|
||||
assert_eq!(doc(&s).paths[0].name, "Tri");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_to_shape_rejects_bad_input_without_changing_history() {
|
||||
let mut s = session(80, 80, 8);
|
||||
assert!(s.execute("path.toShape", json!({})).is_err(), "no path");
|
||||
s.execute("path.set", json!({"path": {"subpaths": [{"knots": [[12, 12], [60, 12], [60, 60]]}]}})).unwrap();
|
||||
let before = doc(&s).clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
for p in [
|
||||
json!({"name": "missing"}),
|
||||
json!({"name": 42}),
|
||||
json!({"name": ["work"]}),
|
||||
json!({"fill": "not a colour"}),
|
||||
json!({"fill": 42}),
|
||||
json!({"stroke": {"width": -1}}),
|
||||
json!({"stroke": {"width": 1e100}}),
|
||||
json!({"stroke": true}),
|
||||
] {
|
||||
assert!(s.execute("path.toShape", p.clone()).is_err(), "accepted {p}");
|
||||
assert_eq!(*doc(&s), before, "{p} modified the document");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history, "{p} changed history");
|
||||
}
|
||||
}
|
||||
|
||||
/// With no Work Path, `path.toShape` doesn't take the active shape layer's path: that would only
|
||||
/// duplicate the shape.
|
||||
#[test]
|
||||
fn path_to_shape_without_a_work_path_does_not_copy_the_active_shape() {
|
||||
let mut s = session(80, 80, 8);
|
||||
s.execute("shape.create", json!({"rect": [10, 10, 30, 30]})).unwrap();
|
||||
let layers = doc(&s).layers.len();
|
||||
for p in [json!({}), json!({"name": "work"})] {
|
||||
assert!(s.execute("path.toShape", p.clone()).is_err(), "{p} made a shape");
|
||||
}
|
||||
assert_eq!(doc(&s).layers.len(), layers);
|
||||
}
|
||||
|
||||
/// An inline `path` (a Pen path still being drawn) makes the shape and leaves the Work Path alone,
|
||||
/// unless it was drawn into the Work Path (`consumeWorkPath`).
|
||||
#[test]
|
||||
fn path_to_shape_takes_an_inline_path() {
|
||||
let mut s = session(80, 80, 8);
|
||||
s.execute("path.set", json!({"path": {"subpaths": [{"knots": [[12, 12], [60, 12], [60, 60]]}]}})).unwrap();
|
||||
let drawn = json!({"subpaths": [{"knots": [[5, 5], [30, 5], [30, 30]]}]});
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let info = s.execute("path.toShape", json!({"path": drawn})).unwrap();
|
||||
let id = LayerId(info["layer"].as_u64().unwrap());
|
||||
let LayerContent::Shape(sh) = &doc(&s).layer(id).unwrap().content else { panic!("not a shape layer") };
|
||||
assert_eq!(sh.path.subpaths[0].knots[0].anchor, Point::new(5.0, 5.0));
|
||||
assert!(doc(&s).work_path.is_some(), "the Work Path stays");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), history + 1);
|
||||
s.execute("path.toShape", json!({"path": drawn, "consumeWorkPath": true})).unwrap();
|
||||
assert!(doc(&s).work_path.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_to_shape_rejects_paths_and_names_it_cannot_use() {
|
||||
let mut s = session(80, 80, 8);
|
||||
s.execute("path.set", json!({"path": {"subpaths": [{"knots": [[12, 12], [60, 12], [60, 60]]}]}})).unwrap();
|
||||
let before = doc(&s).clone();
|
||||
let drawn = json!({"subpaths": [{"knots": [[5, 5], [30, 5], [30, 30]]}]});
|
||||
for p in [
|
||||
json!({"path": {"subpaths": [{"knots": [[5, 5]]}]}}),
|
||||
json!({"path": {"subpaths": []}}),
|
||||
json!({"path": 42}),
|
||||
json!({"path": drawn, "name": "work"}),
|
||||
json!({"path": drawn, "consumeWorkPath": "yes"}),
|
||||
json!({"layerName": 5}),
|
||||
json!({"layerName": ""}),
|
||||
json!({"layerName": " "}),
|
||||
] {
|
||||
assert!(s.execute("path.toShape", p.clone()).is_err(), "accepted {p}");
|
||||
assert_eq!(*doc(&s), before, "{p} modified the document");
|
||||
}
|
||||
s.execute("path.set", json!({"path": {"subpaths": [{"knots": [[12, 12]]}]}})).unwrap();
|
||||
assert!(s.execute("path.toShape", json!({})).is_err(), "a one-anchor Work Path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_make_selection_rejects_invalid_options_without_changing_history() {
|
||||
let mut s = session(80, 80, 8);
|
||||
|
||||
@@ -213,9 +213,9 @@ fn tiff_page_errors_keep_memory_refusals_typed_and_other_context() {
|
||||
other => panic!("page 2 approval refusal lost its fields: {other:?}"),
|
||||
}
|
||||
|
||||
let hard = photocraft_io::IoError::PsdImportBudget { required: 9_000, limit: 8_000 };
|
||||
let hard = photocraft_io::IoError::PsdImportBudget { required: 9_000, limit: 8_000, free_memory: None };
|
||||
match tiff_page_error(display, name, 2, hard) {
|
||||
EngineError::PsdHardBudget { name: named, required, limit } => {
|
||||
EngineError::PsdHardBudget { name: named, required, limit, .. } => {
|
||||
assert_eq!(named, name);
|
||||
assert_eq!((required, limit), (9_000, 8_000));
|
||||
}
|
||||
@@ -244,7 +244,7 @@ fn video_frames_to_layers_keeps_a_layered_tiff_page_refusal_typed() {
|
||||
let _limit = super::limits::Scoped::psd_max_pixel_bytes(1);
|
||||
let err = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap_err();
|
||||
match err {
|
||||
EngineError::PsdHardBudget { name, required, limit } => {
|
||||
EngineError::PsdHardBudget { name, required, limit, .. } => {
|
||||
assert_eq!(name, path);
|
||||
assert_eq!(limit, 1);
|
||||
assert!(required > limit, "the page estimate must be past the caller's limit: {required} > {limit}");
|
||||
@@ -295,7 +295,7 @@ fn video_frames_to_layers_uses_the_footage_limit_for_a_single_page_layered_tiff(
|
||||
let _limit = super::limits::Scoped::psd_max_pixel_bytes(1);
|
||||
let err = s.execute("file.import.videoFramesToLayers", json!({"path": path})).unwrap_err();
|
||||
match err {
|
||||
EngineError::PsdHardBudget { name, required, limit } => {
|
||||
EngineError::PsdHardBudget { name, required, limit, .. } => {
|
||||
assert_eq!(name, path);
|
||||
assert_eq!(limit, 1);
|
||||
assert!(required > limit, "the page estimate must be past the caller's limit: {required} > {limit}");
|
||||
|
||||
+177
-3
@@ -23,8 +23,14 @@ pub enum EngineError {
|
||||
PsdApprovalRequired { name: String, required: u64, soft_limit: u64, hard_limit: u64, available_ram: Option<u64> },
|
||||
/// The file's estimated memory cannot be admitted within the hard ceiling, which no approval
|
||||
/// can raise. The requirement may equal the ceiling when the estimate saturated.
|
||||
#[error("cannot open “{name}”: its estimated memory requirement of {required} bytes cannot be admitted within the {limit} byte hard limit on this machine")]
|
||||
PsdHardBudget { name: String, required: u64, limit: u64 },
|
||||
///
|
||||
/// `free_memory` is the free memory measured when it set the limit, if it did.
|
||||
#[error(
|
||||
"cannot open “{name}”: its estimated memory requirement of {required_text} ({required} bytes) cannot be admitted within the {limit_text} ({limit} byte) hard limit{scope}{scratch}{advice}",
|
||||
required_text = bytes_text(.required), limit_text = bytes_text(.limit), scope = build_limit_scope(build_memory_limit()),
|
||||
scratch = unmeasured_scratch_hint(scratch_room_unmeasured()), advice = photocraft_io::memory::low_memory_advice(.free_memory)
|
||||
)]
|
||||
PsdHardBudget { name: String, required: u64, limit: u64, free_memory: Option<u64> },
|
||||
/// The file behind an opened handle is not the one whose memory estimate was approved.
|
||||
/// The document is discarded and is not opened.
|
||||
#[error("“{name}” changed since it was checked; open it again to approve the new file")]
|
||||
@@ -36,6 +42,75 @@ pub enum EngineError {
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// Where this build's hard memory limit comes from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum BuildMemoryLimit {
|
||||
/// Measured from the computer's memory (64-bit desktop).
|
||||
Measured,
|
||||
/// The 32-bit desktop build: its cap, or the computer's memory if lower.
|
||||
Desktop32Bit,
|
||||
/// Fixed by the browser build.
|
||||
FixedWeb,
|
||||
}
|
||||
|
||||
/// This build's memory-limit source, from its target.
|
||||
fn build_memory_limit() -> BuildMemoryLimit {
|
||||
memory_limit_for(cfg!(target_arch = "wasm32"), cfg!(target_pointer_width = "32"))
|
||||
}
|
||||
|
||||
/// The limit source for a target. The wasm32 check comes first: wasm32 is also 32-bit.
|
||||
fn memory_limit_for(is_wasm32: bool, is_32_bit: bool) -> BuildMemoryLimit {
|
||||
if is_wasm32 {
|
||||
BuildMemoryLimit::FixedWeb
|
||||
} else if is_32_bit {
|
||||
BuildMemoryLimit::Desktop32Bit
|
||||
} else {
|
||||
BuildMemoryLimit::Measured
|
||||
}
|
||||
}
|
||||
|
||||
/// The text after "hard limit": where the limit comes from and, where another build could open
|
||||
/// the file, where to get it. Its sentences stand apart so the action isn't lost in the cause.
|
||||
fn build_limit_scope(limit: BuildMemoryLimit) -> String {
|
||||
let releases = crate::updates_cmds::RELEASES;
|
||||
match limit {
|
||||
BuildMemoryLimit::Measured => " on this machine".to_owned(),
|
||||
BuildMemoryLimit::Desktop32Bit => format!(
|
||||
" on this machine. This 32-bit build of PhotoCraft can use at most 2 GiB of memory for a file, or less if the computer has less memory free. The 64-bit build may be able to open it: download it from {releases}"
|
||||
),
|
||||
BuildMemoryLimit::FixedWeb => format!(" of the browser version of PhotoCraft. To open it, download the desktop app from {releases}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The current scratch configuration, not the admission-time cause of a refusal.
|
||||
fn scratch_room_unmeasured() -> bool {
|
||||
let stats = photocraft_raster::spill::stats();
|
||||
stats.free_space_unmeasured && stats.size_cap_bytes.is_none()
|
||||
}
|
||||
|
||||
/// Configuration guidance only: the refusal can instead be bound by a caller or build limit,
|
||||
/// or by memory that cannot spill. Current scratch stats cannot identify that cause.
|
||||
fn unmeasured_scratch_hint(unmeasured: bool) -> &'static str {
|
||||
if unmeasured {
|
||||
". Current scratch configuration: free space can't be measured and no Scratch Size Limit is set. To configure scratch capacity, set a Scratch Size Limit in Preferences > Scratch Disks, or use a disk whose free space can be measured. Scratch capacity cannot override caller or build limits, or replace memory that cannot spill to disk"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
/// A size for people, next to the exact byte count: "21.5 GiB", "900 MiB", "17 B".
|
||||
fn bytes_text(bytes: &u64) -> String {
|
||||
const GIB: u64 = 1 << 30;
|
||||
const MIB: u64 = 1 << 20;
|
||||
if *bytes >= GIB {
|
||||
format!("{:.1} GiB", *bytes as f64 / GIB as f64)
|
||||
} else if *bytes >= MIB {
|
||||
format!("{} MiB", bytes / MIB)
|
||||
} else {
|
||||
format!("{bytes} B")
|
||||
}
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, EngineError>;
|
||||
|
||||
impl EngineError {
|
||||
@@ -59,7 +134,7 @@ pub(crate) fn io_open_error(name: &str, error: photocraft_io::IoError) -> Engine
|
||||
IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram } => {
|
||||
EngineError::PsdApprovalRequired { name: name.to_string(), required, soft_limit, hard_limit, available_ram }
|
||||
}
|
||||
IoError::PsdImportBudget { required, limit } => EngineError::PsdHardBudget { name: name.to_string(), required, limit },
|
||||
IoError::PsdImportBudget { required, limit, free_memory } => EngineError::PsdHardBudget { name: name.to_string(), required, limit, free_memory },
|
||||
IoError::SourceChanged => EngineError::SourceChanged { name: name.to_string() },
|
||||
error => EngineError::Other(format!("{name}: {error}")),
|
||||
}
|
||||
@@ -70,3 +145,102 @@ impl From<photocraft_raster::AllocationError> for EngineError {
|
||||
Self::Other(format!("not enough memory for this operation ({error}); the document was not changed"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn hard(free_memory: Option<u64>) -> EngineError {
|
||||
EngineError::PsdHardBudget { name: "big.psd".into(), required: 9000, limit: 4000, free_memory }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_budget_message_tells_the_user_to_free_memory_when_it_was_measured() {
|
||||
let message = hard(Some(900 << 20)).to_string();
|
||||
assert!(message.ends_with("Close other apps and try again"), "{message}");
|
||||
assert!(message.contains("900 MiB"), "{message}");
|
||||
|
||||
let message = hard(Some(0)).to_string();
|
||||
assert!(message.contains("measured no free memory"), "{message}");
|
||||
|
||||
let message = hard(None).to_string();
|
||||
assert!(message.contains(&build_limit_scope(build_memory_limit())), "{message}");
|
||||
assert!(!message.contains("Close other apps"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn io_open_error_carries_the_free_memory_through() {
|
||||
for free_memory in [None, Some(0), Some(3 << 30)] {
|
||||
let error = photocraft_io::IoError::PsdImportBudget { required: 9000, limit: 4000, free_memory };
|
||||
match io_open_error("big.psd", error) {
|
||||
EngineError::PsdHardBudget { required: 9000, limit: 4000, free_memory: carried, .. } => assert_eq!(carried, free_memory),
|
||||
other => panic!("expected the typed hard refusal, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_budget_scope_text_per_build() {
|
||||
assert_eq!(build_limit_scope(BuildMemoryLimit::Measured), " on this machine");
|
||||
let releases = crate::updates_cmds::RELEASES;
|
||||
assert_eq!(
|
||||
build_limit_scope(BuildMemoryLimit::Desktop32Bit),
|
||||
format!(
|
||||
" on this machine. This 32-bit build of PhotoCraft can use at most 2 GiB of memory for a file, or less if the computer has less memory free. The 64-bit build may be able to open it: download it from {releases}"
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
build_limit_scope(BuildMemoryLimit::FixedWeb),
|
||||
format!(" of the browser version of PhotoCraft. To open it, download the desktop app from {releases}")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmeasured_scratch_hint_only_when_unmeasured() {
|
||||
assert_eq!(unmeasured_scratch_hint(false), "");
|
||||
let hint = unmeasured_scratch_hint(true);
|
||||
assert!(hint.starts_with(". Current scratch configuration:"), "{hint}");
|
||||
assert!(hint.contains("Scratch Size Limit in Preferences > Scratch Disks") && hint.contains("disk whose free space can be measured"), "{hint}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scratch_configuration_hint_does_not_promise_to_raise_a_binding_limit() {
|
||||
let hint = unmeasured_scratch_hint(true);
|
||||
// A caller-bound refusal can carry the same live scratch state as a capacity refusal.
|
||||
// The note must describe that state without attributing this file's refusal to it.
|
||||
assert!(hint.contains("cannot override caller or build limits"), "{hint}");
|
||||
assert!(hint.contains("memory that cannot spill to disk"), "{hint}");
|
||||
assert!(!hint.contains("for this file") && !hint.contains("so it adds no room"), "{hint}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_budget_message_names_file_numbers_and_scope() {
|
||||
let text = EngineError::PsdHardBudget { name: "big.psd".into(), required: 23_049_071_616, limit: 2_147_483_648, free_memory: None }.to_string();
|
||||
for part in ["big.psd", "21.5 GiB", "23049071616 bytes", "2.0 GiB", "2147483648 byte", "hard limit"] {
|
||||
assert!(text.contains(part), "{text}");
|
||||
}
|
||||
assert!(text.contains(&build_limit_scope(build_memory_limit())), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytes_text_picks_a_readable_unit() {
|
||||
assert_eq!(bytes_text(&17), "17 B");
|
||||
assert_eq!(bytes_text(&(900 << 20)), "900 MiB");
|
||||
assert_eq!(bytes_text(&(2 << 30)), "2.0 GiB");
|
||||
assert_eq!(bytes_text(&23_049_071_616), "21.5 GiB");
|
||||
assert!(bytes_text(&u64::MAX).ends_with(" GiB"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_limit_follows_the_target() {
|
||||
assert_eq!(memory_limit_for(true, true), BuildMemoryLimit::FixedWeb);
|
||||
assert_eq!(memory_limit_for(true, false), BuildMemoryLimit::FixedWeb);
|
||||
assert_eq!(memory_limit_for(false, true), BuildMemoryLimit::Desktop32Bit);
|
||||
assert_eq!(memory_limit_for(false, false), BuildMemoryLimit::Measured);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_gib_in_the_text_matches_the_cap() {
|
||||
assert_eq!(photocraft_io::memory::NATIVE_32BIT_PEAK_CAP, 2 << 30);
|
||||
}
|
||||
}
|
||||
|
||||
+250
-66
@@ -12,6 +12,10 @@
|
||||
//! - [`Session::start`] runs a job-capable command on a worker thread and returns its
|
||||
//! [`JobId`]; [`Session::poll_jobs`] (called every frame by the UI) applies finished jobs.
|
||||
//! On wasm `start` runs inline (same API, written once).
|
||||
//! - Work that is written as [`StepWork`] (Place) also runs where there are no threads: with
|
||||
//! [`Session::set_cooperative_jobs`] (the web build's default) [`run_stepped`] registers the job
|
||||
//! without a worker, and [`Session::poll_jobs`] runs one slice of it, about 8 ms, per call. The
|
||||
//! UI stays responsive between slices, and the result is the same as on a worker.
|
||||
//! - [`Session::cancel_job`] sets the flag; the algorithms check it per tile, row band or
|
||||
//! iteration, and the result is discarded. The document is never touched by a worker.
|
||||
//! - A job with an effect outside the session (a save replacing its file) calls
|
||||
@@ -459,20 +463,44 @@ pub struct JobInfo {
|
||||
type Payload = Box<dyn Any + Send>;
|
||||
type Apply = Box<dyn FnOnce(&mut Session, Payload) -> Result<Value> + Send>;
|
||||
|
||||
/// Wall-clock milliseconds since some fixed point (0 on wasm, where `Instant` is unavailable and
|
||||
/// jobs run inline anyway).
|
||||
/// Milliseconds on the monotonic clock since some fixed point (`web_time` reads the browser's on wasm).
|
||||
fn now_ms() -> f64 {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||||
START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
0.0
|
||||
static START: std::sync::OnceLock<web_time::Instant> = std::sync::OnceLock::new();
|
||||
START.get_or_init(web_time::Instant::now).elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// How much of a frame [`Session::poll_jobs`] gives a [`StepWork`] job, unless
|
||||
/// [`Session::set_job_step_budget`] says otherwise.
|
||||
const STEP_BUDGET: std::time::Duration = std::time::Duration::from_millis(8);
|
||||
|
||||
/// A deadline no job reaches, for running [`StepWork`] to the end in one go.
|
||||
fn no_deadline() -> web_time::Instant {
|
||||
let now = web_time::Instant::now();
|
||||
now.checked_add(std::time::Duration::from_secs(1 << 30)).unwrap_or(now)
|
||||
}
|
||||
|
||||
/// Work a job does a slice at a time (see [`run_stepped`]).
|
||||
pub trait StepWork<T>: Send + 'static {
|
||||
/// Does some of the work and returns `Ok(None)` for "not finished, call again", or the result.
|
||||
/// It should return soon after `deadline` passes (checking it between units of work), but
|
||||
/// always does at least one unit, so that calling it again makes progress. `ctx` reports
|
||||
/// progress and tells of cancellation, as for a worker.
|
||||
fn step(&mut self, ctx: &JobCtx, deadline: web_time::Instant) -> Result<Option<T>>;
|
||||
}
|
||||
|
||||
/// Runs `work` to the end, as a worker does.
|
||||
fn drive<T>(mut work: impl StepWork<T>, ctx: &JobCtx) -> Result<T> {
|
||||
loop {
|
||||
ctx.check()?;
|
||||
if let Some(t) = work.step(ctx, no_deadline())? {
|
||||
return Ok(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one slice of a cooperative job: `Ok(None)` when it has more to do.
|
||||
type Stepper = Box<dyn FnMut(&JobCtx, web_time::Instant) -> Result<Option<Payload>> + Send>;
|
||||
|
||||
struct Running {
|
||||
id: JobId,
|
||||
command: String,
|
||||
@@ -496,7 +524,10 @@ struct Running {
|
||||
/// The document's layer selection when the job started: applying targets it, not whatever
|
||||
/// got selected meanwhile (a Type click does that without editing the document, #7366).
|
||||
layers: Option<LayerSelection>,
|
||||
rx: std::sync::mpsc::Receiver<Result<Payload>>,
|
||||
/// Where the worker thread sends its result. A cooperative job has none: [`Session::poll_jobs`]
|
||||
/// runs its `stepper` instead.
|
||||
rx: Option<std::sync::mpsc::Receiver<Result<Payload>>>,
|
||||
stepper: Option<Stepper>,
|
||||
apply: Option<Apply>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
handle: Option<std::thread::JoinHandle<()>>,
|
||||
@@ -524,6 +555,16 @@ impl LayerSelection {
|
||||
}
|
||||
|
||||
impl Running {
|
||||
/// Runs a slice of a cooperative job until `deadline`: `Ok(None)` when it has more to do.
|
||||
/// A cancelled job ends with `Err(Cancelled)` before doing more.
|
||||
fn step(&mut self, deadline: web_time::Instant) -> Result<Option<Payload>> {
|
||||
self.ctx.check()?;
|
||||
match self.stepper.as_mut() {
|
||||
Some(stepper) => stepper(&self.ctx, deadline),
|
||||
None => Err(EngineError::Other(format!("`{}` has nothing to run", self.label))),
|
||||
}
|
||||
}
|
||||
|
||||
fn info(&self) -> JobInfo {
|
||||
JobInfo {
|
||||
id: self.id,
|
||||
@@ -563,7 +604,6 @@ fn reap_draining(draining: &mut Vec<Draining>) -> bool {
|
||||
}
|
||||
|
||||
/// The session's job table (see the module docs).
|
||||
#[derive(Default)]
|
||||
pub struct Jobs {
|
||||
next: u64,
|
||||
/// Set while [`Session::start`] runs a command: [`run`] spawns instead of running inline.
|
||||
@@ -580,6 +620,39 @@ pub struct Jobs {
|
||||
draining: Vec<Draining>,
|
||||
/// The context inline job work runs under (see [`Session::set_inline_job_ctx`]).
|
||||
inline: Option<JobCtx>,
|
||||
/// No worker threads: [`StepWork`] jobs are stepped by [`Session::poll_jobs`], everything else
|
||||
/// runs inline. On for wasm; see [`Session::set_cooperative_jobs`].
|
||||
cooperative: bool,
|
||||
/// How long [`Session::poll_jobs`] runs a cooperative job per call.
|
||||
step_budget: std::time::Duration,
|
||||
}
|
||||
|
||||
// Derivable on a desktop, where `cooperative` starts off; wasm starts it on.
|
||||
#[allow(clippy::derivable_impls)]
|
||||
impl Default for Jobs {
|
||||
/// No jobs, spawning off; a session steps its jobs itself (cooperative) on wasm only.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
next: 0,
|
||||
spawn: false,
|
||||
pending: None,
|
||||
running: Vec::new(),
|
||||
events: Vec::new(),
|
||||
recent: Vec::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
draining: Vec::new(),
|
||||
inline: None,
|
||||
cooperative: cfg!(target_arch = "wasm32"),
|
||||
step_budget: STEP_BUDGET,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Jobs {
|
||||
/// Does a job started now run on a worker thread? (Not inline, and not stepped on this thread.)
|
||||
fn threaded(&self) -> bool {
|
||||
self.spawn && !self.cooperative && !cfg!(target_arch = "wasm32")
|
||||
}
|
||||
}
|
||||
|
||||
const RECENT: usize = 16;
|
||||
@@ -684,10 +757,81 @@ pub fn run<T: Send + 'static>(
|
||||
// The job's document: stored paths it follows are resolved against it on any thread.
|
||||
let document = s.active().and_then(|d| d.path.as_deref()).map(std::path::PathBuf::from);
|
||||
let _document = crate::doc_path::scope(document.as_deref());
|
||||
if !s.jobs.spawn || cfg!(target_arch = "wasm32") {
|
||||
if !s.jobs.threaded() {
|
||||
let t = work(&s.jobs.inline.clone().unwrap_or_default())?;
|
||||
return apply(s, t);
|
||||
}
|
||||
let mut job = new_job(s, label, lock_document, authorization, document.clone(), apply)?;
|
||||
let (tx, rx) = std::sync::mpsc::channel::<Result<Payload>>();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let wctx = job.ctx.clone();
|
||||
let label_w = label.to_string();
|
||||
// The work closure is moved into the thread. If spawning fails (thread limits), there is
|
||||
// no way to get it back, so the error is reported instead.
|
||||
let spawned = std::thread::Builder::new().name(format!("photocraft-job-{}", job.id.0)).spawn(move || {
|
||||
let _authorization = AuthorizationScope::enter(authorization);
|
||||
let _document = crate::doc_path::scope(document.as_deref());
|
||||
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work(&wctx).map(|t| Box::new(t) as Payload)))
|
||||
.unwrap_or_else(|_| Err(EngineError::Other(format!("`{label_w}` failed with an internal error (logged); the document is unchanged"))));
|
||||
wctx.finish_work();
|
||||
// The receiver is gone when the job was cancelled: nothing to report.
|
||||
let _ = tx.send(r);
|
||||
});
|
||||
job.handle = Some(spawned.map_err(|e| EngineError::Other(format!("could not start a background job: {e}")))?);
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
// Unreachable (wasm runs inline above); keep the types used.
|
||||
drop((work, tx));
|
||||
}
|
||||
job.rx = Some(rx);
|
||||
let id = job.id;
|
||||
s.jobs.pending = Some(job);
|
||||
Ok(json!({"job": id.0}))
|
||||
}
|
||||
|
||||
/// [`run`] for work done a slice at a time ([`StepWork`]): where the session has no worker threads
|
||||
/// ([`Session::set_cooperative_jobs`], the web build) the job runs on the UI thread, a slice of
|
||||
/// about 8 ms per [`Session::poll_jobs`], so the window keeps repainting meanwhile. Elsewhere it
|
||||
/// is [`run`] with `work` driven to the end: on a worker thread for [`Session::start`], inline for
|
||||
/// [`Session::execute`]. The result is the same either way.
|
||||
pub fn run_stepped<T: Send + 'static>(
|
||||
s: &mut Session,
|
||||
label: &str,
|
||||
lock_document: bool,
|
||||
work: impl StepWork<T>,
|
||||
apply: impl FnOnce(&mut Session, T) -> Result<Value> + Send + 'static,
|
||||
) -> Result<Value> {
|
||||
if !(s.jobs.spawn && s.jobs.cooperative) {
|
||||
return run(s, label, lock_document, move |ctx| drive(work, ctx), apply);
|
||||
}
|
||||
let authorization = s.authorize.or_else(|| RENDER_AUTHORIZATION.with(std::cell::Cell::get));
|
||||
let document = s.active().and_then(|d| d.path.as_deref()).map(std::path::PathBuf::from);
|
||||
let mut job = new_job(s, label, lock_document, authorization, document.clone(), apply)?;
|
||||
let (label_w, mut work) = (label.to_string(), work);
|
||||
// The slices run under the requesting session's authority and document, as a worker would.
|
||||
job.stepper = Some(Box::new(move |ctx, deadline| {
|
||||
let _authorization = AuthorizationScope::enter(authorization);
|
||||
let _document = crate::doc_path::scope(document.as_deref());
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work.step(ctx, deadline)))
|
||||
.unwrap_or_else(|_| Err(EngineError::Other(format!("`{label_w}` failed with an internal error (logged); the document is unchanged"))))
|
||||
.map(|done| done.map(|t| Box::new(t) as Payload))
|
||||
}));
|
||||
let id = job.id;
|
||||
s.jobs.pending = Some(job);
|
||||
Ok(json!({"job": id.0}))
|
||||
}
|
||||
|
||||
/// A job for [`run`] and [`run_stepped`] to start, without its worker.
|
||||
fn new_job<T: Send + 'static>(
|
||||
s: &mut Session,
|
||||
label: &str,
|
||||
lock_document: bool,
|
||||
authorization: Option<Authorization>,
|
||||
document: Option<std::path::PathBuf>,
|
||||
apply: impl FnOnce(&mut Session, T) -> Result<Value> + Send + 'static,
|
||||
) -> Result<Running> {
|
||||
if s.jobs.pending.is_some() {
|
||||
return Err(EngineError::Other(format!("`{label}` started a second background job in one command")));
|
||||
}
|
||||
@@ -706,41 +850,15 @@ pub fn run<T: Send + 'static>(
|
||||
(true, None) => return Err(EngineError::NoDocument),
|
||||
(false, _) => (None, None, None),
|
||||
};
|
||||
let ctx = JobCtx::new();
|
||||
let (tx, rx) = std::sync::mpsc::channel::<Result<Payload>>();
|
||||
let apply_document = document.clone();
|
||||
let erased: Apply = Box::new(move |s, any| {
|
||||
let _authorization = AuthorizationScope::enter(authorization);
|
||||
let _document = crate::doc_path::scope(apply_document.as_deref());
|
||||
let _document = crate::doc_path::scope(document.as_deref());
|
||||
let t = any.downcast::<T>().map_err(|_| EngineError::Other("internal error: job result type mismatch".into()))?;
|
||||
apply(s, *t)
|
||||
});
|
||||
s.jobs.next = s.jobs.next.checked_add(1).ok_or_else(|| EngineError::Other("background job identifier space exhausted".into()))?;
|
||||
let id = JobId(s.jobs.next);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let handle = {
|
||||
let wctx = ctx.clone();
|
||||
let label_w = label.to_string();
|
||||
// The work closure is moved into the thread. If spawning fails (thread limits), there is
|
||||
// no way to get it back, so the error is reported instead.
|
||||
let spawned = std::thread::Builder::new().name(format!("photocraft-job-{}", id.0)).spawn(move || {
|
||||
let _authorization = AuthorizationScope::enter(authorization);
|
||||
let _document = crate::doc_path::scope(document.as_deref());
|
||||
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work(&wctx).map(|t| Box::new(t) as Payload)))
|
||||
.unwrap_or_else(|_| Err(EngineError::Other(format!("`{label_w}` failed with an internal error (logged); the document is unchanged"))));
|
||||
wctx.finish_work();
|
||||
// The receiver is gone when the job was cancelled: nothing to report.
|
||||
let _ = tx.send(r);
|
||||
});
|
||||
Some(spawned.map_err(|e| EngineError::Other(format!("could not start a background job: {e}")))?)
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
// Unreachable (wasm runs inline above); keep the types used.
|
||||
drop((work, tx));
|
||||
}
|
||||
s.jobs.pending = Some(Running {
|
||||
id,
|
||||
Ok(Running {
|
||||
id: JobId(s.jobs.next),
|
||||
command: String::new(),
|
||||
label: label.to_string(),
|
||||
params: Value::Null,
|
||||
@@ -750,18 +868,18 @@ pub fn run<T: Send + 'static>(
|
||||
before: crate::actions_record::Before::capture(s),
|
||||
doc,
|
||||
snapshot,
|
||||
ctx,
|
||||
ctx: JobCtx::new(),
|
||||
started_ms: now_ms(),
|
||||
coalesce: s.coalesce_request.clone(),
|
||||
color_restrict: s.color_restrict,
|
||||
filter_mask_layer: s.filter_mask_layer,
|
||||
layers,
|
||||
rx,
|
||||
rx: None,
|
||||
stepper: None,
|
||||
apply: Some(erased),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
handle,
|
||||
});
|
||||
Ok(json!({"job": id.0}))
|
||||
handle: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A document edit whose body is the job: like [`Session::edit`] (one undo step named `label`),
|
||||
@@ -773,7 +891,7 @@ pub fn edit_job<R: Send + 'static>(
|
||||
f: impl FnOnce(&mut Document, &mut Option<LayerId>, &JobCtx) -> Result<R> + Send + 'static,
|
||||
finish: impl FnOnce(R) -> Value + Send + 'static,
|
||||
) -> Result<Value> {
|
||||
if !s.jobs.spawn || cfg!(target_arch = "wasm32") {
|
||||
if !s.jobs.threaded() {
|
||||
// Inline: exactly `Session::edit`, as before jobs existed.
|
||||
let ctx = s.jobs.inline.clone().unwrap_or_default();
|
||||
let r = s.edit(label, |doc, active| f(doc, active, &ctx))?;
|
||||
@@ -1089,15 +1207,17 @@ impl Session {
|
||||
/// insert the layer as one undo step when [`Session::poll_jobs`] applies it. `name` names the
|
||||
/// layer and the file; `params` are the command's (`scale`, `center`, `fit`, `smartObject`).
|
||||
/// The job's result is the command's: `{layer, frame, scale, bounds, smartObject}`. The active
|
||||
/// document is locked meanwhile, so this is refused while another job runs on it. Runs inline
|
||||
/// on wasm.
|
||||
/// document is locked meanwhile, so this is refused while another job runs on it. On wasm (and
|
||||
/// in a [cooperative](Session::set_cooperative_jobs) session) it is not a worker's job but
|
||||
/// one [`Session::poll_jobs`] runs a slice of per call.
|
||||
pub fn start_place_bytes(&mut self, name: &str, bytes: Vec<u8>, linked: Option<String>, params: Value) -> Result<Started> {
|
||||
let input = crate::file_cmds::PlaceInput::new(self, name, bytes, linked, ¶ms)?;
|
||||
let (command, label) = (input.command(), input.job_label());
|
||||
if let Some(conflict) = self.job_conflict(command, true) {
|
||||
return Err(EngineError::Other(conflict));
|
||||
}
|
||||
self.start_job(command, json!({"name": name}), &label, true, move |ctx| crate::file_cmds::prepare_place(input, ctx), crate::file_cmds::apply_place)
|
||||
let work = crate::file_cmds::PlaceSteps::new(input, self.cooperative_jobs());
|
||||
self.start_job_stepped(command, json!({"name": name}), &label, true, work, crate::file_cmds::apply_place)
|
||||
}
|
||||
|
||||
/// Decodes a file in a job and optionally holds damaged PSD content for
|
||||
@@ -1288,9 +1408,30 @@ impl Session {
|
||||
work: impl FnOnce(&JobCtx) -> Result<T> + Send + 'static,
|
||||
apply: impl FnOnce(&mut Session, T) -> Result<Value> + Send + 'static,
|
||||
) -> Result<Started> {
|
||||
self.start_registered(command, params, spawn, |s| run(s, label, lock_document, work, apply))
|
||||
}
|
||||
|
||||
/// [`Session::start_job`] for [`StepWork`]: on a worker, or where the session is cooperative
|
||||
/// (see [`Session::set_cooperative_jobs`]) a slice per [`Session::poll_jobs`] on this thread.
|
||||
pub fn start_job_stepped<T: Send + 'static>(
|
||||
&mut self,
|
||||
command: &str,
|
||||
params: Value,
|
||||
label: &str,
|
||||
lock_document: bool,
|
||||
work: impl StepWork<T>,
|
||||
apply: impl FnOnce(&mut Session, T) -> Result<Value> + Send + 'static,
|
||||
) -> Result<Started> {
|
||||
self.start_registered(command, params, true, |s| run_stepped(s, label, lock_document, work, apply))
|
||||
}
|
||||
|
||||
/// Runs `register` (which calls [`run`] or [`run_stepped`]) with background jobs allowed when
|
||||
/// `spawn` (the jobs then run on a worker, or on wasm inline or in slices, see
|
||||
/// `Jobs::threaded`), and files the job it started under `command`.
|
||||
fn start_registered(&mut self, command: &str, params: Value, spawn: bool, register: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Started> {
|
||||
let prev_spawn = self.jobs.spawn;
|
||||
self.jobs.spawn = spawn && !cfg!(target_arch = "wasm32");
|
||||
let r = run(self, label, lock_document, work, apply);
|
||||
self.jobs.spawn = spawn;
|
||||
let r = register(self);
|
||||
self.jobs.spawn = prev_spawn;
|
||||
let pending = self.jobs.pending.take();
|
||||
match (r, pending) {
|
||||
@@ -1311,23 +1452,58 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this session has no worker threads: [`StepWork`] jobs are run a slice at a time by
|
||||
/// [`Session::poll_jobs`] on the UI thread, and every other command runs inline. The web
|
||||
/// build (wasm) is always like this; tests turn it on to run that path on a desktop.
|
||||
pub fn cooperative_jobs(&self) -> bool {
|
||||
self.jobs.cooperative
|
||||
}
|
||||
|
||||
/// How long one [`Session::poll_jobs`] runs a cooperative job (8 ms by default, a share of a
|
||||
/// frame). A slice always does one unit of work, so zero makes every poll do just that: tests
|
||||
/// use it to count polls without depending on the machine's speed.
|
||||
pub fn set_job_step_budget(&mut self, budget: std::time::Duration) {
|
||||
self.jobs.step_budget = budget;
|
||||
}
|
||||
|
||||
/// Turn [`Session::cooperative_jobs`] on or off. Jobs already running keep running as they
|
||||
/// started.
|
||||
pub fn set_cooperative_jobs(&mut self, on: bool) {
|
||||
self.jobs.cooperative = on;
|
||||
}
|
||||
|
||||
/// Apply finished background jobs (on this thread) and return every job that ended since
|
||||
/// the last call. Cheap when nothing runs; the UI calls it every frame.
|
||||
/// the last call. Also runs one slice (about 8 ms) of a cooperative job, if there is one. Cheap
|
||||
/// when nothing runs; the UI calls it every frame.
|
||||
pub fn poll_jobs(&mut self) -> Vec<JobEvent> {
|
||||
let mut i = 0;
|
||||
let mut stepped = false;
|
||||
let budget = self.jobs.step_budget;
|
||||
while i < self.jobs.running.len() {
|
||||
match self.jobs.running.get(i).map(|r| r.rx.try_recv()) {
|
||||
Some(Ok(r)) => {
|
||||
let Some(job) = self.jobs.running.get_mut(i) else { break };
|
||||
let finished = match &job.rx {
|
||||
Some(rx) => match rx.try_recv() {
|
||||
Ok(r) => Some(r),
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => None,
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
|
||||
Some(Err(EngineError::Other(format!("`{}` stopped unexpectedly; the document is unchanged", job.label))))
|
||||
}
|
||||
},
|
||||
// One cooperative job gets the frame's budget; any others wait for the next poll.
|
||||
None if !stepped => {
|
||||
stepped = true;
|
||||
// An absurd budget (`Duration::MAX` through `set_job_step_budget`) must not
|
||||
// overflow the deadline: fall back to one no job reaches.
|
||||
job.step(web_time::Instant::now().checked_add(budget).unwrap_or_else(no_deadline)).transpose()
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
match finished {
|
||||
Some(r) => {
|
||||
let job = self.jobs.running.remove(i);
|
||||
self.finish_job(job, r);
|
||||
}
|
||||
Some(Err(std::sync::mpsc::TryRecvError::Empty)) => i += 1,
|
||||
Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) => {
|
||||
let job = self.jobs.running.remove(i);
|
||||
let label = job.label.clone();
|
||||
self.finish_job(job, Err(EngineError::Other(format!("`{label}` stopped unexpectedly; the document is unchanged"))));
|
||||
}
|
||||
None => break,
|
||||
None => i += 1,
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -1343,11 +1519,19 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Block until job `id` ends, apply it, and return its result (the control channel's and
|
||||
/// MCP's default `wait`, and the CLI). `Err(Cancelled)` if it was cancelled.
|
||||
/// MCP's default `wait`, and the CLI). `Err(Cancelled)` if it was cancelled. A cooperative job
|
||||
/// is run to the end here.
|
||||
pub fn wait_job(&mut self, id: JobId) -> Result<Value> {
|
||||
if let Some(i) = self.jobs.running.iter().position(|r| r.id == id) {
|
||||
let job = self.jobs.running.remove(i);
|
||||
let r = job.rx.recv().unwrap_or_else(|_| Err(EngineError::Other(format!("`{}` stopped unexpectedly", job.label))));
|
||||
let mut job = self.jobs.running.remove(i);
|
||||
let r = match &job.rx {
|
||||
Some(rx) => rx.recv().unwrap_or_else(|_| Err(EngineError::Other(format!("`{}` stopped unexpectedly", job.label)))),
|
||||
None => loop {
|
||||
if let Some(r) = job.step(no_deadline()).transpose() {
|
||||
break r;
|
||||
}
|
||||
},
|
||||
};
|
||||
self.finish_job(job, r);
|
||||
}
|
||||
match self.jobs.recent.iter().rev().find(|j| j.id == id) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::json;
|
||||
@@ -1161,6 +1162,224 @@ fn every_job_terminal_path_drops_a_live_commit_stroke() {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- cooperative jobs (no worker threads, as on the web) ----------
|
||||
|
||||
/// A job that needs `needed` calls, and records what each one saw.
|
||||
struct Counting {
|
||||
needed: usize,
|
||||
done: usize,
|
||||
/// How far ahead the deadline of each call was.
|
||||
ahead: Arc<Mutex<Vec<Duration>>>,
|
||||
calls: Arc<AtomicUsize>,
|
||||
thread: Arc<Mutex<Option<std::thread::ThreadId>>>,
|
||||
dropped: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Drop for Counting {
|
||||
fn drop(&mut self) {
|
||||
self.dropped.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
impl StepWork<usize> for Counting {
|
||||
fn step(&mut self, ctx: &JobCtx, deadline: web_time::Instant) -> Result<Option<usize>> {
|
||||
self.ahead.lock().unwrap().push(deadline.saturating_duration_since(web_time::Instant::now()));
|
||||
*self.thread.lock().unwrap() = Some(std::thread::current().id());
|
||||
self.calls.fetch_add(1, Ordering::Relaxed);
|
||||
self.done += 1;
|
||||
ctx.progress(self.done as f32 / self.needed as f32, "Counting");
|
||||
Ok((self.done >= self.needed).then_some(self.done))
|
||||
}
|
||||
}
|
||||
|
||||
struct Probe {
|
||||
ahead: Arc<Mutex<Vec<Duration>>>,
|
||||
calls: Arc<AtomicUsize>,
|
||||
thread: Arc<Mutex<Option<std::thread::ThreadId>>>,
|
||||
dropped: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
fn counting(needed: usize) -> (Counting, Probe) {
|
||||
let probe = Probe { ahead: Arc::default(), calls: Arc::default(), thread: Arc::default(), dropped: Arc::default() };
|
||||
let work =
|
||||
Counting { needed, done: 0, ahead: probe.ahead.clone(), calls: probe.calls.clone(), thread: probe.thread.clone(), dropped: probe.dropped.clone() };
|
||||
(work, probe)
|
||||
}
|
||||
|
||||
fn start_counting(s: &mut Session, needed: usize, lock: bool) -> (JobId, Probe) {
|
||||
let (work, probe) = counting(needed);
|
||||
let id = job(s.start_job_stepped("test.stepped", json!({}), "Stepping", lock, work, |_, n| Ok(json!({"steps": n}))).unwrap());
|
||||
(id, probe)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cooperative_job_gets_one_slice_per_poll_on_the_calling_thread() {
|
||||
let mut s = session(40, 30);
|
||||
s.set_cooperative_jobs(true);
|
||||
let (id, probe) = start_counting(&mut s, 3, true);
|
||||
assert!(s.has_jobs());
|
||||
assert_eq!(probe.calls.load(Ordering::Relaxed), 0, "starting does no work");
|
||||
// The document is locked as for a worker.
|
||||
let refused = s.execute("layer.new.layer", json!({})).unwrap_err().to_string();
|
||||
assert!(refused.contains("Stepping"), "{refused}");
|
||||
for polls in 1..=2 {
|
||||
assert!(s.poll_jobs().is_empty(), "poll {polls}");
|
||||
assert_eq!(probe.calls.load(Ordering::Relaxed), polls);
|
||||
assert!(s.has_jobs());
|
||||
}
|
||||
let info = s.job(id).unwrap();
|
||||
assert_eq!(info.message, "Counting");
|
||||
assert!((info.progress - 2.0 / 3.0).abs() < 1e-6, "{}", info.progress);
|
||||
let events = s.poll_jobs();
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events[0].outcome, JobOutcome::Done(json!({"steps": 3})));
|
||||
assert_eq!((events[0].command.as_str(), events[0].label.as_str()), ("test.stepped", "Stepping"));
|
||||
assert!(!s.has_jobs());
|
||||
assert_eq!(*probe.thread.lock().unwrap(), Some(std::thread::current().id()), "no worker thread");
|
||||
// Each slice was given about a frame's budget: no more than 8 ms from the poll.
|
||||
let ahead = probe.ahead.lock().unwrap().clone();
|
||||
assert!(ahead.iter().all(|d| *d <= STEP_BUDGET), "{ahead:?}");
|
||||
assert!(ahead.iter().any(|d| *d > Duration::ZERO), "{ahead:?}");
|
||||
assert!(probe.dropped.load(Ordering::Relaxed), "the finished work is let go");
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cooperative_job_reports_real_elapsed_time() {
|
||||
let mut s = session(8, 8);
|
||||
s.set_cooperative_jobs(true);
|
||||
let (id, _) = start_counting(&mut s, 5, false);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
assert!(s.job(id).unwrap().elapsed_ms >= 15.0, "{}", s.job(id).unwrap().elapsed_ms);
|
||||
assert_eq!(s.wait_job(id).unwrap(), json!({"steps": 5}));
|
||||
}
|
||||
|
||||
/// A budget too large to add to an `Instant` runs the slice to the end instead of overflowing.
|
||||
#[test]
|
||||
fn a_huge_step_budget_does_not_panic() {
|
||||
let mut s = session(8, 8);
|
||||
s.set_cooperative_jobs(true);
|
||||
s.set_job_step_budget(Duration::MAX);
|
||||
let (id, probe) = start_counting(&mut s, 2, false);
|
||||
s.poll_jobs();
|
||||
assert_eq!(probe.calls.load(Ordering::Relaxed), 1, "one slice still runs");
|
||||
assert_eq!(s.wait_job(id).unwrap(), json!({"steps": 2}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_one_cooperative_job_is_stepped_per_poll() {
|
||||
let mut s = session(8, 8);
|
||||
s.set_cooperative_jobs(true);
|
||||
let (a, pa) = start_counting(&mut s, 5, false);
|
||||
let (b, pb) = start_counting(&mut s, 5, false);
|
||||
s.poll_jobs();
|
||||
assert_eq!((pa.calls.load(Ordering::Relaxed), pb.calls.load(Ordering::Relaxed)), (1, 0));
|
||||
s.poll_jobs();
|
||||
assert_eq!((pa.calls.load(Ordering::Relaxed), pb.calls.load(Ordering::Relaxed)), (2, 0));
|
||||
// Both finish all the same.
|
||||
assert_eq!(s.wait_job(a).unwrap(), json!({"steps": 5}));
|
||||
assert_eq!(s.wait_job(b).unwrap(), json!({"steps": 5}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_job_runs_a_cooperative_job_to_the_end() {
|
||||
let mut s = session(8, 8);
|
||||
s.set_cooperative_jobs(true);
|
||||
let (id, probe) = start_counting(&mut s, 50, true);
|
||||
assert_eq!(s.wait_job(id).unwrap(), json!({"steps": 50}));
|
||||
assert_eq!(probe.calls.load(Ordering::Relaxed), 50);
|
||||
assert!(!s.has_jobs());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_a_cooperative_job_between_polls_discards_it() {
|
||||
let mut s = session(8, 8);
|
||||
s.set_cooperative_jobs(true);
|
||||
let (id, probe) = start_counting(&mut s, 10, true);
|
||||
s.poll_jobs();
|
||||
assert!(s.cancel_job(id));
|
||||
assert!(probe.dropped.load(Ordering::Relaxed), "the work is let go at once");
|
||||
assert!(!s.has_jobs());
|
||||
let events = s.poll_jobs();
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(events[0].outcome, JobOutcome::Cancelled);
|
||||
assert_eq!(probe.calls.load(Ordering::Relaxed), 1, "no slice after the cancel");
|
||||
assert!(matches!(s.wait_job(id), Err(EngineError::Cancelled)));
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_or_panicking_slice_fails_the_job() {
|
||||
struct Fails(bool);
|
||||
impl StepWork<()> for Fails {
|
||||
fn step(&mut self, _: &JobCtx, _: web_time::Instant) -> Result<Option<()>> {
|
||||
if self.0 { Err(EngineError::Other("the slice failed".into())) } else { panic!("a bug in the slice") }
|
||||
}
|
||||
}
|
||||
for panics in [false, true] {
|
||||
let mut s = session(8, 8);
|
||||
s.set_cooperative_jobs(true);
|
||||
let id = job(s.start_job_stepped("test.stepped", json!({}), "Failing", true, Fails(!panics), |_, ()| Ok(json!({}))).unwrap());
|
||||
let events = s.poll_jobs();
|
||||
assert_eq!(events.len(), 1, "panics={panics}");
|
||||
let JobOutcome::Failed(msg) = &events[0].outcome else { panic!("{:?}", events[0]) };
|
||||
assert_eq!(events[0].id, id);
|
||||
if panics {
|
||||
assert!(msg.contains("internal error"), "{msg}");
|
||||
} else {
|
||||
assert_eq!(msg, "the slice failed");
|
||||
}
|
||||
assert!(!s.has_jobs());
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cooperative_session_runs_other_commands_inline() {
|
||||
let mut s = session(60, 40);
|
||||
s.set_cooperative_jobs(true);
|
||||
assert!(matches!(s.start("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap(), Started::Done(_)));
|
||||
assert!(!s.has_jobs());
|
||||
let opened = s.start_open("a.png", OpenSource::Bytes(Arc::new(Vec::new())));
|
||||
assert!(opened.is_err() || matches!(opened, Ok(Started::Done(_))), "opening runs inline too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stepped_work_without_cooperation_runs_on_a_worker_or_inline() {
|
||||
// A worker thread, when started in the background.
|
||||
let mut s = session(8, 8);
|
||||
assert!(!s.cooperative_jobs() || cfg!(target_arch = "wasm32"));
|
||||
let (id, probe) = start_counting(&mut s, 4, true);
|
||||
let e = wait_event(&mut s, id);
|
||||
assert_eq!(e.outcome, JobOutcome::Done(json!({"steps": 4})));
|
||||
assert_ne!(*probe.thread.lock().unwrap(), Some(std::thread::current().id()), "ran on a worker");
|
||||
assert_eq!(probe.calls.load(Ordering::Relaxed), 4);
|
||||
|
||||
// Inline, when run as part of a command.
|
||||
let (work, probe) = counting(6);
|
||||
let v = run_stepped(&mut s, "Inline", true, work, |_, n| Ok(json!({"steps": n}))).unwrap();
|
||||
assert_eq!(v, json!({"steps": 6}));
|
||||
assert_eq!(*probe.thread.lock().unwrap(), Some(std::thread::current().id()));
|
||||
assert!(!s.has_jobs());
|
||||
|
||||
// Cooperative, but not started in the background: inline as well.
|
||||
s.set_cooperative_jobs(true);
|
||||
let (work, _) = counting(3);
|
||||
assert_eq!(run_stepped(&mut s, "Inline", true, work, |_, n| Ok(json!({"steps": n}))).unwrap(), json!({"steps": 3}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inline_stepped_job_stops_when_cancelled() {
|
||||
let mut s = session(8, 8);
|
||||
let ctx = JobCtx::new();
|
||||
s.set_inline_job_ctx(Some(ctx.clone()));
|
||||
let (work, probe) = counting(1_000_000);
|
||||
ctx.cancel();
|
||||
let r = run_stepped(&mut s, "Inline", true, work, |_, n| Ok(json!({"steps": n})));
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||||
assert!(probe.calls.load(Ordering::Relaxed) <= 1);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn background_admission_counts_cancelled_workers_until_they_finish() {
|
||||
@@ -1350,14 +1569,14 @@ fn a_failed_job_keeps_its_typed_error_for_wait_and_events() {
|
||||
json!({}),
|
||||
"Test hard budget",
|
||||
false,
|
||||
|_ctx| -> Result<()> { Err(EngineError::PsdHardBudget { name: "too-big.psd".into(), required: 9000, limit: 4000 }) },
|
||||
|_ctx| -> Result<()> { Err(EngineError::PsdHardBudget { name: "too-big.psd".into(), required: 9000, limit: 4000, free_memory: None }) },
|
||||
|_, _| Ok(Value::Null),
|
||||
)
|
||||
.unwrap();
|
||||
let id = job(started);
|
||||
let err = s.wait_job(id).expect_err("the job fails");
|
||||
assert!(
|
||||
matches!(&err, EngineError::PsdHardBudget { name, required, limit } if name == "too-big.psd" && *required == 9000 && *limit == 4000),
|
||||
matches!(&err, EngineError::PsdHardBudget { name, required, limit, .. } if name == "too-big.psd" && *required == 9000 && *limit == 4000),
|
||||
"wait_job must not flatten the typed refusal: {err:?}"
|
||||
);
|
||||
let event = s.poll_jobs().into_iter().find(|e| e.id == id).expect("the job event");
|
||||
|
||||
@@ -100,6 +100,11 @@ choice!(
|
||||
/// pointer (Photoshop), or erase with the current brush while dragging (Krita, Paint).
|
||||
RightClickPaint { BrushPicker = "brushPicker", Erase = "erase" } default BrushPicker
|
||||
);
|
||||
choice!(
|
||||
/// Windows: which pen input supplies pressure. Windows Ink is the default; WinTab needs
|
||||
/// Windows Ink turned off in the tablet driver's utility and a restart.
|
||||
TabletInput { WindowsInk = "windowsInk", WinTab = "winTab" } default WindowsInk
|
||||
);
|
||||
choice!(OtherCursor { Standard = "standard", Precise = "precise" } default Standard);
|
||||
choice!(CheckerSize { None = "none", Small = "small", Medium = "medium", Large = "large" } default Medium);
|
||||
choice!(CheckerColors { Light = "light", Medium = "medium", Dark = "dark", Red = "red", Orange = "orange", Green = "green", Blue = "blue", Purple = "purple", Custom = "custom" } default Light);
|
||||
@@ -287,9 +292,6 @@ pub struct Interface {
|
||||
/// objects in a large document stay visible (Photoshop's Clip Thumbnails to Layer Bounds; #4281).
|
||||
pub clip_thumbnails_to_layer_bounds: bool,
|
||||
pub show_tooltips: bool,
|
||||
/// Menus, popups and collapsing sections fade and slide, and scroll areas glide to a new
|
||||
/// position. Off, everything changes at once (a reduced-motion mode; #1218, #3273).
|
||||
pub enable_animations: bool,
|
||||
/// Move tool drags show only the layer's outline and an arrow, leaving its pixels in place
|
||||
/// until release. Off (the default), the pixels follow the pointer live inside the outline.
|
||||
pub show_bounding_box_when_dragging_layer: bool,
|
||||
@@ -330,7 +332,6 @@ impl Default for Interface {
|
||||
show_menu_colors: true,
|
||||
clip_thumbnails_to_layer_bounds: false,
|
||||
show_tooltips: true,
|
||||
enable_animations: true,
|
||||
show_bounding_box_when_dragging_layer: false,
|
||||
system_title_bar: false,
|
||||
show_file_name_in_title: true,
|
||||
@@ -396,6 +397,9 @@ pub struct Tools {
|
||||
pub right_click_with_painting_tools: RightClickPaint,
|
||||
/// Pen tablets: pressure, tilt and rotation reach the brush (off: a pen paints like a mouse).
|
||||
pub use_tablet_pressure: bool,
|
||||
/// Windows: which pen input supplies pressure. Windows Ink is the default; WinTab needs
|
||||
/// Windows Ink turned off in the tablet driver's utility and a restart.
|
||||
pub tablet_input: TabletInput,
|
||||
/// Pen pressure response: `[input, output]` control points in 0..1 that the pen's pressure
|
||||
/// passes through before it reaches any brush ([`PressureCurve`]). Linear by default.
|
||||
pub pressure_curve: Vec<[f32; 2]>,
|
||||
@@ -423,6 +427,7 @@ impl Default for Tools {
|
||||
double_click_layer_mask_launches_select_and_mask: true,
|
||||
right_click_with_painting_tools: RightClickPaint::BrushPicker,
|
||||
use_tablet_pressure: true,
|
||||
tablet_input: TabletInput::WindowsInk,
|
||||
pressure_curve: vec![[0.0, 0.0], [1.0, 1.0]],
|
||||
bundle_nudges: true,
|
||||
nudge_bundle_pause_ms: 1000,
|
||||
|
||||
@@ -512,6 +512,20 @@ fn svg_group_rasterization_threshold_is_bounded_by_document_depth() {
|
||||
assert_eq!(s.prefs().file_handling.rasterize_svg_groups_deeper_than, 0, "out-of-range preferences leave the valid value unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tablet_input_pref_defaults_to_windows_ink() {
|
||||
let mut s = session();
|
||||
assert_eq!(s.prefs().tools.tablet_input, TabletInput::WindowsInk);
|
||||
assert_eq!(s.execute("prefs.get", json!({"path": "tools.tabletInput"})).unwrap(), json!("windowsInk"));
|
||||
assert_eq!(choices("tools.tabletInput"), Some(TabletInput::NAMES));
|
||||
s.execute("prefs.set", json!({"path": "tools.tabletInput", "value": "winTab"})).unwrap();
|
||||
assert_eq!(s.prefs().tools.tablet_input, TabletInput::WinTab);
|
||||
for bad in [json!("ink"), json!(1), json!(true), json!(null)] {
|
||||
assert!(s.execute("prefs.set", json!({"path": "tools.tabletInput", "value": bad})).is_err());
|
||||
}
|
||||
assert_eq!(s.prefs().tools.tablet_input, TabletInput::WinTab, "rejected values change nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_click_with_painting_tools_pref() {
|
||||
let mut s = session();
|
||||
@@ -1025,6 +1039,25 @@ fn a_wrongly_typed_value_resets_only_that_field() {
|
||||
assert_eq!(invalid[1].keys, ["shortcuts", "file.open"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_removed_enable_animations_preference_still_loads_and_is_unknown() {
|
||||
// #9479: Interface › Enable animations is gone (Photoshop has no such setting). Files saved
|
||||
// with it still load whole, without a reported bad value, and the key isn't written back.
|
||||
let mut s = Session::new();
|
||||
let invalid =
|
||||
s.load_prefs_json(r#"{"version": 2, "interface": {"enableAnimations": false, "showTooltips": false}, "performance": {"historyStates": 20}}"#).unwrap();
|
||||
assert!(invalid.is_empty(), "{invalid:?}");
|
||||
assert!(!s.prefs().interface.show_tooltips, "its neighbours load");
|
||||
assert_eq!(s.prefs().performance.history_states, 20);
|
||||
assert!(!s.prefs_to_json().contains("enableAnimations"));
|
||||
for value in [json!(true), json!(false), json!("nope")] {
|
||||
let e = s.execute("prefs.set", json!({"values": {"interface.enableAnimations": value}})).unwrap_err();
|
||||
assert!(e.to_string().contains("unknown preference"), "{e}");
|
||||
assert!(s.execute("prefs.set", json!({"path": "interface.enableAnimations", "value": value})).is_err());
|
||||
}
|
||||
assert!(s.execute("prefs.get", json!({"path": "interface.enableAnimations"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrongly_typed_section_or_colour_setting_resets_only_that_part() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -2,8 +2,8 @@ use super::shortcuts::normalize_shortcut;
|
||||
use super::{
|
||||
AppearanceMode, Ask, CanvasBorder, CanvasColor, CheckerColors, CheckerSize, ColorPicker, DarkTheme, ExportLocation, ExportMetadata, FontPreview,
|
||||
GpuBackend, Interpolation, LightTheme, LineStyle, LinuxDisplayServer, LogDestination, LogDetail, OtherCursor, PaintingCursor, PlaybackPerformance,
|
||||
PointSize, PressureCurve, QuickExportFormat, RawColorSpace, RawDemosaic, RawDepth, RawSharpen, RenderingMode, RightClickPaint, TextEngine, Theme, TypeUnit,
|
||||
UiFontSize, UiScale, Unit, Value,
|
||||
PointSize, PressureCurve, QuickExportFormat, RawColorSpace, RawDemosaic, RawDepth, RawSharpen, RenderingMode, RightClickPaint, TabletInput, TextEngine,
|
||||
Theme, TypeUnit, UiFontSize, UiScale, Unit, Value,
|
||||
};
|
||||
|
||||
/// Preferences dialog sections in Photoshop's order: (id, title).
|
||||
@@ -88,6 +88,7 @@ pub fn choices(path: &str) -> Option<&'static [&'static str]> {
|
||||
"cursors.painting" => PaintingCursor::NAMES,
|
||||
"cursors.other" => OtherCursor::NAMES,
|
||||
"tools.rightClickWithPaintingTools" => RightClickPaint::NAMES,
|
||||
"tools.tabletInput" => TabletInput::NAMES,
|
||||
"transparencyAndGamut.gridSize" => CheckerSize::NAMES,
|
||||
"transparencyAndGamut.gridColors" => CheckerColors::NAMES,
|
||||
"unitsAndRulers.rulers" | "guidesGridAndSlices.gridUnit" => Unit::NAMES,
|
||||
|
||||
@@ -72,6 +72,7 @@ pub const SHELL_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
|
||||
("window.togglePanels", "Show/Hide All Panels", &[], Some("Tab")),
|
||||
("window.toggle.dock", "Show/Hide Panels", &[], Some("Shift+Tab")),
|
||||
("window.toggle.options", "Options", &["Window"], None),
|
||||
("window.toggle.contextualTaskBar", "Contextual Task Bar", &["Window"], None),
|
||||
// Photoshop's Ctrl+Tab and Ctrl+Shift+Tab, on macOS too (⌘Tab belongs to the system, #2340).
|
||||
("window.nextDocument", "Next Document", &[], Some("Ctrl+Tab")),
|
||||
("window.previousDocument", "Previous Document", &[], Some("Ctrl+Shift+Tab")),
|
||||
|
||||
@@ -129,3 +129,45 @@ fn an_svg_placed_as_a_job_is_as_sharp_as_the_inline_place() {
|
||||
let inline_doc = inline.active().unwrap().doc.clone();
|
||||
assert_eq!(surf.read_region(region), inline_doc.layers.last().unwrap().surface().unwrap().read_region(region), "same pixels as the inline place");
|
||||
}
|
||||
|
||||
/// With no worker threads (the web build) an SVG place is stepped a poll at a time, and renders
|
||||
/// at its placement scale like the inline place does.
|
||||
#[test]
|
||||
fn an_svg_placed_in_steps_is_as_sharp_as_the_inline_place() {
|
||||
use photocraft_engine::jobs::{JobOutcome, Started};
|
||||
let params = json!({"scale": 1000});
|
||||
let new_doc = || {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 400, "height": 400, "background": "white"})).unwrap();
|
||||
s
|
||||
};
|
||||
let mut inline = new_doc();
|
||||
let want = photocraft_engine::file_cmds::place_bytes(&mut inline, "logo.svg", SVG.as_bytes().to_vec(), None, ¶ms).unwrap();
|
||||
|
||||
let mut s = new_doc();
|
||||
s.set_cooperative_jobs(true);
|
||||
s.set_job_step_budget(std::time::Duration::ZERO);
|
||||
let Started::Job(id) = s.start_place_bytes("logo.svg", SVG.as_bytes().to_vec(), None, params).unwrap() else { panic!("expected a job") };
|
||||
let mut polls = 0;
|
||||
let event = loop {
|
||||
polls += 1;
|
||||
assert!(polls < 1000, "the place never ended");
|
||||
if let Some(e) = s.poll_jobs().into_iter().find(|e| e.id == id) {
|
||||
break e;
|
||||
}
|
||||
};
|
||||
assert!(polls > 1, "{polls}");
|
||||
let JobOutcome::Done(mut got) = event.outcome else { panic!("{:?}", event.outcome) };
|
||||
let mut want = want;
|
||||
assert!(got.as_object_mut().and_then(|o| o.remove("layer")).is_some() && want.as_object_mut().and_then(|o| o.remove("layer")).is_some());
|
||||
assert_eq!(got, want);
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let layer = doc.layers.last().unwrap();
|
||||
assert!(matches!(layer.content, LayerContent::Smart(_)));
|
||||
let surf = layer.surface().expect("rendered");
|
||||
assert!(alpha(surf, 200, 148) < 0.01 && alpha(surf, 200, 151) > 0.99, "a pixel-exact top edge");
|
||||
assert!(red(surf, 200, 192) < 0.02, "the thin line is a crisp band: {}", red(surf, 200, 192));
|
||||
let region = Rect::new(90, 140, 310, 260);
|
||||
let inline_doc = inline.active().unwrap().doc.clone();
|
||||
assert_eq!(surf.read_region(region), inline_doc.layers.last().unwrap().surface().unwrap().read_region(region), "same pixels as the inline place");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
//! How long each piece of a stepped Place takes (#10031): the numbers behind the web build's
|
||||
//! promise that a large file does not freeze the window.
|
||||
//!
|
||||
//! Not part of the default suite. Run it in release on one thread, as the web build has:
|
||||
//!
|
||||
//! ```sh
|
||||
//! RAYON_NUM_THREADS=1 cargo test --release -p photocraft-engine --test place_steps_measure -- --ignored --nocapture
|
||||
//! ```
|
||||
//!
|
||||
//! A synthetic 4096×4096 RGBA PNG is placed into a 3600×4200 document three ways: inline as one
|
||||
//! call (the cost without steps), in steps of one unit each (the cost of every unit of work, so the
|
||||
//! ones that cannot be cut up show), and in steps of the 8 ms a frame gives it (the longest frame
|
||||
//! a user would see).
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType};
|
||||
use photocraft_engine::jobs::{JobOutcome, Started};
|
||||
use photocraft_engine::{Session, file_cmds};
|
||||
use serde_json::json;
|
||||
|
||||
const SIZE: u32 = 4096;
|
||||
|
||||
/// A 4096×4096 RGBA PNG of smooth colour and four bits of noise a channel, which makes a file of
|
||||
/// a few tens of MB as a photo does (no personal photo).
|
||||
fn synthetic_png() -> Vec<u8> {
|
||||
let mut data = Vec::with_capacity(SIZE as usize * SIZE as usize * 4);
|
||||
let mut r = 0x9E37_79B9u32;
|
||||
let mut noise = || {
|
||||
r = r.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||
(r >> 28) as u8
|
||||
};
|
||||
for y in 0..SIZE {
|
||||
for x in 0..SIZE {
|
||||
data.extend_from_slice(&[((x / 24) as u8) << 4 | noise(), ((y / 24) as u8) << 4 | noise(), (((x + y) / 48) as u8) << 4 | noise(), 0xF0 | noise()]);
|
||||
}
|
||||
}
|
||||
let img = Image::from_raw(SIZE, SIZE, ChannelLayout::Rgba, SampleType::U8, data).unwrap();
|
||||
photocraft_codecs::encode(&img, Format::Png, &EncodeOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
fn document() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 3600, "height": 4200})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// A place's result without its layer id, which counts up across sessions.
|
||||
fn strip_layer(v: &serde_json::Value) -> serde_json::Value {
|
||||
let mut v = v.clone();
|
||||
v.as_object_mut().map(|o| o.remove("layer"));
|
||||
v
|
||||
}
|
||||
|
||||
fn ms(d: Duration) -> f64 {
|
||||
d.as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// Polls a started place to the end, timing every poll; returns (stage label, time) per poll. The
|
||||
/// label is the status the poll left (the message is set as a unit starts, so a poll that ends in
|
||||
/// a new one began a stage's last unit).
|
||||
fn timed_polls(s: &mut Session, id: photocraft_engine::jobs::JobId) -> (Vec<(String, String, Duration)>, serde_json::Value) {
|
||||
let mut polls = Vec::new();
|
||||
loop {
|
||||
let before = s.job(id).map(|j| j.message).unwrap_or_default();
|
||||
let t = Instant::now();
|
||||
let events = s.poll_jobs();
|
||||
let took = t.elapsed();
|
||||
let after = s.job(id).map_or_else(|| "finish and apply".to_string(), |j| j.message);
|
||||
polls.push((before, after, took));
|
||||
if let Some(e) = events.into_iter().find(|e| e.id == id) {
|
||||
let JobOutcome::Done(result) = e.outcome else { panic!("{:?}", e.outcome) };
|
||||
return (polls, result);
|
||||
}
|
||||
assert!(polls.len() < 1_000_000);
|
||||
}
|
||||
}
|
||||
|
||||
fn stage_of(before: &str, after: &str) -> &'static str {
|
||||
match (before, after) {
|
||||
("", "") => "open the PNG (header, buffer)",
|
||||
("" | "Decoding", "Decoding") => "decode rows",
|
||||
("Decoding", "Flattening") => "image to document (one unit)",
|
||||
("Flattening", "Flattening") => "flatten a band",
|
||||
("Flattening", "Resizing") => "resize: plan the first pass",
|
||||
(_, "Resizing") => "resize: bands and passes",
|
||||
(_, "finish and apply") => "translate, layer and apply (one unit)",
|
||||
_ => "other",
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "a measurement, run by hand (see the module docs)"]
|
||||
fn place_steps_timings() {
|
||||
let t = Instant::now();
|
||||
let png = synthetic_png();
|
||||
println!("synthetic {SIZE}x{SIZE} RGBA PNG: {:.1} MB, made in {:.0} ms", png.len() as f64 / 1e6, ms(t.elapsed()));
|
||||
println!("rayon threads: {}", rayon::current_num_threads());
|
||||
|
||||
// Inline, as one call: no steps. The first run warms the allocator; the second is the time.
|
||||
let mut want = serde_json::Value::Null;
|
||||
let mut inline_ms = 0.0;
|
||||
for run in 1..=2 {
|
||||
let mut inline = document();
|
||||
let t = Instant::now();
|
||||
want = file_cmds::place_bytes(&mut inline, "big.png", png.clone(), None, &json!({})).unwrap();
|
||||
inline_ms = ms(t.elapsed());
|
||||
println!("\ninline place {run} (one call, as a desktop worker does it): {inline_ms:.0} ms");
|
||||
}
|
||||
|
||||
// Cooperative, one unit per poll: the time of every unit of work.
|
||||
let mut s = document();
|
||||
s.set_cooperative_jobs(true);
|
||||
s.set_job_step_budget(Duration::ZERO);
|
||||
let t = Instant::now();
|
||||
let Started::Job(id) = s.start_place_bytes("big.png", png.clone(), None, json!({})).unwrap() else { panic!("expected a job") };
|
||||
let (polls, got) = timed_polls(&mut s, id);
|
||||
let total = ms(t.elapsed());
|
||||
assert_eq!(strip_layer(&got), strip_layer(&want), "the stepped place is the inline place");
|
||||
println!("\nstepped, one unit per poll: {} units, {total:.0} ms in all", polls.len());
|
||||
println!("{:<42} {:>7} {:>10} {:>10}", "stage", "units", "total ms", "longest ms");
|
||||
let mut stages: Vec<&str> = Vec::new();
|
||||
for (b, a, _) in &polls {
|
||||
let st = stage_of(b, a);
|
||||
if !stages.contains(&st) {
|
||||
stages.push(st);
|
||||
}
|
||||
}
|
||||
for st in stages {
|
||||
let times: Vec<f64> = polls.iter().filter(|(b, a, _)| stage_of(b, a) == st).map(|(_, _, d)| ms(*d)).collect();
|
||||
println!("{st:<42} {:>7} {:>10.1} {:>10.1}", times.len(), times.iter().sum::<f64>(), times.iter().copied().fold(0.0, f64::max));
|
||||
}
|
||||
let longest = polls.iter().map(|(_, _, d)| ms(*d)).fold(0.0, f64::max);
|
||||
println!("longest single unit: {longest:.1} ms");
|
||||
|
||||
// Cooperative with the frame budget: the frames a user would see.
|
||||
let mut s = document();
|
||||
s.set_cooperative_jobs(true);
|
||||
let t = Instant::now();
|
||||
let Started::Job(id) = s.start_place_bytes("big.png", png, None, json!({})).unwrap() else { panic!("expected a job") };
|
||||
let (polls, _) = timed_polls(&mut s, id);
|
||||
let total = ms(t.elapsed());
|
||||
let mut times: Vec<f64> = polls.iter().map(|(_, _, d)| ms(*d)).collect();
|
||||
times.sort_by(f64::total_cmp);
|
||||
println!(
|
||||
"\nstepped, 8 ms a poll: {} polls, {total:.0} ms in all ({:+.0}% on inline); median poll {:.1} ms, 95th percentile {:.1} ms, longest {:.1} ms",
|
||||
times.len(),
|
||||
(total / inline_ms - 1.0) * 100.0,
|
||||
times[times.len() / 2],
|
||||
times[times.len() * 95 / 100],
|
||||
times[times.len() - 1]
|
||||
);
|
||||
let slow: Vec<_> = polls.iter().filter(|(_, _, d)| ms(*d) > 16.0).map(|(b, a, d)| format!("{} ({:.0} ms)", stage_of(b, a), ms(*d))).collect();
|
||||
println!("polls over 16 ms: {}", if slow.is_empty() { "none".to_string() } else { slow.join(", ") });
|
||||
}
|
||||
+313
-68
@@ -6,7 +6,7 @@ use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType
|
||||
use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_doc::{AlphaChannel, Document, Layer, LayerContent};
|
||||
use photocraft_geom::{Rect, Size, TILE_SIZE};
|
||||
use photocraft_raster::{AllocationError, Interrupt, RowWriteError, Surface};
|
||||
use photocraft_raster::{AllocationError, Interrupt, PruneCursor, RowWriteError, Surface};
|
||||
|
||||
use crate::renderer::{BandRenderer, RenderError};
|
||||
use crate::{ExportOptions, ExportResult, ImportResult, IoError, TgaBits, XmpEmbed};
|
||||
@@ -126,6 +126,140 @@ fn import_flat_impl_with_options(
|
||||
(image_to_document_with(name, &img, ctl)?, Some(img))
|
||||
}
|
||||
};
|
||||
apply_flat_format(&mut r, bytes, format, img.as_ref())?;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// An image becoming a document's surface a bounded band of rows and a bounded batch of empty
|
||||
/// tiles at a time, so a caller that must not block (the web build has no threads) can step it.
|
||||
/// [`FlatBuilder::finish`] runs whatever is left, so it also gives the one-shot result.
|
||||
pub(crate) struct FlatBuilder {
|
||||
name: String,
|
||||
img: Image,
|
||||
mode: ColorMode,
|
||||
depth: SampleType,
|
||||
convert: RowConverter,
|
||||
surface: Surface,
|
||||
warnings: Vec<String>,
|
||||
/// Rows copied into `surface` so far.
|
||||
rows: u32,
|
||||
/// Rows per [`FlatBuilder::copy_step`].
|
||||
band: u32,
|
||||
/// Whether the tiles are scanned for empty ones: only a source with alpha has any.
|
||||
scans: bool,
|
||||
prune: Option<PruneCursor>,
|
||||
}
|
||||
|
||||
/// Bytes a copy step converts at most; a step is a band of whole rows, so it is never split.
|
||||
const COPY_BAND_BYTES: usize = 4 << 20;
|
||||
/// Rows a copy step writes at most (a narrow image would otherwise copy the whole one in one step).
|
||||
const COPY_BAND_ROWS: u32 = 256;
|
||||
/// Tiles a prune step visits at most.
|
||||
const PRUNE_BATCH: usize = 256;
|
||||
|
||||
impl FlatBuilder {
|
||||
/// Sets up the surface `img` becomes, without copying a pixel yet. Refuses an image whose
|
||||
/// tiles the machine can't hold beside it, as [`image_to_document`] does.
|
||||
pub(crate) fn new(name: &str, img: Image) -> Result<Self, IoError> {
|
||||
let (w, h) = img.dimensions();
|
||||
let (mode, target_layout, depth, csample) = flat_target(img.layout(), img.sample_type());
|
||||
check_layer_fits(w, h, target_layout, csample, crate::memory::available())?;
|
||||
let convert = RowConverter::new((img.layout(), img.sample_type()), (target_layout, csample));
|
||||
let row = (w as usize).saturating_mul(convert.src_px).max(1);
|
||||
let band = (COPY_BAND_BYTES / row).clamp(1, COPY_BAND_ROWS as usize) as u32;
|
||||
Ok(Self {
|
||||
name: name.to_string(),
|
||||
warnings: flat_warnings(&img),
|
||||
surface: Surface::new(surface_format(target_layout, csample)),
|
||||
scans: img.layout().has_alpha(),
|
||||
convert,
|
||||
mode,
|
||||
depth,
|
||||
rows: 0,
|
||||
band: band.min(h.max(1)),
|
||||
prune: None,
|
||||
img,
|
||||
})
|
||||
}
|
||||
|
||||
/// True once every row is in the surface.
|
||||
pub(crate) fn copy_done(&self) -> bool {
|
||||
self.rows >= self.img.dimensions().1
|
||||
}
|
||||
|
||||
/// Copies one bounded band of rows into the tiles, converted as [`image_to_document`] does.
|
||||
pub(crate) fn copy_step(&mut self) -> Result<(), IoError> {
|
||||
if self.copy_done() {
|
||||
return Ok(());
|
||||
}
|
||||
let (w, h) = self.img.dimensions();
|
||||
let y1 = self.rows.saturating_add(self.band).min(h);
|
||||
let row = (w as usize).checked_mul(self.convert.src_px).filter(|&b| b > 0).ok_or_else(|| IoError::Unsupported("image too large".into()))?;
|
||||
let at = (self.rows as usize).saturating_mul(row);
|
||||
let end = (y1 as usize).saturating_mul(row);
|
||||
let data = self.img.data().get(at..end).ok_or_else(|| IoError::Unsupported("the decoded image is shorter than its size".into()))?;
|
||||
let to_i32 = |v: u32| i32::try_from(v).map_err(|_| IoError::Unsupported("image too large".into()));
|
||||
let rect = Rect::new(0, to_i32(self.rows)?, to_i32(w)?, to_i32(y1)?);
|
||||
let convert = &self.convert;
|
||||
let failed = std::sync::atomic::AtomicBool::new(false);
|
||||
self.surface
|
||||
.try_write_rows_with_interrupt(rect, &Interrupt::NONE, |y, x0, dst| {
|
||||
if !convert.fill(data, w as usize, y - rect.y0, x0, dst) {
|
||||
failed.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
})
|
||||
.map_err(|e| match e {
|
||||
RowWriteError::Cancelled(_) => IoError::Cancelled,
|
||||
RowWriteError::Allocation(ae) => alloc_error(ae, w, h),
|
||||
})?;
|
||||
if failed.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
return Err(IoError::Unsupported("the decoded image does not match its size".into()));
|
||||
}
|
||||
self.rows = y1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// True once every tile has been through the prune scan (at once for a source without alpha).
|
||||
pub(crate) fn prune_done(&self) -> bool {
|
||||
!self.scans || self.prune.as_ref().is_some_and(|c| c.is_done())
|
||||
}
|
||||
|
||||
/// Drops one bounded batch of tiles that are entirely the default pixel; true when done.
|
||||
pub(crate) fn prune_step(&mut self) -> bool {
|
||||
if !self.scans {
|
||||
return true;
|
||||
}
|
||||
if self.prune.is_none() {
|
||||
self.prune = Some(self.surface.prune_cursor());
|
||||
}
|
||||
let Some(cursor) = self.prune.as_mut() else { return true };
|
||||
self.surface.prune_batch(cursor, PRUNE_BATCH)
|
||||
}
|
||||
|
||||
/// The document, after copying and pruning whatever is left: the one-shot result and the last
|
||||
/// step of a stepped one.
|
||||
pub(crate) fn finish(mut self, bytes: &[u8], format: Option<Format>) -> Result<ImportResult, IoError> {
|
||||
let copied = self.copy_done();
|
||||
while !self.copy_done() {
|
||||
self.copy_step()?;
|
||||
}
|
||||
if !copied {
|
||||
// Any scan before the last rows missed the tiles they added: scan them all again.
|
||||
self.prune = None;
|
||||
}
|
||||
while !self.prune_step() {}
|
||||
let Self { name, img, mode, depth, surface, warnings, .. } = self;
|
||||
let (w, h) = img.dimensions();
|
||||
let mut r = flat_document(&name, (w, h, img.layout(), mode, depth), surface, img.icc.clone(), &img.meta, warnings, Some(&img))?;
|
||||
apply_flat_format(&mut r, bytes, format, Some(&img))?;
|
||||
Ok(r)
|
||||
}
|
||||
}
|
||||
|
||||
/// What every flat format does to the document of its pixels: the palette mode, the save
|
||||
/// settings, a Targa's alpha channel and the profile an untagged image needs. `img` is the
|
||||
/// decoded image, when the document was built from one (a streamed PNG has none).
|
||||
pub(crate) fn apply_flat_format(r: &mut ImportResult, bytes: &[u8], format: Option<Format>, img: Option<&Image>) -> Result<(), IoError> {
|
||||
// A palette BMP, PNG or GIF opens in Indexed Color mode with its colour table, as in
|
||||
// Photoshop (#3802, #4804, #7886). A GIF is always palette-based: the first frame's table.
|
||||
let palette = match format {
|
||||
@@ -141,7 +275,7 @@ fn import_flat_impl_with_options(
|
||||
r.document.color_table = Some(photocraft_doc::ColorTable { colors, transparent });
|
||||
}
|
||||
r.document.file_encoding = file_encoding_as(format, bytes);
|
||||
if format == Some(Format::Tga) && img.as_ref().is_some_and(|i| i.layout() == ChannelLayout::Rgba) {
|
||||
if format == Some(Format::Tga) && img.is_some_and(|i| i.layout() == ChannelLayout::Rgba) {
|
||||
tga_alpha_to_channel(&mut r.document)?;
|
||||
}
|
||||
// OpenEXR and Radiance HDR hold linear, scene-referred values (Rec. 709 primaries unless
|
||||
@@ -157,15 +291,15 @@ fn import_flat_impl_with_options(
|
||||
}
|
||||
if d.icc_profile.is_none() && d.mode == ColorMode::Rgb {
|
||||
// Only an image the whole-image path decoded can carry a CICP description (a PNG never does).
|
||||
d.icc_profile = img.as_ref().and_then(cicp_profile);
|
||||
d.icc_profile = img.and_then(cicp_profile);
|
||||
if d.icc_profile.is_none()
|
||||
&& let Some((profile, warning)) = img.as_ref().and_then(hdr_fallback)
|
||||
&& let Some((profile, warning)) = img.and_then(hdr_fallback)
|
||||
{
|
||||
d.icc_profile = Some(profile);
|
||||
r.warnings.push(warning);
|
||||
}
|
||||
}
|
||||
Ok(r)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A PQ or HLG image, which the decoder turned into linear light, on primaries
|
||||
@@ -650,22 +784,33 @@ fn image_to_document_with(name: &str, img: &Image, ctl: &Interrupt) -> Result<Im
|
||||
/// [`image_to_document_with`], with the memory the machine can still use given (see
|
||||
/// [`crate::memory::available`]): `None` when it isn't known.
|
||||
fn image_to_document_with_memory(name: &str, img: &Image, ctl: &Interrupt, available: Option<u64>) -> Result<ImportResult, IoError> {
|
||||
// What the decoder noticed (frames or pages left out, data ending early) comes first.
|
||||
let mut warnings: Vec<String> = img.warnings.iter().map(ToString::to_string).collect();
|
||||
let warnings = flat_warnings(img);
|
||||
let (mode, target_layout, depth, csample) = flat_target(img.layout(), img.sample_type());
|
||||
if img.sample_type() == CSample::F16 {
|
||||
warnings.push("16-bit float samples are stored as 32-bit float".to_string());
|
||||
}
|
||||
let (w, h) = img.dimensions();
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
// The decoded pixels are already here: check the tiles built beside them before they exist.
|
||||
check_layer_fits(w, h, target_layout, csample, available)?;
|
||||
let s = image_surface_with(img, target_layout, csample, ctl)?;
|
||||
let mut s = image_surface_with(img, target_layout, csample, ctl)?;
|
||||
// Tiles that are entirely the default pixel (zero, so transparent) can only come from a
|
||||
// source with alpha: an opaque one writes the maximum into every alpha sample.
|
||||
if img.layout().has_alpha() {
|
||||
s.prune();
|
||||
}
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
ctl.progress(0.95);
|
||||
flat_document(name, (w, h, img.layout(), mode, depth), s, img.icc.clone(), &img.meta, warnings, Some(img))
|
||||
}
|
||||
|
||||
/// What the decoder noticed (frames or pages left out, data ending early) and the conversion
|
||||
/// will add, for the document of `img`.
|
||||
fn flat_warnings(img: &Image) -> Vec<String> {
|
||||
let mut warnings: Vec<String> = img.warnings.iter().map(ToString::to_string).collect();
|
||||
if img.sample_type() == CSample::F16 {
|
||||
warnings.push("16-bit float samples are stored as 32-bit float".to_string());
|
||||
}
|
||||
warnings
|
||||
}
|
||||
|
||||
/// The document colour mode, the layout and sample type of its surface, and its depth, for a
|
||||
/// decoded image of `layout` and `sample`.
|
||||
fn flat_target(layout: ChannelLayout, sample: CSample) -> (ColorMode, ChannelLayout, SampleType, CSample) {
|
||||
@@ -689,7 +834,7 @@ fn flat_target(layout: ChannelLayout, sample: CSample) -> (ColorMode, ChannelLay
|
||||
fn flat_document(
|
||||
name: &str,
|
||||
shape: (u32, u32, ChannelLayout, ColorMode, SampleType),
|
||||
mut s: Surface,
|
||||
s: Surface,
|
||||
icc: Option<Vec<u8>>,
|
||||
meta: &codecs::Metadata,
|
||||
mut warnings: Vec<String>,
|
||||
@@ -697,11 +842,6 @@ fn flat_document(
|
||||
) -> Result<ImportResult, IoError> {
|
||||
let (w, h, layout, mode, depth) = shape;
|
||||
let mut doc = Document::new(name, Size::new(w, h), mode, depth);
|
||||
// Tiles that are entirely the default pixel (zero, so transparent) can only come from a
|
||||
// source with alpha: an opaque one writes the maximum into every alpha sample.
|
||||
if layout.has_alpha() {
|
||||
s.prune();
|
||||
}
|
||||
// As in Photoshop: an opaque image opens as the locked Background layer, one with
|
||||
// transparency (an alpha channel, or a tRNS chunk the decoder expands to one) as a normal
|
||||
// layer named "Layer 0", since a Background can't hold transparency.
|
||||
@@ -743,58 +883,48 @@ fn import_png_streamed(name: &str, bytes: &[u8], opts: &crate::ImportOptions, ct
|
||||
import_png_streamed_with(name, bytes, opts, ctl, min_bytes, crate::memory::available)
|
||||
}
|
||||
|
||||
/// [`import_png_streamed`], with the memory the machine can still use given (see
|
||||
/// [`crate::memory::available`]): `None` when it isn't known.
|
||||
fn import_png_streamed_with(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
opts: &crate::ImportOptions,
|
||||
ctl: &Interrupt,
|
||||
min_bytes: u64,
|
||||
available: impl FnOnce() -> Option<u64>,
|
||||
) -> Result<Option<ImportResult>, IoError> {
|
||||
struct Stream {
|
||||
surface: Surface,
|
||||
header: codecs::PngHeader,
|
||||
convert: RowConverter,
|
||||
}
|
||||
// Rows are worked off 0.02..0.55 so a fallback to the whole-image path, which reports 0.6
|
||||
// after its decode, never takes progress backwards.
|
||||
let state = std::cell::RefCell::new(None::<Stream>);
|
||||
let mut available = Some(available);
|
||||
let busy = || IoError::Unsupported("the PNG reader re-entered itself".into());
|
||||
let mut begin = |header: &codecs::PngHeader| -> Result<bool, IoError> {
|
||||
// Decoded size, from the header; a size that overflows is certainly large enough.
|
||||
let bytes = u64::from(header.width)
|
||||
.checked_mul(u64::from(header.height))
|
||||
.and_then(|px| px.checked_mul((header.layout.channels() * header.sample.bytes()) as u64));
|
||||
if bytes.is_some_and(|b| b < min_bytes) {
|
||||
return Ok(false);
|
||||
}
|
||||
// A cancelled import is reported as such, not as the memory it would have needed.
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
/// A PNG's rows becoming the tiles of its layer as they are decoded: the surface, and what turns a
|
||||
/// decoded row into its pixels. Shared by [`import_png_streamed`] (all at once) and the stepped
|
||||
/// import ([`crate::PngImport`], a bounded piece at a time), which give the same document.
|
||||
pub(crate) struct PngStream {
|
||||
surface: Surface,
|
||||
header: codecs::PngHeader,
|
||||
convert: RowConverter,
|
||||
}
|
||||
|
||||
impl PngStream {
|
||||
/// Sets up the surface for rows of `header`, after checking the layer's tiles and a group of
|
||||
/// rows as decoded and as converted against `available` (the memory the machine can still use,
|
||||
/// when known): Linux overcommits, so the tiles would be allocated even when they can't be
|
||||
/// backed, and writing them would have the process killed.
|
||||
pub(crate) fn new(header: &codecs::PngHeader, available: Option<u64>) -> Result<Self, IoError> {
|
||||
let (_, target_layout, _, csample) = flat_target(header.layout, header.sample);
|
||||
// The layer's tiles, plus one group of rows as decoded and as converted into them.
|
||||
// Linux overcommits, so the tiles would be allocated even when they can't be backed, and
|
||||
// writing them would have the process killed: refuse first, as `tiff_to_document` does.
|
||||
let bpp = surface_format(target_layout, csample).bytes_per_pixel() as u64;
|
||||
let src_px = (header.layout.channels() * header.sample.bytes()) as u64;
|
||||
let group = u64::from(header.width).saturating_mul(u64::from(header.height.min(TILE_SIZE as u32)));
|
||||
let needed = tile_bytes(header.width, header.height, bpp).saturating_add(group.saturating_mul(src_px)).saturating_add(group.saturating_mul(bpp));
|
||||
crate::memory::check_fits(header.width, header.height, needed, available.take().and_then(|f| f()))?;
|
||||
*state.try_borrow_mut().map_err(|_| busy())? = Some(Stream {
|
||||
crate::memory::check_fits(header.width, header.height, needed, available)?;
|
||||
Ok(Self {
|
||||
surface: Surface::new(surface_format(target_layout, csample)),
|
||||
header: *header,
|
||||
convert: RowConverter::new((header.layout, header.sample), (target_layout, csample)),
|
||||
});
|
||||
ctl.progress(0.02);
|
||||
Ok(true)
|
||||
};
|
||||
let mut rows = |y0: u32, data: &[u8]| -> Result<(), IoError> {
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
let mut guard = state.try_borrow_mut().map_err(|_| busy())?;
|
||||
let Some(Stream { surface, header, convert }) = guard.as_mut() else { return Err(busy()) };
|
||||
let (w, h) = (header.width, header.height);
|
||||
})
|
||||
}
|
||||
|
||||
/// [`PngStream::new`] for a stepped import, which streams every PNG whose rows come in order
|
||||
/// and not only the big ones: a layer under [`STREAM_MIN_BYTES`] of tiles is not checked
|
||||
/// against free memory, as the whole-image path leaves it unchecked ([`check_layer_fits`]).
|
||||
pub(crate) fn for_steps(header: &codecs::PngHeader) -> Result<Self, IoError> {
|
||||
let (_, target_layout, _, csample) = flat_target(header.layout, header.sample);
|
||||
let tiles = tile_bytes(header.width, header.height, surface_format(target_layout, csample).bytes_per_pixel() as u64);
|
||||
Self::new(header, if tiles < STREAM_MIN_BYTES { None } else { crate::memory::available() })
|
||||
}
|
||||
|
||||
/// Converts the whole rows `y0..` in `data` into the tiles, checking `ctl` as it goes.
|
||||
pub(crate) fn write_rows(&mut self, y0: u32, data: &[u8], ctl: &Interrupt) -> Result<(), IoError> {
|
||||
let (w, h) = (self.header.width, self.header.height);
|
||||
let convert = &self.convert;
|
||||
let row_bytes = (w as usize).checked_mul(convert.src_px).filter(|&b| b > 0).ok_or_else(|| IoError::Unsupported("image too large".into()))?;
|
||||
let n = u32::try_from(data.len() / row_bytes).unwrap_or(0);
|
||||
if n == 0 || !data.len().is_multiple_of(row_bytes) {
|
||||
@@ -803,7 +933,7 @@ fn import_png_streamed_with(
|
||||
let to_i32 = |v: u32| i32::try_from(v).map_err(|_| IoError::Unsupported("image too large".into()));
|
||||
let rect = Rect::new(0, to_i32(y0)?, to_i32(w)?, to_i32(y0.saturating_add(n))?);
|
||||
let failed = std::sync::atomic::AtomicBool::new(false);
|
||||
surface
|
||||
self.surface
|
||||
.try_write_rows_with_interrupt(rect, ctl, |y, x0, dst| {
|
||||
if !convert.fill(data, w as usize, y - rect.y0, x0, dst) {
|
||||
failed.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
@@ -816,6 +946,76 @@ fn import_png_streamed_with(
|
||||
if failed.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
return Err(IoError::Unsupported("the decoded image does not match its size".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the layer is scanned for tiles of only the default pixel: only a source with alpha
|
||||
/// has any.
|
||||
pub(crate) fn scans(&self) -> bool {
|
||||
self.header.layout.has_alpha()
|
||||
}
|
||||
|
||||
/// Drops the tiles that hold only the default pixel, all at once.
|
||||
pub(crate) fn prune(&mut self) {
|
||||
if self.scans() {
|
||||
self.surface.prune();
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops one bounded batch of those tiles from where `cursor` left off; true when done.
|
||||
pub(crate) fn prune_step(&mut self, cursor: &mut photocraft_raster::PruneCursor) -> bool {
|
||||
!self.scans() || self.surface.prune_batch(cursor, PRUNE_BATCH)
|
||||
}
|
||||
|
||||
/// A cursor for [`PngStream::prune_step`].
|
||||
pub(crate) fn prune_cursor(&self) -> photocraft_raster::PruneCursor {
|
||||
self.surface.prune_cursor()
|
||||
}
|
||||
|
||||
/// The document of the layer, with the profile and metadata the file ended with.
|
||||
pub(crate) fn into_document(self, name: &str, extras: codecs::PngExtras) -> Result<ImportResult, IoError> {
|
||||
let Self { surface, header, .. } = self;
|
||||
let (mode, _, depth, _) = flat_target(header.layout, header.sample);
|
||||
let warnings = extras.warnings.iter().map(ToString::to_string).collect();
|
||||
flat_document(name, (header.width, header.height, header.layout, mode, depth), surface, extras.icc, &extras.meta, warnings, None)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`import_png_streamed`], with the memory the machine can still use given (see
|
||||
/// [`crate::memory::available`]): `None` when it isn't known.
|
||||
fn import_png_streamed_with(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
opts: &crate::ImportOptions,
|
||||
ctl: &Interrupt,
|
||||
min_bytes: u64,
|
||||
available: impl FnOnce() -> Option<u64>,
|
||||
) -> Result<Option<ImportResult>, IoError> {
|
||||
// Rows are worked off 0.02..0.55 so a fallback to the whole-image path, which reports 0.6
|
||||
// after its decode, never takes progress backwards.
|
||||
let state = std::cell::RefCell::new(None::<PngStream>);
|
||||
let mut available = Some(available);
|
||||
let busy = || IoError::Unsupported("the PNG reader re-entered itself".into());
|
||||
let mut begin = |header: &codecs::PngHeader| -> Result<bool, IoError> {
|
||||
// Decoded size, from the header; a size that overflows is certainly large enough.
|
||||
let bytes = u64::from(header.width)
|
||||
.checked_mul(u64::from(header.height))
|
||||
.and_then(|px| px.checked_mul((header.layout.channels() * header.sample.bytes()) as u64));
|
||||
if bytes.is_some_and(|b| b < min_bytes) {
|
||||
return Ok(false);
|
||||
}
|
||||
// A cancelled import is reported as such, not as the memory it would have needed.
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
*state.try_borrow_mut().map_err(|_| busy())? = Some(PngStream::new(header, available.take().and_then(|f| f()))?);
|
||||
ctl.progress(0.02);
|
||||
Ok(true)
|
||||
};
|
||||
let mut rows = |y0: u32, data: &[u8]| -> Result<(), IoError> {
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
let mut guard = state.try_borrow_mut().map_err(|_| busy())?;
|
||||
let Some(stream) = guard.as_mut() else { return Err(busy()) };
|
||||
stream.write_rows(y0, data, ctl)?;
|
||||
let (h, n) = (stream.header.height, u32::try_from(data.len() / (stream.header.width as usize * stream.convert.src_px).max(1)).unwrap_or(0));
|
||||
ctl.progress(0.02 + 0.53 * (y0 + n) as f32 / h.max(1) as f32);
|
||||
Ok(())
|
||||
};
|
||||
@@ -830,14 +1030,13 @@ fn import_png_streamed_with(
|
||||
return Ok(None);
|
||||
};
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
let Some(Stream { surface, header, .. }) = state.into_inner() else { return Ok(None) };
|
||||
let Some(mut stream) = state.into_inner() else { return Ok(None) };
|
||||
if extras.orientation != 1 {
|
||||
return Ok(None);
|
||||
}
|
||||
ctl.progress(0.95);
|
||||
let (mode, _, depth, _) = flat_target(header.layout, header.sample);
|
||||
let warnings = extras.warnings.iter().map(ToString::to_string).collect();
|
||||
flat_document(name, (header.width, header.height, header.layout, mode, depth), surface, extras.icc, &extras.meta, warnings, None).map(Some)
|
||||
stream.prune();
|
||||
stream.into_document(name, extras).map(Some)
|
||||
}
|
||||
|
||||
/// The pixels of a decoded image as a surface of the target layout and sample type, converted
|
||||
@@ -2463,6 +2662,18 @@ mod streamed_png_tests {
|
||||
assert!(matches!(r, Err(IoError::Cancelled)), "{:?}", r.map(|_| ()));
|
||||
}
|
||||
|
||||
/// The stream a stepped import builds refuses a layer that won't fit with the error the
|
||||
/// one-shot streamed import gives, and leaves a small one unchecked, as the whole-image path does.
|
||||
#[test]
|
||||
fn a_stream_for_steps_keeps_the_memory_errors() {
|
||||
let big = codecs::PngHeader { width: 20_000, height: 20_000, layout: ChannelLayout::Rgba, sample: CSample::U8 };
|
||||
let e = PngStream::new(&big, Some(1 << 20)).err().expect("refused");
|
||||
assert!(matches!(&e, IoError::Unsupported(m) if m.contains("not enough memory to open this 20000 × 20000 px image")), "{e}");
|
||||
let small = codecs::PngHeader { width: 64, height: 64, layout: ChannelLayout::Rgba, sample: CSample::U8 };
|
||||
assert!(PngStream::for_steps(&small).is_ok(), "a small layer is not checked");
|
||||
assert!(PngStream::new(&small, Some(1 << 20)).is_err(), "though the check itself would refuse it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_large_documents_stream() {
|
||||
let doc = |w, h, depth| Document::new("size", Size::new(w, h), ColorMode::Rgb, depth);
|
||||
@@ -2498,14 +2709,14 @@ mod streamed_png_tests {
|
||||
|
||||
let lowered = crate::ImportOptions { psd_max_pixel_bytes: 99, ..Default::default() };
|
||||
match tiff_admission(100, 0, &lowered, &ctl) {
|
||||
Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (100, 99)),
|
||||
Err(IoError::PsdImportBudget { required, limit, .. }) => assert_eq!((required, limit), (100, 99)),
|
||||
other => panic!("expected the caller's limit to refuse, got {:?}", other.map(|_| ())),
|
||||
}
|
||||
assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(ample), "a refused nested import leaves the parent's allowance untouched");
|
||||
|
||||
let stale = crate::ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(99), ..Default::default() };
|
||||
match tiff_admission(100, 0, &stale, &ctl) {
|
||||
Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (100, 99)),
|
||||
Err(IoError::PsdImportBudget { required, limit, .. }) => assert_eq!((required, limit), (100, 99)),
|
||||
other => panic!("expected the approved estimate bound to refuse, got {:?}", other.map(|_| ())),
|
||||
}
|
||||
assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(ample), "a refused nested import leaves the parent's allowance untouched");
|
||||
@@ -2532,7 +2743,7 @@ mod streamed_png_tests {
|
||||
crate::ImportOptions { psd_high_memory_approved: true, psd_approved_estimate: Some(u64::MAX), ..Default::default() },
|
||||
] {
|
||||
match tiff_admission(u64::MAX, 0, &opts, &Interrupt::NONE) {
|
||||
Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (u64::MAX, u64::MAX)),
|
||||
Err(IoError::PsdImportBudget { required, limit, .. }) => assert_eq!((required, limit), (u64::MAX, u64::MAX)),
|
||||
other => panic!("expected a hard refusal for {opts:?}, got {:?}", other.map(|_| ())),
|
||||
}
|
||||
}
|
||||
@@ -2540,6 +2751,40 @@ mod streamed_png_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod build_tests {
|
||||
use super::*;
|
||||
|
||||
/// The stepped builder gives exactly what [`image_to_document`] gives, for every layout, over
|
||||
/// a surface of several tiles.
|
||||
#[test]
|
||||
fn a_stepped_build_equals_image_to_document() {
|
||||
for (layout, sample) in
|
||||
[(ChannelLayout::Gray, CSample::U8), (ChannelLayout::GrayA, CSample::U16), (ChannelLayout::Rgb, CSample::U8), (ChannelLayout::Rgba, CSample::U16)]
|
||||
{
|
||||
let len = 300 * 260 * layout.channels() * sample.bytes();
|
||||
let data: Vec<u8> = (0..len).map(|i| (i.wrapping_mul(2_654_435_761) >> 11) as u8).collect();
|
||||
let mut img = Image::from_raw(300, 260, layout, sample, data).unwrap();
|
||||
img.meta.dpi = Some((300.0, 300.0));
|
||||
img.meta.text.push(("Comment".into(), "kept".into()));
|
||||
let expected = image_to_document("a.png", &img).unwrap();
|
||||
let mut build = FlatBuilder::new("a.png", img).unwrap();
|
||||
while !build.copy_done() {
|
||||
build.copy_step().unwrap();
|
||||
}
|
||||
while !build.prune_step() {}
|
||||
let got = build.finish(&[], None).unwrap();
|
||||
let (mut a, mut b) = (expected.document, got.document);
|
||||
b.id = a.id;
|
||||
for (x, y) in a.layers.iter_mut().zip(&mut b.layers) {
|
||||
y.id = x.id;
|
||||
}
|
||||
assert!(a == b, "{layout:?} {sample:?}: the stepped build differs");
|
||||
assert_eq!(expected.warnings, got.warnings, "{layout:?} {sample:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod fused_tile_tests {
|
||||
use super::*;
|
||||
|
||||
+63
-19
@@ -52,6 +52,7 @@ pub mod exr_parts;
|
||||
mod flat;
|
||||
mod gradient_bake;
|
||||
pub mod guides_map;
|
||||
mod png_steps;
|
||||
pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient};
|
||||
mod duotone_map;
|
||||
mod kra;
|
||||
@@ -99,6 +100,7 @@ pub use flat::{
|
||||
export_png_streamed_with_renderer, export_preview_png_with_renderer, file_encoding, import_gif_frames, import_tiff_page, import_tiff_page_with_options,
|
||||
import_webp_frames, tga_alpha_channel_to_transparency, tga_default_bits,
|
||||
};
|
||||
pub use png_steps::PngImport;
|
||||
// Re-exported for the `flat_open_bench` example, which times the tile-building phase of a flat open.
|
||||
#[doc(hidden)]
|
||||
pub use flat::image_to_document;
|
||||
@@ -124,8 +126,12 @@ pub enum IoError {
|
||||
#[error("PSD: {0}")]
|
||||
Psd(#[from] PsdError),
|
||||
/// The conservative PSD pixel-storage and workspace estimate exceeded its allowance.
|
||||
#[error("PSD import needs an estimated {required} bytes of pixel memory; limit is {limit} bytes")]
|
||||
PsdImportBudget { required: u64, limit: u64 },
|
||||
///
|
||||
/// `free_memory` is the free memory measured when it set the limit (see
|
||||
/// [`memory::MemoryBudget::measured_free`]); `None` when a caller or attempt allowance, the
|
||||
/// platform cap or an unknown capacity set it.
|
||||
#[error("PSD import needs an estimated {required} bytes of pixel memory; limit is {limit} bytes{advice}", advice = crate::memory::low_memory_advice(.free_memory))]
|
||||
PsdImportBudget { required: u64, limit: u64, free_memory: Option<u64> },
|
||||
/// PSD pixel-storage estimate exceeds the automatic soft limit, but is within the hard limit.
|
||||
/// Explicit approval is required to proceed.
|
||||
#[error(
|
||||
@@ -900,53 +906,91 @@ pub fn import_file(name: &str, path: &std::path::Path, opts: &ImportOptions, ctl
|
||||
import_file_for_open_with(name, path, opts, ctl).map(|(result, _)| result)
|
||||
}
|
||||
|
||||
/// Dispatches format-specific importers and propagates a structured PSD damage
|
||||
/// flag alongside the ordinary best-effort import result.
|
||||
fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result<ImportResult, IoError> {
|
||||
/// The importer a file goes to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Route {
|
||||
Pcraft,
|
||||
Psd,
|
||||
Affinity,
|
||||
Ora,
|
||||
Kra,
|
||||
Xcf,
|
||||
GzippedXcf,
|
||||
Pdn,
|
||||
Raw,
|
||||
Svg,
|
||||
/// A `.psd`/`.psb`/`.psdt` with no raster signature.
|
||||
NamedPsd,
|
||||
/// A flat raster format, through the codecs.
|
||||
Flat,
|
||||
}
|
||||
|
||||
/// Which importer takes the file `name` holding `bytes`. The checks run in this order.
|
||||
pub(crate) fn route(name: &str, bytes: &[u8]) -> Route {
|
||||
// A declared native extension must reach its loader so malformed bundles retain format errors.
|
||||
if has_extension(name, photocraft_format::EXTENSION) || photocraft_format::is_pcraft(bytes) {
|
||||
let document = photocraft_format::load_from_bytes(bytes)?;
|
||||
return Ok(ImportResult { warnings: open_warnings(&document), document, source_read_only: false, preview_only: false });
|
||||
return Route::Pcraft;
|
||||
}
|
||||
// Magic first: an Affinity file renamed .psd is still Affinity (#5258 corpus
|
||||
// preview_never_saves_back_to_its_native_or_renamed_source).
|
||||
if is_psd(bytes) {
|
||||
return import_psd(name, ctl, damaged, opts, |want, recover| PsdFile::from_bytes_and_merged_preflight(bytes, want, recover));
|
||||
return Route::Psd;
|
||||
}
|
||||
if affinity::is_affinity(bytes) || affinity::has_extension(name) {
|
||||
return affinity::import(name, bytes);
|
||||
return Route::Affinity;
|
||||
}
|
||||
if ora::is_ora(bytes) || has_extension(name, "ora") {
|
||||
return ora::import(name, bytes, ctl);
|
||||
return Route::Ora;
|
||||
}
|
||||
// Krita files are ZIP containers. A recognized raster signature still wins over a
|
||||
// misleading .kra suffix (as with SVG imports).
|
||||
if kra::is_kra(bytes) || (kra::EXTENSIONS.iter().any(|e| has_extension(name, e)) && photocraft_codecs::detect(bytes).is_none()) {
|
||||
return kra::import(name, bytes, ctl);
|
||||
return Route::Kra;
|
||||
}
|
||||
// GIMP files are gzip or raw; as above, a recognized raster signature still wins over a
|
||||
// misleading .xcf suffix.
|
||||
if xcf::is_xcf(bytes) || (has_extension(name, "xcf") && photocraft_codecs::detect(bytes).is_none()) {
|
||||
return xcf::import(name, bytes, ctl);
|
||||
return Route::Xcf;
|
||||
}
|
||||
if xcf::is_gzipped_xcf(name, bytes) {
|
||||
return xcf::import(name, &xcf::gunzip(bytes)?, ctl);
|
||||
return Route::GzippedXcf;
|
||||
}
|
||||
if has_extension(name, "pdn") || bytes.starts_with(b"PDN3") {
|
||||
return pdn::import(name, bytes, ctl);
|
||||
return Route::Pdn;
|
||||
}
|
||||
if raw::is_raw(bytes) {
|
||||
return raw::import_raw_demosaic(name, bytes, opts.demosaic);
|
||||
return Route::Raw;
|
||||
}
|
||||
if is_svg_input(name, bytes) {
|
||||
return svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth);
|
||||
return Route::Svg;
|
||||
}
|
||||
// A `.psd`/`.psb`/`.psdt` with no raster signature keeps the PSD error instead of
|
||||
// `codec: unrecognized image format` (#5258). Magic already returned above.
|
||||
if is_psd_input(name, bytes) {
|
||||
return import_psd(name, ctl, damaged, opts, |want, recover| PsdFile::from_bytes_and_merged_preflight(bytes, want, recover));
|
||||
return Route::NamedPsd;
|
||||
}
|
||||
Route::Flat
|
||||
}
|
||||
|
||||
/// Dispatches format-specific importers and propagates a structured PSD damage
|
||||
/// flag alongside the ordinary best-effort import result.
|
||||
fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result<ImportResult, IoError> {
|
||||
match route(name, bytes) {
|
||||
Route::Pcraft => {
|
||||
let document = photocraft_format::load_from_bytes(bytes)?;
|
||||
Ok(ImportResult { warnings: open_warnings(&document), document, source_read_only: false, preview_only: false })
|
||||
}
|
||||
Route::Psd | Route::NamedPsd => import_psd(name, ctl, damaged, opts, |want, recover| PsdFile::from_bytes_and_merged_preflight(bytes, want, recover)),
|
||||
Route::Affinity => affinity::import(name, bytes),
|
||||
Route::Ora => ora::import(name, bytes, ctl),
|
||||
Route::Kra => kra::import(name, bytes, ctl),
|
||||
Route::Xcf => xcf::import(name, bytes, ctl),
|
||||
Route::GzippedXcf => xcf::import(name, &xcf::gunzip(bytes)?, ctl),
|
||||
Route::Pdn => pdn::import(name, bytes, ctl),
|
||||
Route::Raw => raw::import_raw_demosaic(name, bytes, opts.demosaic),
|
||||
Route::Svg => svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth),
|
||||
Route::Flat => flat::import_flat_with_options(name, bytes, opts, ctl),
|
||||
}
|
||||
flat::import_flat_with_options(name, bytes, opts, ctl)
|
||||
}
|
||||
|
||||
/// Extension names can be wrong (for example, an image downloaded as WebP and renamed `.svg`).
|
||||
@@ -1406,7 +1450,7 @@ mod tests {
|
||||
for (opts, what) in cases {
|
||||
super::psd_gate::set_active_attempt_budget(ample);
|
||||
match super::import_with_options_and_interrupt("nested.psd", &bytes, &opts, &ctl) {
|
||||
Err(super::IoError::PsdImportBudget { required: r, limit }) => {
|
||||
Err(super::IoError::PsdImportBudget { required: r, limit, .. }) => {
|
||||
assert_eq!((r, limit), (required, required - 1), "{what} must refuse with its exact fields")
|
||||
}
|
||||
other => panic!("expected {what} to refuse, got {:?}", other.map(|_| ())),
|
||||
|
||||
+324
-42
@@ -31,9 +31,23 @@ pub const MAX_SOFT_BUDGET: u64 = 8 << 30;
|
||||
/// platform's actual allocation limits, but the process may run out of memory.
|
||||
pub const UNKNOWN_MEMORY_WARNING_THRESHOLD: u64 = 8 << 30;
|
||||
|
||||
/// Reserve subtracted from commit headroom when known.
|
||||
/// Largest reserve subtracted from commit headroom when known. The reserve is a quarter of the
|
||||
/// headroom, at least [`LOW_MEMORY_RESERVE`] and at most this, so a machine with little commit
|
||||
/// headroom still has room for a small file.
|
||||
pub const COMMIT_RESERVE: u64 = 512 << 20;
|
||||
|
||||
/// The smallest amount an approved import leaves free: for the app, its display and the system.
|
||||
///
|
||||
/// Free RAM or commit headroom at or below it leaves no room at all, so every file is refused.
|
||||
pub const LOW_MEMORY_RESERVE: u64 = 256 << 20;
|
||||
|
||||
/// What automatic opening leaves free once that is less than the quarter-of-free-RAM rule.
|
||||
const AUTOMATIC_RAM_RESERVE: u64 = 1 << 30;
|
||||
|
||||
/// When opening a file would leave less than this free, the approval prompt warns that
|
||||
/// PhotoCraft may run out of memory.
|
||||
pub const LOW_MEMORY_WARNING_MARGIN: u64 = 1 << 30;
|
||||
|
||||
/// Bytes Rust's layout rules allow for one contiguous allocation on this target
|
||||
/// (`isize::MAX`), not a bound on an import's aggregate peak.
|
||||
///
|
||||
@@ -171,6 +185,11 @@ pub struct MemoryBudget {
|
||||
/// Set when available memory is unknown: estimates above this threshold still need explicit
|
||||
/// approval but also carry the uncertain-capacity warning. `None` when capacity is known.
|
||||
pub warning_threshold: Option<u64>,
|
||||
/// The free memory measured when measured memory is what set the hard limit: the smaller of
|
||||
/// the known available RAM and commit headroom. `None` when neither is known, when the
|
||||
/// platform cap or the caller's limit is what bound the hard limit, and on the web. A refusal
|
||||
/// reports it so the user can be told to free memory (see [`low_memory_advice`]).
|
||||
pub measured_free: Option<u64>,
|
||||
}
|
||||
|
||||
/// Admission decision for a given required memory estimate.
|
||||
@@ -213,6 +232,34 @@ impl MemoryBudget {
|
||||
pub fn requires_uncertainty_warning(&self, required: u64) -> bool {
|
||||
self.warning_threshold.is_some_and(|threshold| required > threshold)
|
||||
}
|
||||
|
||||
/// The free memory to report when `required` is refused, or `None` when closing other apps
|
||||
/// cannot help: the estimate overflowed `u64` (`u64::MAX`), or the limit that refused it was
|
||||
/// not set by measured memory.
|
||||
pub fn refusal_free_memory(&self, required: u64) -> Option<u64> {
|
||||
if required == u64::MAX { None } else { self.measured_free }
|
||||
}
|
||||
}
|
||||
|
||||
/// The sentence appended to a hard-memory refusal when measured free memory set the limit; empty
|
||||
/// for `None`. `Some(0)` also covers the fail-closed reading of an unreadable memory limit.
|
||||
pub fn low_memory_advice(free_memory: &Option<u64>) -> String {
|
||||
match free_memory {
|
||||
None => String::new(),
|
||||
Some(0) => ". PhotoCraft measured no free memory, or could not read this system's memory limit. Close other apps and try again".to_string(),
|
||||
Some(n) => format!(". About {} of memory is free. Close other apps and try again", size_text(*n)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A size for people: "3.0 GiB", "900 MiB", "512 B".
|
||||
fn size_text(bytes: u64) -> String {
|
||||
if bytes >= 1 << 30 {
|
||||
format!("{:.1} GiB", bytes as f64 / (1u64 << 30) as f64)
|
||||
} else if bytes >= 1 << 20 {
|
||||
format!("{} MiB", bytes / (1 << 20))
|
||||
} else {
|
||||
format!("{bytes} B")
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an approval-required estimate carries the unknown-capacity warning, given the
|
||||
@@ -252,16 +299,22 @@ pub fn native_platform_cap() -> u64 {
|
||||
/// The limits are for an import's aggregate peak estimate, not for one allocation: a peak may sum
|
||||
/// many buffers, each of which is separately bounded where the decoder allocates it.
|
||||
///
|
||||
/// Policy:
|
||||
/// - Known RAM: H = min(floor(3*A/4), A - 1 GiB, C - reserve if known, [`native_platform_cap`]);
|
||||
/// S = min(A/2, 8 GiB, H).
|
||||
/// - Unknown native RAM: S = min(2 GiB, H) where H is [`native_platform_cap`], reduced by known
|
||||
/// commit headroom; approval above S is possible up to H. 8 GiB is a warning threshold, not H.
|
||||
/// - Web (wasm32): S = 1 GiB; H = min([`WASM_MAX_PEAK_BUDGET`], caller limit).
|
||||
/// Policy (A = available RAM, C = commit headroom, each when known):
|
||||
/// - Known RAM: H = min(floor(3*A/4), A - [`LOW_MEMORY_RESERVE`], C - reserve if known,
|
||||
/// [`native_platform_cap`]), where the commit reserve is a quarter of C, at least
|
||||
/// [`LOW_MEMORY_RESERVE`] and at most [`COMMIT_RESERVE`]. S = min(A/2, 8 GiB, max(A - 1 GiB,
|
||||
/// A/4), max(C - [`COMMIT_RESERVE`], C/4) if known, H). Above 4/3 GiB free this is the usual
|
||||
/// "leave 1 GiB free"; below it up to a quarter of free RAM opens automatically and the rest
|
||||
/// goes to approval. At or below [`LOW_MEMORY_RESERVE`] of either there is no room.
|
||||
/// - Unknown native RAM: S = min(2 GiB, commit soft room if known, H) where H is
|
||||
/// [`native_platform_cap`], reduced by known commit headroom as above; approval above S is
|
||||
/// possible up to H. 8 GiB is a warning threshold, not H.
|
||||
/// - <= S: automatic; S < E <= H: explicit approval; > H: refuse, no unlimited override.
|
||||
/// - The saturated `u64::MAX` overflow sentinel is always refused, even when H is `u64::MAX`
|
||||
/// (see [`MemoryBudget::decide`]).
|
||||
/// - Known zero available RAM stays zero (it never becomes unknown/free).
|
||||
/// - Known zero available RAM stays zero (it never becomes unknown/free). The fail-closed reading
|
||||
/// of an unreadable memory limit is `Some(0)`, so it stays refused; only a credited tile share
|
||||
/// (see [`resolve_budget_with_scratch`]) can pass, as before.
|
||||
/// - swap is never part of the adaptive budget.
|
||||
/// - Explicit caller limits may lower admission, never bypass the hard boundary.
|
||||
pub fn resolve_budget(snapshot: MemorySnapshot, caller_limit: Option<u64>) -> MemoryBudget {
|
||||
@@ -294,47 +347,72 @@ fn resolve_budget_credited(platform: Platform, snapshot: MemorySnapshot, caller_
|
||||
if let Some(caller) = caller_limit.filter(|&c| c > 0) {
|
||||
hard = hard.min(caller);
|
||||
}
|
||||
return MemoryBudget { soft_limit: WASM_BUDGET.min(hard), hard_limit: hard, available_ram: None, warning_threshold: None };
|
||||
return MemoryBudget { soft_limit: WASM_BUDGET.min(hard), hard_limit: hard, available_ram: None, warning_threshold: None, measured_free: None };
|
||||
}
|
||||
|
||||
let platform_cap = native_platform_cap();
|
||||
let (mut hard, mut soft, warning_threshold) = match snapshot.available_ram {
|
||||
Some(a) => {
|
||||
let h_pct = ((a as u128 * 3) / 4) as u64;
|
||||
let h_reserve = a.saturating_sub(1 << 30);
|
||||
let mut h = h_pct.min(h_reserve);
|
||||
let ram = snapshot.available_ram;
|
||||
let commit = snapshot.commit_headroom;
|
||||
|
||||
if let Some(c) = snapshot.commit_headroom {
|
||||
let c_room = c.saturating_sub(COMMIT_RESERVE);
|
||||
h = h.min(c_room);
|
||||
}
|
||||
|
||||
h = h.min(platform_cap);
|
||||
|
||||
let s_pct = a / 2;
|
||||
let s = s_pct.min(MAX_SOFT_BUDGET).min(h);
|
||||
(h, s, None)
|
||||
}
|
||||
None => {
|
||||
let mut h = platform_cap;
|
||||
if let Some(c) = snapshot.commit_headroom {
|
||||
let c_room = c.saturating_sub(COMMIT_RESERVE);
|
||||
h = h.min(c_room);
|
||||
}
|
||||
let s = NATIVE_FALLBACK_BUDGET.min(h);
|
||||
(h, s, Some(UNKNOWN_MEMORY_WARNING_THRESHOLD))
|
||||
}
|
||||
// The room measured memory leaves; with neither measurement known only the platform cap bounds.
|
||||
let measured_room = match (ram.map(ram_hard_room), commit.map(commit_hard_room)) {
|
||||
(Some(r), Some(c)) => Some(r.min(c)),
|
||||
(r, c) => r.or(c),
|
||||
};
|
||||
let mut hard = measured_room.map_or(platform_cap, |room| room.min(platform_cap));
|
||||
let commit_soft = commit.map(commit_soft_room);
|
||||
let (mut soft, warning_threshold) = match ram {
|
||||
Some(a) => (ram_soft_room(a).min(commit_soft.unwrap_or(u64::MAX)).min(hard), None),
|
||||
None => (NATIVE_FALLBACK_BUDGET.min(commit_soft.unwrap_or(u64::MAX)).min(hard), Some(UNKNOWN_MEMORY_WARNING_THRESHOLD)),
|
||||
};
|
||||
// Tile pixels the scratch disk takes need no RAM (see [`resolve_budget_with_scratch`]).
|
||||
hard = hard.saturating_add(credit);
|
||||
soft = soft.saturating_add(credit);
|
||||
let machine_limit = hard;
|
||||
|
||||
if let Some(caller) = caller_limit.filter(|&c| c > 0) {
|
||||
hard = hard.min(caller);
|
||||
soft = soft.min(hard);
|
||||
}
|
||||
|
||||
MemoryBudget { soft_limit: soft, hard_limit: hard, available_ram: snapshot.available_ram, warning_threshold }
|
||||
// Report the measured free memory only when it alone set the hard limit: where the platform
|
||||
// cap equals the measured room, more free memory could not raise the limit.
|
||||
let measured_free = match (ram, commit) {
|
||||
(None, None) => None,
|
||||
(Some(a), None) => Some(a),
|
||||
(None, Some(c)) => Some(c),
|
||||
(Some(a), Some(c)) => Some(a.min(c)),
|
||||
}
|
||||
.filter(|_| measured_room.is_some_and(|room| room < platform_cap) && hard >= machine_limit);
|
||||
|
||||
MemoryBudget { soft_limit: soft, hard_limit: hard, available_ram: ram, warning_threshold, measured_free }
|
||||
}
|
||||
|
||||
/// Hard room (what an approved import may use) when `a` bytes of RAM are free: three quarters of
|
||||
/// it, leaving at least [`LOW_MEMORY_RESERVE`].
|
||||
fn ram_hard_room(a: u64) -> u64 {
|
||||
let quarter_rule = ((a as u128 * 3) / 4) as u64;
|
||||
quarter_rule.min(a.saturating_sub(LOW_MEMORY_RESERVE))
|
||||
}
|
||||
|
||||
/// Automatic room when `a` bytes of RAM are free: half of it, up to [`MAX_SOFT_BUDGET`], leaving
|
||||
/// 1 GiB free or, when that is less, a quarter of it.
|
||||
fn ram_soft_room(a: u64) -> u64 {
|
||||
(a / 2).min(MAX_SOFT_BUDGET).min(a.saturating_sub(AUTOMATIC_RAM_RESERVE).max(a / 4))
|
||||
}
|
||||
|
||||
/// Hard room when `c` bytes of commit headroom remain: all but a reserve of a quarter, at least
|
||||
/// [`LOW_MEMORY_RESERVE`] and at most [`COMMIT_RESERVE`].
|
||||
fn commit_hard_room(c: u64) -> u64 {
|
||||
// `clamp` panics only if its bounds are out of order, and they are constants.
|
||||
const { assert!(LOW_MEMORY_RESERVE <= COMMIT_RESERVE) };
|
||||
let reserve = (c / 4).clamp(LOW_MEMORY_RESERVE, COMMIT_RESERVE);
|
||||
c.saturating_sub(reserve)
|
||||
}
|
||||
|
||||
/// Automatic room when `c` bytes of commit headroom remain.
|
||||
fn commit_soft_room(c: u64) -> u64 {
|
||||
c.saturating_sub(COMMIT_RESERVE).max(c / 4)
|
||||
}
|
||||
|
||||
/// Result of evaluating an import admission request.
|
||||
@@ -411,7 +489,9 @@ fn evaluate_psd_admission_for(
|
||||
}
|
||||
cap
|
||||
}
|
||||
BudgetDecision::Refused => return Err(IoError::PsdImportBudget { required, limit: budget.hard_limit }),
|
||||
BudgetDecision::Refused => {
|
||||
return Err(IoError::PsdImportBudget { required, limit: budget.hard_limit, free_memory: budget.refusal_free_memory(required) });
|
||||
}
|
||||
};
|
||||
|
||||
if required > authorized_total {
|
||||
@@ -448,7 +528,7 @@ pub(crate) fn nested_import_local_bound(required: u64, caller_limit: u64, approv
|
||||
(caller, approved) => caller.or(approved),
|
||||
};
|
||||
match limit {
|
||||
Some(limit) if required > limit => Err(IoError::PsdImportBudget { required, limit }),
|
||||
Some(limit) if required > limit => Err(IoError::PsdImportBudget { required, limit, free_memory: None }),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -767,7 +847,7 @@ mod tests {
|
||||
|
||||
for (approved, estimate) in [(false, None), (true, None), (true, Some(u64::MAX))] {
|
||||
match evaluate_psd_admission_for(Platform::Native, u64::MAX, 0, 0, approved, estimate, MemorySnapshot::UNKNOWN) {
|
||||
Err(IoError::PsdImportBudget { required, limit }) => {
|
||||
Err(IoError::PsdImportBudget { required, limit, .. }) => {
|
||||
assert_eq!((required, limit), (u64::MAX, u64::MAX), "the typed refusal keeps the estimate and limit unchanged")
|
||||
}
|
||||
other => panic!("approved={approved}, estimate={estimate:?}: expected a hard refusal, got {other:?}"),
|
||||
@@ -777,7 +857,7 @@ mod tests {
|
||||
// A caller limit equal to the sentinel, or an approved estimate of it, is no exception.
|
||||
assert!(matches!(
|
||||
evaluate_psd_admission_for(Platform::Native, u64::MAX, 0, u64::MAX, true, Some(u64::MAX), MemorySnapshot::UNKNOWN),
|
||||
Err(IoError::PsdImportBudget { required: u64::MAX, limit: u64::MAX })
|
||||
Err(IoError::PsdImportBudget { required: u64::MAX, limit: u64::MAX, .. })
|
||||
));
|
||||
}
|
||||
|
||||
@@ -816,8 +896,9 @@ mod tests {
|
||||
|
||||
let snap_tight = MemorySnapshot { available_ram: None, swap_free: None, commit_headroom: Some(gb) };
|
||||
let b_tight = resolve_budget(snap_tight, None);
|
||||
assert_eq!(b_tight.hard_limit, gb - COMMIT_RESERVE);
|
||||
assert_eq!(b_tight.soft_limit, gb - COMMIT_RESERVE);
|
||||
// 1 GiB of headroom keeps a quarter free (256 MiB), not the full 512 MiB.
|
||||
assert_eq!(b_tight.hard_limit, 768 << 20);
|
||||
assert_eq!(b_tight.soft_limit, 512 << 20);
|
||||
|
||||
let snap_room = MemorySnapshot { available_ram: None, swap_free: None, commit_headroom: Some(4 * gb) };
|
||||
let b_room = resolve_budget(snap_room, None);
|
||||
@@ -995,7 +1076,7 @@ mod tests {
|
||||
assert!(evaluate_psd_admission(26 * gb, 18 * gb, 0, true, Some(26 * gb - 1), snap).is_err());
|
||||
// 10 GiB non-spillable is over H: refused even when approved.
|
||||
let err = evaluate_psd_admission(28 * gb, 18 * gb, 0, true, Some(28 * gb), snap).unwrap_err();
|
||||
assert!(matches!(err, IoError::PsdImportBudget { required, limit } if required == 28 * gb && limit == 27 * gb));
|
||||
assert!(matches!(err, IoError::PsdImportBudget { required, limit, .. } if required == 28 * gb && limit == 27 * gb));
|
||||
// A spillable share claimed beyond the total is clamped to the total.
|
||||
assert!(evaluate_psd_admission(5 * gb, u64::MAX, 0, false, None, snap).is_ok());
|
||||
// The caller's explicit limit still bounds the whole import.
|
||||
@@ -1081,4 +1162,205 @@ mod tests {
|
||||
let without_swap = MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None };
|
||||
assert_eq!(resolve_budget_for(Platform::Native, with_swap, None), resolve_budget_for(Platform::Native, without_swap, None));
|
||||
}
|
||||
|
||||
const MIB: u64 = 1 << 20;
|
||||
const GIB: u64 = 1 << 30;
|
||||
|
||||
fn native_budget(ram: Option<u64>, commit: Option<u64>) -> MemoryBudget {
|
||||
resolve_budget_for(Platform::Native, MemorySnapshot { available_ram: ram, swap_free: None, commit_headroom: commit }, None)
|
||||
}
|
||||
|
||||
fn hard_refusal(result: Result<AdmissionOutcome, IoError>) -> (u64, u64, Option<u64>) {
|
||||
match result {
|
||||
Err(IoError::PsdImportBudget { required, limit, free_memory }) => (required, limit, free_memory),
|
||||
other => panic!("expected a hard refusal, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn low_ram_boundaries_keep_room_for_small_files() {
|
||||
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
|
||||
return;
|
||||
}
|
||||
// (free RAM, soft limit, hard limit)
|
||||
let table = [
|
||||
(0, 0, 0),
|
||||
(128 * MIB, 0, 0),
|
||||
(256 * MIB, 0, 0),
|
||||
(256 * MIB + 1, 64 * MIB, 1),
|
||||
(512 * MIB, 128 * MIB, 256 * MIB),
|
||||
(GIB, 256 * MIB, 768 * MIB),
|
||||
(GIB + 1, 256 * MIB, 768 * MIB),
|
||||
(1366 * MIB, 342 * MIB, 2049 * MIB / 2),
|
||||
(3 * GIB / 2, 512 * MIB, 1152 * MIB),
|
||||
(2 * GIB, GIB, 3 * GIB / 2),
|
||||
(3 * GIB, 3 * GIB / 2, 9 * GIB / 4),
|
||||
(4 * GIB, 2 * GIB, 3 * GIB),
|
||||
(8 * GIB, 4 * GIB, 6 * GIB),
|
||||
];
|
||||
for (ram, soft, hard) in table {
|
||||
let b = native_budget(Some(ram), None);
|
||||
// The soft limit is also bounded by the hard limit: 256 MiB + 1 leaves 1 byte.
|
||||
let soft = soft.min(hard);
|
||||
assert_eq!((b.soft_limit, b.hard_limit), (soft, hard), "free RAM {ram}");
|
||||
assert_eq!(b.warning_threshold, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn low_commit_boundaries_keep_room_for_small_files() {
|
||||
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
|
||||
return;
|
||||
}
|
||||
// (commit headroom, soft limit, hard limit) with plenty of RAM, then with RAM unknown.
|
||||
let table = [
|
||||
(0, 0, 0),
|
||||
(128 * MIB, 0, 0),
|
||||
(256 * MIB, 0, 0),
|
||||
(512 * MIB, 128 * MIB, 256 * MIB),
|
||||
(512 * MIB + 1, 128 * MIB, 256 * MIB + 1),
|
||||
(GIB, 512 * MIB, 768 * MIB),
|
||||
(3 * GIB / 2, GIB, 1152 * MIB),
|
||||
(2 * GIB, 3 * GIB / 2, 3 * GIB / 2),
|
||||
(5 * GIB, 9 * GIB / 2, 9 * GIB / 2),
|
||||
];
|
||||
for (commit, soft, hard) in table {
|
||||
let b = native_budget(Some(64 * GIB), Some(commit));
|
||||
assert_eq!((b.soft_limit, b.hard_limit), (soft, hard), "commit {commit}, RAM known");
|
||||
let unknown = native_budget(None, Some(commit));
|
||||
assert_eq!(unknown.hard_limit, hard, "commit {commit}, RAM unknown");
|
||||
assert_eq!(unknown.soft_limit, soft.min(2 * GIB), "commit {commit}, RAM unknown");
|
||||
assert_eq!(unknown.warning_threshold, Some(UNKNOWN_MEMORY_WARNING_THRESHOLD));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budgets_grow_with_free_memory_and_leave_the_reserve() {
|
||||
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
|
||||
return;
|
||||
}
|
||||
for by_commit in [false, true] {
|
||||
let (mut last_soft, mut last_hard) = (0, 0);
|
||||
let mut measured = 0;
|
||||
while measured <= 9 * GIB {
|
||||
let b = if by_commit { native_budget(Some(64 * GIB), Some(measured)) } else { native_budget(Some(measured), None) };
|
||||
assert!(b.soft_limit <= b.hard_limit, "commit={by_commit} {measured}");
|
||||
assert!(b.hard_limit <= measured, "commit={by_commit} {measured}");
|
||||
assert!(b.soft_limit >= last_soft && b.hard_limit >= last_hard, "commit={by_commit} {measured}: not non-decreasing");
|
||||
if b.hard_limit > 0 {
|
||||
assert!(measured - b.hard_limit >= LOW_MEMORY_RESERVE, "commit={by_commit} {measured}: reserve not kept");
|
||||
}
|
||||
(last_soft, last_hard) = (b.soft_limit, b.hard_limit);
|
||||
measured += 16 * MIB;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_file_opens_on_a_machine_with_little_free_memory() {
|
||||
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
|
||||
return;
|
||||
}
|
||||
let b = native_budget(Some(900 * MIB), None);
|
||||
assert_eq!(b.decide(100 * MIB), BudgetDecision::Automatic);
|
||||
assert_eq!(b.decide(300 * MIB), BudgetDecision::RequiresApproval);
|
||||
assert_eq!(b.decide(700 * MIB), BudgetDecision::Refused);
|
||||
|
||||
// The reported case: about 190 MB beyond 1 GiB free.
|
||||
let snap = MemorySnapshot { available_ram: Some(190_693_376 + GIB), swap_free: None, commit_headroom: None };
|
||||
let (required, limit, free) = hard_refusal(evaluate_psd_admission_for(Platform::Native, 1_136_504_592, 0, 0, false, None, snap));
|
||||
assert_eq!((required, limit), (1_136_504_592, (190_693_376 + GIB) * 3 / 4));
|
||||
assert_eq!(free, Some(190_693_376 + GIB));
|
||||
assert!(matches!(evaluate_psd_admission_for(Platform::Native, 500_000_000, 0, 0, false, None, snap), Err(IoError::PsdApprovalRequired { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refusals_report_free_memory_only_when_measured_memory_set_the_limit() {
|
||||
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
|
||||
return;
|
||||
}
|
||||
let snap = |ram, commit| MemorySnapshot { available_ram: ram, swap_free: None, commit_headroom: commit };
|
||||
let refuse = |required, caller, snapshot| hard_refusal(evaluate_psd_admission_for(Platform::Native, required, 0, caller, false, None, snapshot));
|
||||
|
||||
// RAM binds.
|
||||
assert_eq!(refuse(2 * GIB, 0, snap(Some(GIB), None)), (2 * GIB, 768 * MIB, Some(GIB)));
|
||||
// Commit headroom below RAM binds.
|
||||
assert_eq!(refuse(2 * GIB, 0, snap(Some(64 * GIB), Some(GIB))), (2 * GIB, 768 * MIB, Some(GIB)));
|
||||
// Commit headroom alone (RAM unknown).
|
||||
assert_eq!(refuse(2 * GIB, 0, snap(None, Some(GIB))), (2 * GIB, 768 * MIB, Some(GIB)));
|
||||
// Zero measured RAM (also the fail-closed unreadable limit) refuses everything.
|
||||
assert_eq!(refuse(1, 0, snap(Some(0), None)), (1, 0, Some(0)));
|
||||
// A binding caller limit is not the machine's.
|
||||
assert_eq!(refuse(2 * GIB, GIB, snap(Some(8 * GIB), None)), (2 * GIB, GIB, None));
|
||||
assert_eq!(refuse(2 * GIB, GIB, MemorySnapshot::UNKNOWN), (2 * GIB, GIB, None));
|
||||
// The overflow sentinel is not helped by closing apps.
|
||||
assert_eq!(refuse(u64::MAX, 0, snap(Some(8 * GIB), None)), (u64::MAX, 6 * GIB, None));
|
||||
assert_eq!(refuse(u64::MAX, 0, MemorySnapshot::UNKNOWN), (u64::MAX, u64::MAX, None));
|
||||
|
||||
// On the budget itself.
|
||||
assert_eq!(native_budget(Some(8 * GIB), None).measured_free, Some(8 * GIB));
|
||||
assert_eq!(native_budget(Some(8 * GIB), None).refusal_free_memory(u64::MAX), None);
|
||||
assert_eq!(native_budget(None, None).measured_free, None);
|
||||
assert_eq!(resolve_budget_for(Platform::Web, snap(Some(GIB), None), None).measured_free, None);
|
||||
// A caller limit equal to the machine's limit does not hide the measurement.
|
||||
assert_eq!(resolve_budget_for(Platform::Native, snap(Some(8 * GIB), None), Some(6 * GIB)).measured_free, Some(8 * GIB));
|
||||
assert_eq!(resolve_budget_for(Platform::Native, snap(Some(8 * GIB), None), Some(6 * GIB - 1)).measured_free, None);
|
||||
}
|
||||
|
||||
/// Only 32-bit native has a finite cap: when it equals the measured room, freeing memory
|
||||
/// cannot raise the limit, so no free-memory figure is reported.
|
||||
#[test]
|
||||
fn a_platform_cap_equal_to_the_measured_room_reports_no_free_memory() {
|
||||
let cap = native_platform_cap();
|
||||
if cap == u64::MAX {
|
||||
return;
|
||||
}
|
||||
assert_eq!(native_budget(None, Some(cap + COMMIT_RESERVE)).measured_free, None);
|
||||
assert_eq!(native_budget(None, Some(cap - 1 + COMMIT_RESERVE)).measured_free, Some(cap - 1 + COMMIT_RESERVE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scratch_credit_adds_to_the_low_memory_limits() {
|
||||
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
|
||||
return;
|
||||
}
|
||||
let snap = |ram, commit| MemorySnapshot { available_ram: ram, swap_free: None, commit_headroom: commit };
|
||||
with_mock_scratch(Some(40 * GIB), || {
|
||||
let one_gib = snap(Some(GIB), None);
|
||||
let out = evaluate_psd_admission_for(Platform::Native, 2 * GIB + 100 * MIB, 2 * GIB, 0, false, None, one_gib).unwrap();
|
||||
assert_eq!(out.authorized_total, 256 * MIB + 2 * GIB);
|
||||
|
||||
let err = evaluate_psd_admission_for(Platform::Native, 2 * GIB + 500 * MIB, 2 * GIB, 0, false, None, one_gib).unwrap_err();
|
||||
assert!(matches!(err, IoError::PsdApprovalRequired { soft_limit, hard_limit, .. }
|
||||
if soft_limit == 2 * GIB + 256 * MIB && hard_limit == 2 * GIB + 768 * MIB));
|
||||
|
||||
let refused = hard_refusal(evaluate_psd_admission_for(Platform::Native, 2 * GIB + 800 * MIB, 2 * GIB, 0, true, None, one_gib));
|
||||
assert_eq!(refused, (2 * GIB + 800 * MIB, 2 * GIB + 768 * MIB, Some(GIB)));
|
||||
|
||||
// Fail closed: nothing measured, so only the credited tile share passes.
|
||||
let zero = snap(Some(0), None);
|
||||
assert!(evaluate_psd_admission_for(Platform::Native, 2 * GIB, 2 * GIB, 0, false, None, zero).is_ok());
|
||||
let refused = hard_refusal(evaluate_psd_admission_for(Platform::Native, 2 * GIB + 1, 2 * GIB, 0, true, None, zero));
|
||||
assert_eq!(refused, (2 * GIB + 1, 2 * GIB, Some(0)));
|
||||
|
||||
// Low commit headroom with plenty of RAM: H = 256 MiB + credit.
|
||||
let low_commit = snap(Some(64 * GIB), Some(512 * MIB));
|
||||
let refused = hard_refusal(evaluate_psd_admission_for(Platform::Native, 2 * GIB + 300 * MIB, 2 * GIB, 0, true, None, low_commit));
|
||||
assert_eq!(refused, (2 * GIB + 300 * MIB, 2 * GIB + 256 * MIB, Some(512 * MIB)));
|
||||
let b = resolve_budget_credited(Platform::Native, low_commit, None, 2 * GIB);
|
||||
assert_eq!((b.soft_limit, b.hard_limit), (2 * GIB + 128 * MIB, 2 * GIB + 256 * MIB));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn low_memory_advice_names_the_free_memory() {
|
||||
assert_eq!(low_memory_advice(&None), "");
|
||||
assert_eq!(
|
||||
low_memory_advice(&Some(0)),
|
||||
". PhotoCraft measured no free memory, or could not read this system's memory limit. Close other apps and try again"
|
||||
);
|
||||
assert_eq!(low_memory_advice(&Some(900 << 20)), ". About 900 MiB of memory is free. Close other apps and try again");
|
||||
assert_eq!(low_memory_advice(&Some(3 << 30)), ". About 3.0 GiB of memory is free. Close other apps and try again");
|
||||
assert_eq!(low_memory_advice(&Some(512)), ". About 512 B of memory is free. Close other apps and try again");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//! A PNG import in resumable steps, for a caller that must not block for the whole file (the web
|
||||
//! build has no threads): the same document [`crate::import_with_options_and_interrupt`] gives.
|
||||
//!
|
||||
//! A PNG whose rows come in final order is streamed: each decoded group of rows becomes tiles at
|
||||
//! once and is dropped, as [`crate::import_with_options_and_interrupt`] does, so the image never
|
||||
//! exists next to the layer built from it (a 100 MP RGBA8 file would need about 400 MB more, which
|
||||
//! a browser tab does not have). Any other PNG (interlaced, animated, or stored in another
|
||||
//! orientation) is decoded whole, turned upright and copied into tiles, each in bounded steps.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_codecs::{self as codecs, DecodeOptions, Format, Limits, OrientSteps, PngDecodeRows, PngExtras, PngFinish, SharedBytes, begin_png_finish};
|
||||
use photocraft_geom::TILE_SIZE;
|
||||
use photocraft_raster::{Interrupt, PruneCursor};
|
||||
|
||||
use crate::flat::{FlatBuilder, PngStream, apply_flat_format};
|
||||
use crate::{ImportResult, IoError, Route};
|
||||
|
||||
/// The rows of a file being streamed into the tiles of its layer.
|
||||
struct Streaming {
|
||||
rows: PngDecodeRows<SharedBytes>,
|
||||
stream: PngStream,
|
||||
}
|
||||
|
||||
/// A streamed layer being scanned for tiles that hold only the default pixel.
|
||||
struct Pruning {
|
||||
stream: PngStream,
|
||||
cursor: PruneCursor,
|
||||
extras: PngExtras,
|
||||
}
|
||||
|
||||
enum Stage {
|
||||
/// The rows becoming tiles as they are decoded.
|
||||
Stream(Box<Streaming>),
|
||||
/// The streamed layer's prune scan.
|
||||
Prune(Box<Pruning>),
|
||||
/// The whole image, decoded a row at a time: a file whose rows can't be streamed.
|
||||
Rows(Box<PngDecodeRows<SharedBytes>>),
|
||||
/// The decoded image turned upright (an EXIF orientation 2-8), a band of rows at a time.
|
||||
Orient(Box<OrientSteps>),
|
||||
/// The decoded image becoming the document, a band of rows and a batch of tiles at a time.
|
||||
Build(Box<FlatBuilder>),
|
||||
Spent,
|
||||
}
|
||||
|
||||
/// A plain PNG file being imported as a document, a few rows at a time.
|
||||
pub struct PngImport {
|
||||
name: String,
|
||||
bytes: Arc<Vec<u8>>,
|
||||
stage: Stage,
|
||||
}
|
||||
|
||||
impl PngImport {
|
||||
/// Starts importing `bytes` (named `name`) when the import would decode them as a plain PNG,
|
||||
/// which reads the header and refuses what the import refuses; `None` for any other file,
|
||||
/// which only [`crate::import_with_options_and_interrupt`] reads. The decoder shares `bytes`.
|
||||
pub fn new(name: &str, bytes: &Arc<Vec<u8>>) -> Result<Option<Self>, IoError> {
|
||||
if crate::route(name, bytes) != Route::Flat || codecs::detect(bytes) != Some(Format::Png) {
|
||||
return Ok(None);
|
||||
}
|
||||
let rows = PngDecodeRows::new_streaming(SharedBytes(Arc::clone(bytes)), &Limits::default())?;
|
||||
let stage = if rows.streamable() {
|
||||
let stream = PngStream::for_steps(&rows.header())?;
|
||||
Stage::Stream(Box::new(Streaming { rows, stream }))
|
||||
} else {
|
||||
Stage::Rows(Box::new(Self::buffered(rows)?))
|
||||
};
|
||||
Ok(Some(Self { name: name.to_string(), bytes: Arc::clone(bytes), stage }))
|
||||
}
|
||||
|
||||
/// A decoder that holds the whole image: its output is reserved up front.
|
||||
fn buffered(mut rows: PngDecodeRows<SharedBytes>) -> Result<PngDecodeRows<SharedBytes>, IoError> {
|
||||
rows.reserve_output()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Whether the rows are streamed into the layer's tiles as they are decoded, so the decoded
|
||||
/// image never exists whole. False for a file whose rows can't come in final order, and from
|
||||
/// the moment a late `eXIf` sends a streamed one back to a whole decode.
|
||||
pub fn streams(&self) -> bool {
|
||||
matches!(self.stage, Stage::Stream(_) | Stage::Prune(_))
|
||||
}
|
||||
|
||||
/// How much of the import is done, `0.0..=1.0`.
|
||||
pub fn progress(&self) -> f32 {
|
||||
match &self.stage {
|
||||
Stage::Stream(s) => s.rows.progress(),
|
||||
Stage::Rows(rows) => rows.progress(),
|
||||
Stage::Orient(steps) => steps.progress(),
|
||||
Stage::Prune(_) | Stage::Build(_) | Stage::Spent => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Works while `more()` returns true (at least one bounded piece per call): rows (into tiles
|
||||
/// as they come, or into the whole image), the turn upright, the copy into tiles, then the
|
||||
/// prune scan. `Some` once the document is built, after which the import is spent.
|
||||
pub fn step(&mut self, more: &mut dyn FnMut() -> bool) -> Result<Option<ImportResult>, IoError> {
|
||||
match std::mem::replace(&mut self.stage, Stage::Spent) {
|
||||
Stage::Stream(mut s) => {
|
||||
let result = {
|
||||
let Streaming { rows, stream } = &mut *s;
|
||||
let mut sink = |y0: u32, data: &[u8]| stream.write_rows(y0, data, &Interrupt::NONE);
|
||||
rows.step_stream::<IoError>(TILE_SIZE as u32, more, &mut sink)?
|
||||
};
|
||||
self.stage = match result {
|
||||
None => Stage::Stream(s),
|
||||
// An `eXIf` after the image data turns the image: decode it whole instead, as
|
||||
// the one-shot import does, with the streamed layer released first.
|
||||
Some(extras) if extras.orientation != 1 => {
|
||||
drop(s);
|
||||
let rows = PngDecodeRows::new_streaming(SharedBytes(Arc::clone(&self.bytes)), &Limits::default())?;
|
||||
Stage::Rows(Box::new(Self::buffered(rows)?))
|
||||
}
|
||||
Some(extras) => {
|
||||
let stream = s.stream;
|
||||
let cursor = stream.prune_cursor();
|
||||
Stage::Prune(Box::new(Pruning { stream, cursor, extras }))
|
||||
}
|
||||
};
|
||||
Ok(None)
|
||||
}
|
||||
Stage::Prune(mut p) => loop {
|
||||
if p.stream.prune_step(&mut p.cursor) {
|
||||
let Pruning { stream, extras, .. } = *p;
|
||||
let mut r = stream.into_document(&self.name, extras)?;
|
||||
apply_flat_format(&mut r, &self.bytes, Some(Format::Png), None)?;
|
||||
return Ok(Some(r));
|
||||
}
|
||||
if !more() {
|
||||
self.stage = Stage::Prune(p);
|
||||
return Ok(None);
|
||||
}
|
||||
},
|
||||
Stage::Rows(mut rows) => {
|
||||
self.stage = match rows.step(more)? {
|
||||
Some(img) => {
|
||||
// The resolution, upright orientation and final limit checks `decode` does.
|
||||
match begin_png_finish(img, &DecodeOptions::default())? {
|
||||
PngFinish::Done(img) => Stage::Build(Box::new(FlatBuilder::new(&self.name, *img)?)),
|
||||
PngFinish::Orient(steps) => Stage::Orient(steps),
|
||||
}
|
||||
}
|
||||
None => Stage::Rows(rows),
|
||||
};
|
||||
Ok(None)
|
||||
}
|
||||
Stage::Orient(mut steps) => {
|
||||
self.stage = match steps.step(more)? {
|
||||
Some(img) => Stage::Build(Box::new(FlatBuilder::new(&self.name, img)?)),
|
||||
None => Stage::Orient(steps),
|
||||
};
|
||||
Ok(None)
|
||||
}
|
||||
Stage::Build(mut build) => loop {
|
||||
if !build.copy_done() {
|
||||
build.copy_step()?;
|
||||
if !more() {
|
||||
self.stage = Stage::Build(build);
|
||||
return Ok(None);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !build.prune_done() {
|
||||
build.prune_step();
|
||||
if !more() {
|
||||
self.stage = Stage::Build(build);
|
||||
return Ok(None);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
return build.finish(self.bytes.as_slice(), Some(Format::Png)).map(Some);
|
||||
},
|
||||
Stage::Spent => Err(IoError::Unsupported("the PNG was already imported".into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -249,7 +249,7 @@ pub fn estimate(file: &PsdFile) -> Result<PsdMemoryEstimate, IoError> {
|
||||
pub fn check(file: &PsdFile, limit: u64) -> Result<PsdMemoryEstimate, IoError> {
|
||||
let est = estimate(file)?;
|
||||
if est.total_bytes > limit {
|
||||
return Err(IoError::PsdImportBudget { required: est.total_bytes, limit });
|
||||
return Err(IoError::PsdImportBudget { required: est.total_bytes, limit, free_memory: None });
|
||||
}
|
||||
Ok(est)
|
||||
}
|
||||
|
||||
@@ -284,6 +284,29 @@ fn zero_available_ram_refuses_admission() {
|
||||
});
|
||||
}
|
||||
|
||||
/// A small file opens with 900 MiB free (it used to be refused outright below 1 GiB); with no
|
||||
/// free memory at all it is refused and the refusal says why.
|
||||
#[test]
|
||||
fn small_file_opens_with_little_free_memory_and_a_refusal_names_it() {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return; // the web policy ignores a host snapshot; it has its own tests
|
||||
}
|
||||
let file = testgen::small(Version::Psd, Compression::Zip);
|
||||
let bytes = file.to_bytes().unwrap();
|
||||
|
||||
let low = crate::memory::MemorySnapshot { available_ram: Some(900 << 20), swap_free: None, commit_headroom: None };
|
||||
crate::memory::with_mock_memory(low, || {
|
||||
let res = crate::import_with_options("small.psd", &bytes, &crate::ImportOptions::default());
|
||||
assert!(res.is_ok(), "{:?}", res.map(|_| ()));
|
||||
});
|
||||
|
||||
let none = crate::memory::MemorySnapshot { available_ram: Some(0), swap_free: None, commit_headroom: None };
|
||||
crate::memory::with_mock_memory(none, || {
|
||||
let res = crate::import_with_options("small.psd", &bytes, &crate::ImportOptions::default());
|
||||
assert!(matches!(res, Err(IoError::PsdImportBudget { limit: 0, free_memory: Some(0), .. })));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_rejection_and_approval_files_release_gate() {
|
||||
if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) {
|
||||
@@ -337,7 +360,7 @@ fn retry_estimate_cap_rejects_altered_or_enlarged_file() {
|
||||
|
||||
// 3. Exceeds hard limit: refused completely regardless of approval
|
||||
let res = crate::memory::evaluate_psd_admission(10 * gb, 0, 0, true, Some(10 * gb), snap);
|
||||
assert!(matches!(res, Err(IoError::PsdImportBudget { required, limit }) if required == 10 * gb && limit == 9 * gb));
|
||||
assert!(matches!(res, Err(IoError::PsdImportBudget { required, limit, .. }) if required == 10 * gb && limit == 9 * gb));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -413,7 +436,7 @@ fn nested_imports_consume_from_shared_allowance_and_do_not_reset_parent() {
|
||||
|
||||
// Second nested consume exceeds remaining 1 GB
|
||||
let err = crate::psd_gate::consume_attempt_allowance(2 * gb).unwrap_err();
|
||||
assert!(matches!(err, IoError::PsdImportBudget { required, limit } if required == 2 * gb && limit == gb));
|
||||
assert!(matches!(err, IoError::PsdImportBudget { required, limit, .. } if required == 2 * gb && limit == gb));
|
||||
|
||||
// Allowance is still 1 GB (failed attempt does not reset or corrupt parent)
|
||||
assert!(crate::psd_gate::consume_attempt_allowance(gb).is_ok());
|
||||
@@ -472,7 +495,7 @@ fn real_import_propagates_high_memory_approval_and_its_estimate_bound() {
|
||||
let lowered = crate::ImportOptions { psd_high_memory_approved: true, psd_max_pixel_bytes: required - 1, ..Default::default() };
|
||||
assert!(matches!(
|
||||
crate::import_with_options("approval.psd", &bytes, &lowered),
|
||||
Err(IoError::PsdImportBudget { required: r, limit: l }) if r == required && l == required - 1
|
||||
Err(IoError::PsdImportBudget { required: r, limit: l, .. }) if r == required && l == required - 1
|
||||
));
|
||||
});
|
||||
});
|
||||
@@ -527,7 +550,7 @@ fn memory_drop_while_waiting_for_the_gate_refuses_before_decoding() {
|
||||
|
||||
let result = rx.recv_timeout(Duration::from_secs(10)).expect("the post-gate recheck must refuse instead of decoding");
|
||||
match result {
|
||||
Err(IoError::PsdImportBudget { required, limit: 0 }) => assert!(required > 0),
|
||||
Err(IoError::PsdImportBudget { required, limit: 0, .. }) => assert!(required > 0),
|
||||
other => panic!("expected the post-gate recheck to refuse with a zero budget, got {other:?}"),
|
||||
}
|
||||
handle.join().expect("worker thread");
|
||||
|
||||
@@ -79,14 +79,14 @@ pub(crate) fn consume_attempt_allowance(bytes: u64) -> Result<(), IoError> {
|
||||
ATTEMPT_ALLOWANCE.with(|a| match a.get() {
|
||||
Some(remaining) => {
|
||||
if bytes == u64::MAX || bytes > remaining {
|
||||
return Err(IoError::PsdImportBudget { required: bytes, limit: remaining });
|
||||
return Err(IoError::PsdImportBudget { required: bytes, limit: remaining, free_memory: None });
|
||||
}
|
||||
a.set(Some(remaining - bytes));
|
||||
Ok(())
|
||||
}
|
||||
None => {
|
||||
// Unknown allowance during reentrant gate must fail closed.
|
||||
Err(IoError::PsdImportBudget { required: bytes, limit: 0 })
|
||||
Err(IoError::PsdImportBudget { required: bytes, limit: 0, free_memory: None })
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -193,7 +193,7 @@ mod tests {
|
||||
set_active_attempt_budget(u64::MAX);
|
||||
|
||||
let err = consume_attempt_allowance(u64::MAX).expect_err("the overflow sentinel is never a charge");
|
||||
assert!(matches!(err, IoError::PsdImportBudget { required, limit } if required == u64::MAX && limit == u64::MAX));
|
||||
assert!(matches!(err, IoError::PsdImportBudget { required, limit, .. } if required == u64::MAX && limit == u64::MAX));
|
||||
assert_eq!(active_attempt_remaining(), Some(u64::MAX), "a refused sentinel charge leaves the parent's allowance untouched");
|
||||
|
||||
// One byte below the sentinel is an ordinary, enormous charge.
|
||||
|
||||
@@ -1319,7 +1319,7 @@ mod tests {
|
||||
let lowered = ImportOptions { psd_high_memory_approved: true, psd_max_pixel_bytes: required - 1, ..Default::default() };
|
||||
assert!(matches!(
|
||||
crate::import_with_options("l.tif", &bytes, &lowered),
|
||||
Err(IoError::PsdImportBudget { required: r, limit: l }) if r == required && l == required - 1
|
||||
Err(IoError::PsdImportBudget { required: r, limit: l, .. }) if r == required && l == required - 1
|
||||
));
|
||||
});
|
||||
});
|
||||
@@ -1351,7 +1351,7 @@ mod tests {
|
||||
// remaining allowance is untouched.
|
||||
crate::psd_gate::set_active_attempt_budget(charged - 1);
|
||||
match crate::import_with_options_and_interrupt("charge.tif", &bytes, &ImportOptions::default(), &ctl) {
|
||||
Err(IoError::PsdImportBudget { required, limit }) => assert_eq!((required, limit), (charged, charged - 1)),
|
||||
Err(IoError::PsdImportBudget { required, limit, .. }) => assert_eq!((required, limit), (charged, charged - 1)),
|
||||
other => panic!("expected an import-budget refusal, got {other:?}"),
|
||||
}
|
||||
assert_eq!(crate::psd_gate::active_attempt_remaining(), Some(charged - 1), "a failed nested import leaves the allowance as it was");
|
||||
@@ -1462,7 +1462,7 @@ mod tests {
|
||||
crate::memory::with_mock_memory(zero, || {
|
||||
crate::flat::with_before_composite_decode(hook(&decoded), || {
|
||||
match crate::import_with_options("bogus.tif", &bytes, &ImportOptions::default()) {
|
||||
Err(IoError::PsdImportBudget { limit: 0, required }) => assert!(required > 0),
|
||||
Err(IoError::PsdImportBudget { limit: 0, required, .. }) => assert!(required > 0),
|
||||
other => panic!("expected an import-budget refusal, got {other:?}"),
|
||||
}
|
||||
assert_eq!(decoded.get(), 0, "a refused file must not decode its composite");
|
||||
@@ -1504,7 +1504,7 @@ mod tests {
|
||||
crate::memory::with_mock_memory(zero, || {
|
||||
crate::flat::with_before_composite_decode(hook(&decoded), || {
|
||||
match crate::import_with_options("zero.tif", &bytes, &ImportOptions::default()) {
|
||||
Err(IoError::PsdImportBudget { limit: 0, required }) => assert!(required > 0),
|
||||
Err(IoError::PsdImportBudget { limit: 0, required, .. }) => assert!(required > 0),
|
||||
other => panic!("expected an import-budget refusal, got {other:?}"),
|
||||
}
|
||||
assert_eq!(decoded.get(), 0, "a refused file must not decode its composite");
|
||||
@@ -1589,7 +1589,7 @@ mod tests {
|
||||
|
||||
let result = rx.recv_timeout(Duration::from_secs(10)).expect("the post-gate recheck must refuse instead of decoding");
|
||||
match result {
|
||||
Err(IoError::PsdImportBudget { limit: 0, required }) => assert!(required > 0),
|
||||
Err(IoError::PsdImportBudget { limit: 0, required, .. }) => assert!(required > 0),
|
||||
other => panic!("expected the post-gate recheck to refuse with a zero budget, got {other:?}"),
|
||||
}
|
||||
assert!(!decoded.load(Ordering::SeqCst), "the composite must not be decoded after the post-gate refusal");
|
||||
|
||||
@@ -45,6 +45,7 @@ mod pattern_fill_psd;
|
||||
mod pcraft_full_composite;
|
||||
mod pcraft_manifest_name;
|
||||
mod pdn_corpus;
|
||||
mod png_steps;
|
||||
mod png_text_metadata;
|
||||
mod psd16_merged_transparency;
|
||||
mod psd32_export;
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
//! A PNG imported in steps gives the document `import_with_options_and_interrupt` gives.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType, encode};
|
||||
use photocraft_doc::Document;
|
||||
use photocraft_io::{ImportOptions, ImportResult, PngImport, import_with_options_and_interrupt};
|
||||
use photocraft_raster::Interrupt;
|
||||
|
||||
/// A pseudo-random `w`×`h` image.
|
||||
fn noise(w: u32, h: u32, layout: ChannelLayout, sample: SampleType) -> Image {
|
||||
let len = w as usize * h as usize * layout.channels() * sample.bytes();
|
||||
Image::from_raw(w, h, layout, sample, (0..len).map(|i| (i.wrapping_mul(2_654_435_761) >> 11) as u8).collect()).unwrap()
|
||||
}
|
||||
|
||||
fn whole(name: &str, bytes: &[u8]) -> ImportResult {
|
||||
import_with_options_and_interrupt(name, bytes, &ImportOptions::default(), &Interrupt::NONE).unwrap()
|
||||
}
|
||||
|
||||
/// Imports `bytes` in steps, `per_call` rows at a time (0: unlimited); returns the result and
|
||||
/// how many calls it took.
|
||||
fn stepped(name: &str, bytes: &[u8], per_call: usize) -> (ImportResult, usize) {
|
||||
let bytes = Arc::new(bytes.to_vec());
|
||||
let mut import = PngImport::new(name, &bytes).unwrap().expect("a plain PNG");
|
||||
let mut calls = 0;
|
||||
loop {
|
||||
calls += 1;
|
||||
let mut left = per_call;
|
||||
let mut more = || {
|
||||
left = left.wrapping_sub(1);
|
||||
per_call == 0 || left > 0
|
||||
};
|
||||
if let Some(r) = import.step(&mut more).unwrap() {
|
||||
return (r, calls);
|
||||
}
|
||||
assert!(calls < 100_000);
|
||||
}
|
||||
}
|
||||
|
||||
/// The documents are the same but for the ids minted for them.
|
||||
fn assert_same(a: &Document, b: &Document, what: &str) {
|
||||
let (mut a, mut b) = (a.clone(), b.clone());
|
||||
b.id = a.id;
|
||||
assert_eq!(a.layers.len(), b.layers.len(), "{what}");
|
||||
for (x, y) in a.layers.iter_mut().zip(&mut b.layers) {
|
||||
y.id = x.id;
|
||||
}
|
||||
assert!(a == b, "{what}: the documents differ");
|
||||
}
|
||||
|
||||
fn assert_stepped_equals_import(name: &str, bytes: &[u8], what: &str) {
|
||||
let expected = whole(name, bytes);
|
||||
for per_call in [1, 7, 0] {
|
||||
let (got, _) = stepped(name, bytes, per_call);
|
||||
assert_same(&got.document, &expected.document, &format!("{what}, {per_call} rows per call"));
|
||||
assert_eq!(got.warnings, expected.warnings, "{what}");
|
||||
assert_eq!((got.source_read_only, got.preview_only), (expected.source_read_only, expected.preview_only), "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stepped_png_import_equals_import() {
|
||||
for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba] {
|
||||
for sample in [SampleType::U8, SampleType::U16] {
|
||||
let mut img = noise(45, 38, layout, sample);
|
||||
img.meta.dpi = Some((144.0, 144.0));
|
||||
img.meta.text.push(("Comment".into(), "stepped".into()));
|
||||
for interlaced in [false, true] {
|
||||
let bytes = encode(&img, Format::Png, &EncodeOptions { png_interlaced: interlaced, ..Default::default() }).unwrap();
|
||||
assert_stepped_equals_import("a.png", &bytes, &format!("{layout:?} {sample:?} interlaced={interlaced}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stepped_png_import_keeps_a_palette_as_indexed_colour() {
|
||||
let pal = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [9, 9, 9]];
|
||||
let idx: Vec<u8> = (0..40 * 30).map(|i| (i % 4) as u8).collect();
|
||||
let bytes = photocraft_codecs::encode_png_indexed(40, 30, &idx, &pal, Some(3), None, None).unwrap();
|
||||
let (got, _) = stepped("p.png", &bytes, 0);
|
||||
assert!(got.document.color_table.is_some(), "an Indexed Color document");
|
||||
assert_stepped_equals_import("p.png", &bytes, "palette");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stepped_png_import_takes_a_step_per_row_and_bounded_steps_to_build_the_document() {
|
||||
let bytes = encode(&noise(8, 20, ChannelLayout::Rgba, SampleType::U8), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let (_, calls) = stepped("a.png", &bytes, 1);
|
||||
// 19 calls that each decode a row (its rows become tiles as they come), one that decodes the
|
||||
// last row and reads to the end of the file, then the prune scan of the tiles and the document.
|
||||
assert_eq!(calls, 21);
|
||||
let arc = Arc::new(bytes);
|
||||
let mut import = PngImport::new("a.png", &arc).unwrap().unwrap();
|
||||
assert_eq!(import.progress(), 0.0);
|
||||
while import.step(&mut || false).unwrap().is_none() {
|
||||
assert!(import.progress() <= 1.0);
|
||||
}
|
||||
assert!(import.step(&mut || true).is_err(), "a finished import is spent");
|
||||
}
|
||||
|
||||
/// Imports `bytes` with an empty budget (one bounded piece per call); returns the result and the
|
||||
/// number of calls.
|
||||
fn stepped_zero_budget(name: &str, bytes: &[u8]) -> (ImportResult, usize) {
|
||||
let bytes = Arc::new(bytes.to_vec());
|
||||
let mut import = PngImport::new(name, &bytes).unwrap().expect("a plain PNG");
|
||||
let mut calls = 0;
|
||||
loop {
|
||||
calls += 1;
|
||||
if let Some(r) = import.step(&mut || false).unwrap() {
|
||||
return (r, calls);
|
||||
}
|
||||
assert!(calls < 100_000, "the import never finished");
|
||||
}
|
||||
}
|
||||
|
||||
/// A CRC-valid PNG chunk.
|
||||
fn png_chunk(kind: &[u8; 4], data: &[u8]) -> Vec<u8> {
|
||||
let mut crc = flate2::Crc::new();
|
||||
crc.update(kind);
|
||||
crc.update(data);
|
||||
let mut out = u32::try_from(data.len()).unwrap().to_be_bytes().to_vec();
|
||||
out.extend_from_slice(kind);
|
||||
out.extend_from_slice(data);
|
||||
out.extend_from_slice(&crc.sum().to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// A compressed `zTXt` chunk with `text` as its value.
|
||||
fn ztxt_chunk(keyword: &[u8], text: &[u8]) -> Vec<u8> {
|
||||
use std::io::Write;
|
||||
let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
encoder.write_all(text).unwrap();
|
||||
let packed = encoder.finish().unwrap();
|
||||
let mut data = keyword.to_vec();
|
||||
data.extend_from_slice(&[0, 0]);
|
||||
data.extend_from_slice(&packed);
|
||||
png_chunk(b"zTXt", &data)
|
||||
}
|
||||
|
||||
/// `png` with `chunks` between the image data and `IEND`.
|
||||
fn with_chunks_before_iend(png: &[u8], chunks: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut at = 8;
|
||||
loop {
|
||||
let len = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize;
|
||||
if &png[at + 4..at + 8] == b"IEND" {
|
||||
let mut out = png[..at].to_vec();
|
||||
for c in chunks {
|
||||
out.extend_from_slice(c);
|
||||
}
|
||||
out.extend_from_slice(&png[at..]);
|
||||
return out;
|
||||
}
|
||||
at += len + 12;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stepped_png_import_copies_a_multi_tile_image_in_bounded_steps() {
|
||||
// Four tiles (300 × 260 at 256 px), with a compressed text chunk after the image data.
|
||||
let mut img = noise(300, 260, ChannelLayout::Rgba, SampleType::U16);
|
||||
img.meta.dpi = Some((240.0, 240.0));
|
||||
let base = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let text = "A".repeat(120_000);
|
||||
let bytes = with_chunks_before_iend(&base, &[ztxt_chunk(b"Comment", text.as_bytes())]);
|
||||
assert_stepped_equals_import("tiles.png", &bytes, "multi-tile with compressed text");
|
||||
|
||||
let expected = whole("tiles.png", &bytes);
|
||||
let (got, calls) = stepped_zero_budget("tiles.png", &bytes);
|
||||
assert_same(&got.document, &expected.document, "zero budget");
|
||||
assert_eq!(got.warnings, expected.warnings);
|
||||
assert_eq!(got.document.metadata.text, vec![("Comment".into(), text)], "the compressed text survives the steps");
|
||||
// One call per row, then its copy bands, its prune batch and the document step, each a call
|
||||
// of its own with an empty budget.
|
||||
assert!(calls >= 260 + 4, "{} calls: an empty budget must not make one step do it all", calls);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_plain_png_is_stepped() {
|
||||
let png = Arc::new(encode(&noise(4, 4, ChannelLayout::Rgb, SampleType::U8), Format::Png, &EncodeOptions::default()).unwrap());
|
||||
assert!(PngImport::new("a.png", &png).unwrap().is_some());
|
||||
// The same bytes under a name that sends them to another importer, or another format.
|
||||
assert!(PngImport::new("a.pcraft", &png).unwrap().is_none());
|
||||
let jpeg = Arc::new(encode(&noise(4, 4, ChannelLayout::Rgb, SampleType::U8), Format::Jpeg, &EncodeOptions::default()).unwrap());
|
||||
assert!(PngImport::new("a.jpg", &jpeg).unwrap().is_none());
|
||||
assert!(PngImport::new("a.svg", &Arc::new(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>".to_vec())).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_png_fails_in_steps_as_it_does_whole() {
|
||||
let bytes = encode(&noise(64, 64, ChannelLayout::Rgb, SampleType::U8), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
for cut in [30, bytes.len() / 2] {
|
||||
let cut = Arc::new(bytes.get(..cut).unwrap().to_vec());
|
||||
let whole = import_with_options_and_interrupt("a.png", &cut, &ImportOptions::default(), &Interrupt::NONE);
|
||||
let stepped = PngImport::new("a.png", &cut).and_then(|import| {
|
||||
let mut import = import.expect("a PNG by its signature");
|
||||
loop {
|
||||
if let Some(r) = import.step(&mut || true)? {
|
||||
return Ok(r);
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(whole.is_err() && stepped.is_err(), "cut at {}", cut.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// An `eXIf` chunk (little-endian) holding only the orientation `o`.
|
||||
fn exif_chunk(o: u16) -> Vec<u8> {
|
||||
let mut t = b"II*\0".to_vec();
|
||||
t.extend_from_slice(&8u32.to_le_bytes());
|
||||
t.extend_from_slice(&1u16.to_le_bytes());
|
||||
for v in [0x0112u16, 3] {
|
||||
t.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
t.extend_from_slice(&1u32.to_le_bytes());
|
||||
t.extend_from_slice(&o.to_le_bytes());
|
||||
t.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
|
||||
png_chunk(b"eXIf", &t)
|
||||
}
|
||||
|
||||
/// `png` with `chunk` just before its image data.
|
||||
fn with_chunk_before_idat(png: &[u8], chunk: &[u8]) -> Vec<u8> {
|
||||
let at = png.windows(4).position(|w| w == b"IDAT").unwrap() - 4;
|
||||
let mut out = png[..at].to_vec();
|
||||
out.extend_from_slice(chunk);
|
||||
out.extend_from_slice(&png[at..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Drives `bytes` to the end a row at a time; true if the import streamed at the start.
|
||||
fn streams_at_start(bytes: &[u8]) -> bool {
|
||||
let bytes = Arc::new(bytes.to_vec());
|
||||
PngImport::new("a.png", &bytes).unwrap().unwrap().streams()
|
||||
}
|
||||
|
||||
/// A plain PNG streams its rows into the layer; a file that can't (interlaced, or stored in
|
||||
/// another orientation) is decoded whole.
|
||||
#[test]
|
||||
fn a_plain_png_streams_and_other_files_are_decoded_whole() {
|
||||
let img = noise(40, 30, ChannelLayout::Rgb, SampleType::U8);
|
||||
let plain = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert!(streams_at_start(&plain));
|
||||
let interlaced = encode(&img, Format::Png, &EncodeOptions { png_interlaced: true, ..Default::default() }).unwrap();
|
||||
assert!(!streams_at_start(&interlaced));
|
||||
assert!(!streams_at_start(&with_chunk_before_idat(&plain, &exif_chunk(6))));
|
||||
// An upright eXIf streams; one after the image data is only seen at the end.
|
||||
assert!(streams_at_start(&with_chunk_before_idat(&plain, &exif_chunk(1))));
|
||||
assert!(streams_at_start(&with_chunks_before_iend(&plain, &[exif_chunk(6)])));
|
||||
}
|
||||
|
||||
/// A file with an orientation turns upright in bands and gives the document the one-shot import
|
||||
/// gives, whether the `eXIf` comes before the image data (decoded whole from the start) or after
|
||||
/// it (streamed, then decoded whole), for every orientation, and a tall file takes many calls.
|
||||
#[test]
|
||||
fn an_oriented_png_is_turned_upright_in_steps_like_import() {
|
||||
for (layout, sample) in [(ChannelLayout::Gray, SampleType::U8), (ChannelLayout::Rgba, SampleType::U16)] {
|
||||
let mut img = noise(70, 150, layout, sample);
|
||||
img.meta.dpi = Some((120.0, 120.0));
|
||||
img.icc = Some(vec![7; 40]);
|
||||
let base = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
for o in 2..=8u16 {
|
||||
for late in [false, true] {
|
||||
let bytes = if late { with_chunks_before_iend(&base, &[exif_chunk(o)]) } else { with_chunk_before_idat(&base, &exif_chunk(o)) };
|
||||
let what = format!("{layout:?} {sample:?} orientation {o}, eXIf {}", if late { "after" } else { "before" });
|
||||
let expected = whole("o.png", &bytes);
|
||||
assert_eq!(expected.document.size.width, if o >= 5 { 150 } else { 70 }, "{what}: upright");
|
||||
let (got, calls) = stepped_zero_budget("o.png", &bytes);
|
||||
assert_same(&got.document, &expected.document, &what);
|
||||
assert_eq!(got.warnings, expected.warnings, "{what}");
|
||||
// 150 rows decoded one call each, the turn in bands of 64 output rows, the copy.
|
||||
assert!(calls > 150 + 2, "{what}: {calls} calls");
|
||||
assert_stepped_equals_import("o.png", &bytes, &what);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A late `eXIf` sends a streamed import back to a whole decode, and the import says so.
|
||||
#[test]
|
||||
fn a_late_exif_ends_the_streaming() {
|
||||
let base = encode(&noise(20, 20, ChannelLayout::Rgb, SampleType::U8), Format::Png, &EncodeOptions::default()).unwrap();
|
||||
let bytes = Arc::new(with_chunks_before_iend(&base, &[exif_chunk(3)]));
|
||||
let mut import = PngImport::new("a.png", &bytes).unwrap().unwrap();
|
||||
assert!(import.streams());
|
||||
while import.streams() {
|
||||
assert!(import.step(&mut || false).unwrap().is_none());
|
||||
}
|
||||
// From here the whole image is decoded.
|
||||
assert!(import.step(&mut || false).unwrap().is_none());
|
||||
assert!(!import.streams());
|
||||
}
|
||||
|
||||
/// A streamed import with an ICC profile, text and a resolution is the one-shot import, at every
|
||||
/// depth and layout, 16-bit included.
|
||||
#[test]
|
||||
fn a_streamed_png_with_a_profile_and_text_equals_import() {
|
||||
for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba] {
|
||||
for sample in [SampleType::U8, SampleType::U16] {
|
||||
let mut img = noise(300, 270, layout, sample);
|
||||
img.icc = Some(vec![9; 60]);
|
||||
img.meta.dpi = Some((200.0, 200.0));
|
||||
img.meta.text.push(("Title".into(), "streamed".into()));
|
||||
let bytes = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert!(streams_at_start(&bytes));
|
||||
assert_stepped_equals_import("s.png", &bytes, &format!("{layout:?} {sample:?} with a profile"));
|
||||
let (got, _) = stepped("s.png", &bytes, 0);
|
||||
assert_eq!(got.document.icc_profile.as_deref().map(Vec::as_slice), Some(&[9u8; 60][..]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,11 +15,19 @@ crc32fast = "1"
|
||||
lz4_flex = { version = "0.11", default-features = false, features = ["std", "safe-encode", "safe-decode"] }
|
||||
|
||||
# Native only: converting a region's tiles is independent per tile, so it runs on all cores;
|
||||
# sysinfo reads the physical RAM size for the memory limit and the scratch volume's free space.
|
||||
# sysinfo reads the physical RAM size for the memory limit.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
rayon = { workspace = true }
|
||||
sysinfo = { version = "=0.40.1", default-features = false, features = ["system"] }
|
||||
|
||||
# macOS reports capacity including purgeable space only through sysinfo's volume properties.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
sysinfo = { version = "=0.40.1", default-features = false, features = ["system", "disk"] }
|
||||
|
||||
# statvfs on the scratch directory.
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
|
||||
|
||||
# Available physical memory and commit headroom (memory/system.rs) through winsafe's safe
|
||||
# `GlobalMemoryStatusEx` wrapper.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
|
||||
+58
-137
@@ -11,10 +11,12 @@ pub mod headroom;
|
||||
mod interrupt;
|
||||
pub use interrupt::{Cancelled, Interrupt};
|
||||
pub mod scratch;
|
||||
mod shift;
|
||||
pub use shift::TranslateSteps;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::ops::{Bound, Deref, DerefMut};
|
||||
use std::sync::{Arc, RwLockReadGuard, RwLockWriteGuard};
|
||||
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType, read_sample, read_samples, write_sample};
|
||||
@@ -274,6 +276,20 @@ fn last_difference(a: &[u8], b: &[u8]) -> Option<usize> {
|
||||
x.iter().zip(y).rposition(|(p, q)| p != q).map(|i| k * DIFF_BLOCK + i)
|
||||
}
|
||||
|
||||
/// Where [`Surface::prune_batch`] resumes: after the last tile it visited.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PruneCursor {
|
||||
after: Option<TileCoord>,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl PruneCursor {
|
||||
/// True once every tile has been visited.
|
||||
pub fn is_done(&self) -> bool {
|
||||
self.done
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Surface {
|
||||
format: PixelFormat,
|
||||
@@ -776,6 +792,43 @@ impl Surface {
|
||||
self.tiles.retain(|_, t| t.bytes().chunks_exact(bpp).any(|px| px != dp));
|
||||
}
|
||||
|
||||
/// A [`PruneCursor`] for [`Surface::prune_batch`], which drops the same tiles as [`Surface::prune`]
|
||||
/// a batch at a time (for a caller that must not block: the web build has no threads).
|
||||
pub fn prune_cursor(&self) -> PruneCursor {
|
||||
PruneCursor::default()
|
||||
}
|
||||
|
||||
/// Drops the tiles that are entirely the default pixel, visiting at most `max` tiles in
|
||||
/// coordinate order and resuming after them on the next call; returns true when every tile
|
||||
/// has been visited (and so [`Surface::prune`] has nothing left to drop). A `max` of zero
|
||||
/// visits one tile. The scan reads the live tile map from the cursor on: a tile inserted at or
|
||||
/// before the last visited coordinate is not visited, one inserted after it is (and dropped
|
||||
/// when it holds only the default pixel, which reads the same as an absent tile).
|
||||
pub fn prune_batch(&mut self, cursor: &mut PruneCursor, max: usize) -> bool {
|
||||
if cursor.done {
|
||||
return true;
|
||||
}
|
||||
let dp = self.default_pixel.as_ref();
|
||||
let bpp = dp.len();
|
||||
let max = max.max(1);
|
||||
let keys: Vec<TileCoord> = match cursor.after {
|
||||
None => self.tiles.keys().take(max).copied().collect(),
|
||||
Some(after) => self.tiles.range((Bound::Excluded(after), Bound::Unbounded)).take(max).map(|(c, _)| *c).collect(),
|
||||
};
|
||||
for c in &keys {
|
||||
if self.tiles.get(c).is_some_and(|t| !t.bytes().chunks_exact(bpp).any(|px| px != dp)) {
|
||||
self.tiles.remove(c);
|
||||
}
|
||||
}
|
||||
let Some(last) = keys.last().copied() else {
|
||||
cursor.done = true;
|
||||
return true;
|
||||
};
|
||||
cursor.after = Some(last);
|
||||
cursor.done = keys.len() < max || self.tiles.range((Bound::Excluded(last), Bound::Unbounded)).next().is_none();
|
||||
cursor.done
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn locate(&self, x: i32, y: i32) -> (TileCoord, usize) {
|
||||
let c = TileCoord::containing(x, y);
|
||||
@@ -1262,144 +1315,12 @@ impl Surface {
|
||||
out.tiles = sources().map(|(c, t)| (TileCoord::new(c.tx.saturating_add(tx), c.ty.saturating_add(ty)), t.clone())).collect();
|
||||
return out;
|
||||
}
|
||||
let bpp = self.format.bytes_per_pixel();
|
||||
let moved = content.translate(dx, dy);
|
||||
let targets: std::collections::BTreeSet<TileCoord> = sources().flat_map(|(c, _)| c.rect().translate(dx, dy).intersect(&moved).tiles()).collect();
|
||||
let mut uniform = UniformTiles::default();
|
||||
let mut builder = shift::ShiftBuilder::new(self, dx, dy, content);
|
||||
for (_, t) in sources() {
|
||||
uniform.value_of(t, bpp);
|
||||
builder.scan(t);
|
||||
}
|
||||
// The fill row: one tile row of the default pixel, so the regions a shift vacates
|
||||
// fill with bulk copies (empty when the default is zero — the tile starts zeroed).
|
||||
|
||||
// One row of the default pixel, so the regions a shift vacates fill with bulk copies.
|
||||
let fill_row: Vec<u8> = if self.default_pixel.iter().any(|&b| b != 0) {
|
||||
let mut row = Vec::with_capacity(TILE_SIZE as usize * bpp);
|
||||
for _ in 0..TILE_SIZE {
|
||||
row.extend_from_slice(&self.default_pixel);
|
||||
}
|
||||
row
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
// One tile row of the default pixel, to compare a finished tile with a row at a time.
|
||||
let default_row = self.default_pixel.repeat(TILE_SIZE.unsigned_abs() as usize);
|
||||
// Target tiles rebuilt from the same source tiles at the same offset are the same tile:
|
||||
// a bundle can point thousands of tile references at one payload, and a move would
|
||||
// otherwise copy it into a separate buffer for each.
|
||||
let built: std::sync::Mutex<std::collections::HashMap<Vec<usize>, Option<Arc<Tile>>>> = Default::default();
|
||||
let build_target = |dc: TileCoord| -> Option<(TileCoord, Arc<Tile>)> {
|
||||
let dr = dc.rect();
|
||||
let sr = dr.translate(dx.saturating_neg(), dy.saturating_neg());
|
||||
// Every pixel of the target comes from a source tile (none from the default pixel).
|
||||
// `sr` must be the exact preimage: an offset of `i32::MIN` saturates its negation.
|
||||
let covered = sr.width() == TILE_SIZE.unsigned_abs()
|
||||
&& sr.height() == TILE_SIZE.unsigned_abs()
|
||||
&& sr.translate(dx, dy) == dr
|
||||
&& content.contains_rect(&sr)
|
||||
&& sr.tiles().all(|sc| self.tiles.contains_key(&sc));
|
||||
if covered && let Some(shared) = uniform.window(self, sr) {
|
||||
// A tile of only the default pixel is left out, as `prune` would.
|
||||
let keep = shared.bytes().get(..bpp) != Some(&*self.default_pixel);
|
||||
return keep.then_some((dc, shared));
|
||||
}
|
||||
// The identities of the source tiles under a covered window (the offset is the same
|
||||
// for every target of this call).
|
||||
let memo_key: Option<Vec<usize>> = covered.then(|| sr.tiles().map(|sc| self.tiles.get(&sc).map_or(0, |t| Arc::as_ptr(t) as usize)).collect());
|
||||
if let Some(k) = &memo_key
|
||||
&& let Some(hit) = built.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(k)
|
||||
{
|
||||
return hit.clone().map(|t| (dc, t));
|
||||
}
|
||||
|
||||
let mut data = scratch::take_exact((TILE_SIZE * TILE_SIZE) as usize * bpp, 0u8);
|
||||
let (tx0, ty0) = (i64::from(dc.tx) * i64::from(TILE_SIZE), i64::from(dc.ty) * i64::from(TILE_SIZE));
|
||||
let row_len = TILE_SIZE as usize * bpp;
|
||||
// Per stored row: copy the source span that falls inside the content in as few
|
||||
// memcpys as the tile grid allows, and fill the vacated edges from the default
|
||||
// row — no whole-tile pre-fill, which rewrote nearly every byte twice.
|
||||
for local_y in 0..i64::from(TILE_SIZE) {
|
||||
let y = ty0 + local_y;
|
||||
let Some(row) = data.get_mut(local_y as usize * row_len..(local_y as usize + 1) * row_len) else { continue };
|
||||
let in_content_y = y - i64::from(dy) >= i64::from(content.y0) && y - i64::from(dy) < i64::from(content.y1);
|
||||
// The row's target columns whose SOURCE lies inside the content are copied
|
||||
// (the copy loop crosses source tiles as needed); the rest stays default —
|
||||
// exactly the pixels the shift vacated.
|
||||
let cx0 = (i64::from(content.x0) + i64::from(dx)).max(tx0);
|
||||
let cx1 = (i64::from(content.x1) + i64::from(dx)).min(tx0 + i64::from(TILE_SIZE));
|
||||
if !in_content_y || cx1 <= cx0 {
|
||||
if !fill_row.is_empty() {
|
||||
row.copy_from_slice(&fill_row);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let left = (cx0.max(tx0) - tx0) as usize * bpp;
|
||||
let copied_end = (cx1.min(tx0 + i64::from(TILE_SIZE)) - tx0) as usize * bpp;
|
||||
if !fill_row.is_empty() {
|
||||
if left > 0 {
|
||||
row[..left].copy_from_slice(&fill_row[..left]);
|
||||
}
|
||||
if copied_end < row_len {
|
||||
row[copied_end..].copy_from_slice(&fill_row[copied_end..]);
|
||||
}
|
||||
}
|
||||
let mut x = cx0.max(tx0);
|
||||
let x_end = cx1.min(tx0 + i64::from(TILE_SIZE));
|
||||
// Rows run over the same one or two source tiles: cache the last lookup.
|
||||
let mut cached: Option<(i64, i64, TileBytes<'_>)> = None;
|
||||
while x < x_end {
|
||||
// The source document position this target column reads, and the source
|
||||
// tile it lives in (the shift crosses source tiles as x runs).
|
||||
let (sx, sy) = (x - i64::from(dx), y - i64::from(dy));
|
||||
let (tx, ty) = (sx.div_euclid(i64::from(TILE_SIZE)), sy.div_euclid(i64::from(TILE_SIZE)));
|
||||
// A missing source tile inside the content holds the default pixel, not
|
||||
// zeros: fill the span from the default row instead of skipping it
|
||||
// (echelon's white-mask-with-sparse-tiles case).
|
||||
if !matches!(&cached, Some((ctx, cty, _)) if *ctx == tx && *cty == ty) {
|
||||
match self.tiles.get(&TileCoord::new(tx as i32, ty as i32)) {
|
||||
Some(t) => cached = Some((tx, ty, t.bytes())),
|
||||
None => {
|
||||
let span_end = ((tx + 1) * i64::from(TILE_SIZE) + i64::from(dx)).min(x_end).max(x + 1);
|
||||
if !fill_row.is_empty() {
|
||||
let at = (x - tx0) as usize * bpp;
|
||||
let len = (span_end - x) as usize * bpp;
|
||||
if let Some(d) = row.get_mut(at..at + len) {
|
||||
d.copy_from_slice(&fill_row[at..at + len]);
|
||||
}
|
||||
}
|
||||
x = span_end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, _, st)) = &cached else { break };
|
||||
let span_end = (((tx + 1) * i64::from(TILE_SIZE) + i64::from(dx)).min(x_end)).max(x + 1);
|
||||
let span = (span_end - x) as usize * bpp;
|
||||
let src = ((sy - ty * i64::from(TILE_SIZE)) * row_len as i64 + (sx - tx * i64::from(TILE_SIZE)) * bpp as i64) as usize;
|
||||
let dst = (x - tx0) as usize * bpp;
|
||||
if let (Some(d), Some(sr)) = (row.get_mut(dst..dst + span), st.get(src..src + span)) {
|
||||
d.copy_from_slice(sr);
|
||||
}
|
||||
x = span_end;
|
||||
}
|
||||
}
|
||||
// A target that got only default pixels isn't stored, as `prune` would drop it. Checked
|
||||
// after the copy, a row at a time: a tile with content stops at its first such row.
|
||||
let finished = if data.chunks(default_row.len()).any(|row| row != default_row) {
|
||||
Some(Arc::new(Tile::from_vec(data)))
|
||||
} else {
|
||||
scratch::give(data);
|
||||
None
|
||||
};
|
||||
// Workers that missed the memo at the same time each built a copy: all of them take
|
||||
// the one stored first, so the targets share it however many threads raced.
|
||||
let finished = match memo_key {
|
||||
Some(k) => built.lock().unwrap_or_else(std::sync::PoisonError::into_inner).entry(k).or_insert(finished).clone(),
|
||||
None => finished,
|
||||
};
|
||||
finished.map(|t| (dc, t))
|
||||
};
|
||||
let targets = builder.targets(self);
|
||||
let build_target = |dc: TileCoord| builder.build(self, dc);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
|
||||
@@ -21,7 +21,7 @@ use std::fs::File;
|
||||
use std::path::{Path, PathBuf};
|
||||
#[cfg(windows)]
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
|
||||
const ALIGN: u64 = 4096;
|
||||
@@ -48,6 +48,7 @@ pub(crate) struct Allocator {
|
||||
|
||||
impl Allocator {
|
||||
/// Bytes currently allocated (end of file minus free space).
|
||||
#[cfg(test)]
|
||||
pub fn used(&self) -> u64 {
|
||||
self.end - self.by_offset.values().sum::<u64>()
|
||||
}
|
||||
@@ -108,6 +109,9 @@ pub(crate) struct ScratchFile {
|
||||
#[cfg(not(windows))]
|
||||
linked: bool,
|
||||
allocator: Mutex<Allocator>,
|
||||
/// What [`ScratchFile::used`] reads. No lock: `free` truncates the file under the allocator lock,
|
||||
/// and a dead folder would block that, so a status read must not wait for it.
|
||||
used: AtomicU64,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ScratchFile {
|
||||
@@ -129,6 +133,7 @@ impl ScratchFile {
|
||||
#[cfg(not(windows))]
|
||||
linked,
|
||||
allocator: Mutex::new(Allocator::default()),
|
||||
used: AtomicU64::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -145,6 +150,7 @@ impl ScratchFile {
|
||||
pub fn write(&self, data: &[u8]) -> std::io::Result<Extent> {
|
||||
let len = u32::try_from(data.len()).map_err(|_| std::io::Error::other("block larger than 4 GiB"))?;
|
||||
let mut extent = self.lock().alloc(len);
|
||||
self.used.fetch_add(extent.alloc, Ordering::Relaxed);
|
||||
if let Err(e) = write_all_at(&self.main, data, extent.offset) {
|
||||
self.free(extent);
|
||||
return Err(e);
|
||||
@@ -164,6 +170,7 @@ impl ScratchFile {
|
||||
}
|
||||
|
||||
pub fn free(&self, extent: Extent) {
|
||||
self.used.fetch_sub(extent.alloc, Ordering::Relaxed);
|
||||
let mut allocator = self.lock();
|
||||
allocator.free(extent);
|
||||
if allocator.end == 0 {
|
||||
@@ -175,7 +182,7 @@ impl ScratchFile {
|
||||
}
|
||||
|
||||
pub fn used(&self) -> u64 {
|
||||
self.lock().used()
|
||||
self.used.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, Allocator> {
|
||||
@@ -483,6 +490,23 @@ mod tests {
|
||||
assert_eq!(a.alloc(10).offset, 4096, "remainder of the split hole is used next");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn used_follows_writes_and_frees() {
|
||||
let dir = std::env::temp_dir().join(format!("pc-scratch-used-{}", std::process::id()));
|
||||
let scratch = ScratchFile::create(&dir).unwrap();
|
||||
assert_eq!(scratch.used(), 0);
|
||||
let a = scratch.write(b"one").unwrap();
|
||||
assert_eq!(scratch.used(), a.alloc);
|
||||
let b = scratch.write(&[1u8; 9000]).unwrap();
|
||||
assert_eq!(scratch.used(), a.alloc + b.alloc);
|
||||
scratch.free(a);
|
||||
assert_eq!(scratch.used(), b.alloc);
|
||||
scratch.free(b);
|
||||
assert_eq!(scratch.used(), 0);
|
||||
drop(scratch);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_roundtrip_and_crc() {
|
||||
let dir = std::env::temp_dir().join("photocraft-scratch-test");
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
//! [`Surface::translated`] in pieces: the target tiles of a shift by a whole number of pixels
|
||||
//! that is not a whole number of tiles, each built from the source tiles it reads. The one-shot
|
||||
//! call and [`TranslateSteps`] build every tile with the same code, so their results are equal.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use photocraft_geom::{Rect, TILE_SIZE, TileCoord};
|
||||
|
||||
use super::{Surface, Tile, TileBytes, UniformTiles, scratch};
|
||||
|
||||
/// What the target tiles of one shift share: the offset, the source's content bounds, rows of the
|
||||
/// default pixel, which source tiles are one solid value, and the tiles already built.
|
||||
pub(super) struct ShiftBuilder {
|
||||
dx: i32,
|
||||
dy: i32,
|
||||
content: Rect,
|
||||
bpp: usize,
|
||||
default_pixel: Box<[u8]>,
|
||||
/// One row of the default pixel, so the regions a shift vacates fill with bulk copies (empty
|
||||
/// when the default is zero: the tile starts zeroed).
|
||||
fill_row: Vec<u8>,
|
||||
/// One tile row of the default pixel, to compare a finished tile with a row at a time.
|
||||
default_row: Vec<u8>,
|
||||
pub(super) uniform: UniformTiles,
|
||||
/// Target tiles rebuilt from the same source tiles at the same offset are the same tile: a
|
||||
/// bundle can point thousands of tile references at one payload, and a move would otherwise
|
||||
/// copy it into a separate buffer for each.
|
||||
built: Mutex<HashMap<Vec<usize>, Option<Arc<Tile>>>>,
|
||||
}
|
||||
|
||||
impl ShiftBuilder {
|
||||
/// A builder for shifting `src` by (`dx`, `dy`); `content` must hold every pixel of `src`
|
||||
/// that isn't the default one.
|
||||
pub(super) fn new(src: &Surface, dx: i32, dy: i32, content: Rect) -> Self {
|
||||
let bpp = src.format.bytes_per_pixel();
|
||||
let fill_row: Vec<u8> = if src.default_pixel.iter().any(|&b| b != 0) {
|
||||
let mut row = Vec::with_capacity(TILE_SIZE as usize * bpp);
|
||||
for _ in 0..TILE_SIZE {
|
||||
row.extend_from_slice(&src.default_pixel);
|
||||
}
|
||||
row
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
Self {
|
||||
dx,
|
||||
dy,
|
||||
content,
|
||||
bpp,
|
||||
default_pixel: src.default_pixel.clone(),
|
||||
fill_row,
|
||||
default_row: src.default_pixel.repeat(TILE_SIZE.unsigned_abs() as usize),
|
||||
uniform: UniformTiles::default(),
|
||||
built: Mutex::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The source tiles that can hold content, in coordinate order.
|
||||
pub(super) fn sources(src: &Surface, content: Rect) -> impl Iterator<Item = (&TileCoord, &Arc<Tile>)> {
|
||||
src.tiles.iter().filter(move |(c, _)| !c.rect().intersect(&content).is_empty())
|
||||
}
|
||||
|
||||
/// Notes whether source tile `t` is one solid value, so targets reading only such tiles share
|
||||
/// one tile.
|
||||
pub(super) fn scan(&mut self, t: &Arc<Tile>) {
|
||||
self.uniform.value_of(t, self.bpp);
|
||||
}
|
||||
|
||||
/// The target tiles: every tile a source tile's pixels land on.
|
||||
pub(super) fn targets(&self, src: &Surface) -> BTreeSet<TileCoord> {
|
||||
let (dx, dy) = (self.dx, self.dy);
|
||||
let moved = self.content.translate(dx, dy);
|
||||
Self::sources(src, self.content).flat_map(|(c, _)| c.rect().translate(dx, dy).intersect(&moved).tiles()).collect()
|
||||
}
|
||||
|
||||
/// Builds target tile `dc` of `src` shifted; `None` when it would hold only the default pixel.
|
||||
pub(super) fn build(&self, src: &Surface, dc: TileCoord) -> Option<(TileCoord, Arc<Tile>)> {
|
||||
let (dx, dy, content, bpp) = (self.dx, self.dy, self.content, self.bpp);
|
||||
let (fill_row, default_row, built, uniform) = (&self.fill_row, &self.default_row, &self.built, &self.uniform);
|
||||
let dr = dc.rect();
|
||||
let sr = dr.translate(dx.saturating_neg(), dy.saturating_neg());
|
||||
// Every pixel of the target comes from a source tile (none from the default pixel).
|
||||
// `sr` must be the exact preimage: an offset of `i32::MIN` saturates its negation.
|
||||
let covered = sr.width() == TILE_SIZE.unsigned_abs()
|
||||
&& sr.height() == TILE_SIZE.unsigned_abs()
|
||||
&& sr.translate(dx, dy) == dr
|
||||
&& content.contains_rect(&sr)
|
||||
&& sr.tiles().all(|sc| src.tiles.contains_key(&sc));
|
||||
if covered && let Some(shared) = uniform.window(src, sr) {
|
||||
// A tile of only the default pixel is left out, as `prune` would.
|
||||
let keep = shared.bytes().get(..bpp) != Some(&*self.default_pixel);
|
||||
return keep.then_some((dc, shared));
|
||||
}
|
||||
// The identities of the source tiles under a covered window (the offset is the same
|
||||
// for every target of this call).
|
||||
let memo_key: Option<Vec<usize>> = covered.then(|| sr.tiles().map(|sc| src.tiles.get(&sc).map_or(0, |t| Arc::as_ptr(t) as usize)).collect());
|
||||
if let Some(k) = &memo_key
|
||||
&& let Some(hit) = built.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(k)
|
||||
{
|
||||
return hit.clone().map(|t| (dc, t));
|
||||
}
|
||||
|
||||
let mut data = scratch::take_exact((TILE_SIZE * TILE_SIZE) as usize * bpp, 0u8);
|
||||
let (tx0, ty0) = (i64::from(dc.tx) * i64::from(TILE_SIZE), i64::from(dc.ty) * i64::from(TILE_SIZE));
|
||||
let row_len = TILE_SIZE as usize * bpp;
|
||||
// Per stored row: copy the source span that falls inside the content in as few
|
||||
// memcpys as the tile grid allows, and fill the vacated edges from the default
|
||||
// row — no whole-tile pre-fill, which rewrote nearly every byte twice.
|
||||
for local_y in 0..i64::from(TILE_SIZE) {
|
||||
let y = ty0 + local_y;
|
||||
let Some(row) = data.get_mut(local_y as usize * row_len..(local_y as usize + 1) * row_len) else { continue };
|
||||
let in_content_y = y - i64::from(dy) >= i64::from(content.y0) && y - i64::from(dy) < i64::from(content.y1);
|
||||
// The row's target columns whose SOURCE lies inside the content are copied
|
||||
// (the copy loop crosses source tiles as needed); the rest stays default —
|
||||
// exactly the pixels the shift vacated.
|
||||
let cx0 = (i64::from(content.x0) + i64::from(dx)).max(tx0);
|
||||
let cx1 = (i64::from(content.x1) + i64::from(dx)).min(tx0 + i64::from(TILE_SIZE));
|
||||
if !in_content_y || cx1 <= cx0 {
|
||||
if !fill_row.is_empty() {
|
||||
row.copy_from_slice(fill_row);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let left = (cx0.max(tx0) - tx0) as usize * bpp;
|
||||
let copied_end = (cx1.min(tx0 + i64::from(TILE_SIZE)) - tx0) as usize * bpp;
|
||||
if !fill_row.is_empty() {
|
||||
if left > 0 {
|
||||
row[..left].copy_from_slice(&fill_row[..left]);
|
||||
}
|
||||
if copied_end < row_len {
|
||||
row[copied_end..].copy_from_slice(&fill_row[copied_end..]);
|
||||
}
|
||||
}
|
||||
let mut x = cx0.max(tx0);
|
||||
let x_end = cx1.min(tx0 + i64::from(TILE_SIZE));
|
||||
// Rows run over the same one or two source tiles: cache the last lookup.
|
||||
let mut cached: Option<(i64, i64, TileBytes<'_>)> = None;
|
||||
while x < x_end {
|
||||
// The source document position this target column reads, and the source
|
||||
// tile it lives in (the shift crosses source tiles as x runs).
|
||||
let (sx, sy) = (x - i64::from(dx), y - i64::from(dy));
|
||||
let (tx, ty) = (sx.div_euclid(i64::from(TILE_SIZE)), sy.div_euclid(i64::from(TILE_SIZE)));
|
||||
// A missing source tile inside the content holds the default pixel, not
|
||||
// zeros: fill the span from the default row instead of skipping it
|
||||
// (echelon's white-mask-with-sparse-tiles case).
|
||||
if !matches!(&cached, Some((ctx, cty, _)) if *ctx == tx && *cty == ty) {
|
||||
match src.tiles.get(&TileCoord::new(tx as i32, ty as i32)) {
|
||||
Some(t) => cached = Some((tx, ty, t.bytes())),
|
||||
None => {
|
||||
let span_end = ((tx + 1) * i64::from(TILE_SIZE) + i64::from(dx)).min(x_end).max(x + 1);
|
||||
if !fill_row.is_empty() {
|
||||
let at = (x - tx0) as usize * bpp;
|
||||
let len = (span_end - x) as usize * bpp;
|
||||
if let Some(d) = row.get_mut(at..at + len) {
|
||||
d.copy_from_slice(&fill_row[at..at + len]);
|
||||
}
|
||||
}
|
||||
x = span_end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, _, st)) = &cached else { break };
|
||||
let span_end = (((tx + 1) * i64::from(TILE_SIZE) + i64::from(dx)).min(x_end)).max(x + 1);
|
||||
let span = (span_end - x) as usize * bpp;
|
||||
let src = ((sy - ty * i64::from(TILE_SIZE)) * row_len as i64 + (sx - tx * i64::from(TILE_SIZE)) * bpp as i64) as usize;
|
||||
let dst = (x - tx0) as usize * bpp;
|
||||
if let (Some(d), Some(sr)) = (row.get_mut(dst..dst + span), st.get(src..src + span)) {
|
||||
d.copy_from_slice(sr);
|
||||
}
|
||||
x = span_end;
|
||||
}
|
||||
}
|
||||
// A target that got only default pixels isn't stored, as `prune` would drop it. Checked
|
||||
// after the copy, a row at a time: a tile with content stops at its first such row.
|
||||
let finished = if data.chunks(default_row.len()).any(|row| row != default_row) {
|
||||
Some(Arc::new(Tile::from_vec(data)))
|
||||
} else {
|
||||
scratch::give(data);
|
||||
None
|
||||
};
|
||||
// Workers that missed the memo at the same time each built a copy: all of them take
|
||||
// the one stored first, so the targets share it however many threads raced.
|
||||
let finished = match memo_key {
|
||||
Some(k) => built.lock().unwrap_or_else(std::sync::PoisonError::into_inner).entry(k).or_insert(finished).clone(),
|
||||
None => finished,
|
||||
};
|
||||
finished.map(|t| (dc, t))
|
||||
}
|
||||
}
|
||||
|
||||
/// A surface shifted by whole pixels, a bounded piece of work at a time: the same surface
|
||||
/// [`Surface::translated`] returns, for a caller that must not block for the whole shift (the web
|
||||
/// build has no threads). A unit of work is the scan of one source tile or the build of one
|
||||
/// target tile, so a call of [`TranslateSteps::step`] that is asked to stop does no more than one.
|
||||
pub struct TranslateSteps {
|
||||
src: Surface,
|
||||
builder: ShiftBuilder,
|
||||
/// The source tiles still to scan, then the target tiles still to build, both in coordinate
|
||||
/// order: the targets are the tiles the shifted source tiles land on, found as they are scanned.
|
||||
scan: std::vec::IntoIter<(TileCoord, Arc<Tile>)>,
|
||||
sources: usize,
|
||||
found: BTreeSet<TileCoord>,
|
||||
targets: Option<std::vec::IntoIter<TileCoord>>,
|
||||
built: usize,
|
||||
total_targets: usize,
|
||||
out: Surface,
|
||||
/// Set when the shift is by whole tiles, which needs no building.
|
||||
whole_tiles: bool,
|
||||
dx: i32,
|
||||
dy: i32,
|
||||
content: Rect,
|
||||
}
|
||||
|
||||
impl TranslateSteps {
|
||||
/// Prepares to shift `src` by (`dx`, `dy`); `content` must hold every pixel of `src` that
|
||||
/// isn't the default one (`src.content_bounds()`, say), as for [`Surface::translated`].
|
||||
pub fn new(src: Surface, dx: i32, dy: i32, content: Rect) -> Self {
|
||||
let whole_tiles = dx % TILE_SIZE == 0 && dy % TILE_SIZE == 0;
|
||||
let builder = ShiftBuilder::new(&src, dx, dy, content);
|
||||
let tiles: Vec<(TileCoord, Arc<Tile>)> =
|
||||
if whole_tiles { Vec::new() } else { ShiftBuilder::sources(&src, content).map(|(c, t)| (*c, Arc::clone(t))).collect() };
|
||||
let out = Surface { format: src.format, default_pixel: src.default_pixel.clone(), tiles: Default::default() };
|
||||
Self {
|
||||
sources: tiles.len(),
|
||||
scan: tiles.into_iter(),
|
||||
builder,
|
||||
found: BTreeSet::new(),
|
||||
targets: None,
|
||||
built: 0,
|
||||
total_targets: 0,
|
||||
out,
|
||||
whole_tiles,
|
||||
dx,
|
||||
dy,
|
||||
content,
|
||||
src,
|
||||
}
|
||||
}
|
||||
|
||||
/// How much of the shift is done, `0.0..=1.0`.
|
||||
pub fn progress(&self) -> f32 {
|
||||
let todo = self.scan.len() + self.targets.as_ref().map_or(0, ExactSizeIterator::len);
|
||||
let total = self.sources + self.total_targets;
|
||||
if total == 0 { 0.0 } else { (1.0 - todo as f32 / total as f32).clamp(0.0, 1.0) }
|
||||
}
|
||||
|
||||
/// Does at least one unit of work, then goes on while `more()` returns true; `Some` with the
|
||||
/// shifted surface once the last tile is built.
|
||||
pub fn step(&mut self, more: &mut dyn FnMut() -> bool) -> Option<Surface> {
|
||||
if self.whole_tiles {
|
||||
return Some(self.src.translated(self.dx, self.dy, self.content));
|
||||
}
|
||||
loop {
|
||||
if self.targets.is_none() {
|
||||
match self.scan.next() {
|
||||
Some((c, t)) => {
|
||||
self.builder.scan(&t);
|
||||
let moved = self.content.translate(self.dx, self.dy);
|
||||
self.found.extend(c.rect().translate(self.dx, self.dy).intersect(&moved).tiles());
|
||||
}
|
||||
None => {
|
||||
let list: Vec<TileCoord> = std::mem::take(&mut self.found).into_iter().collect();
|
||||
self.total_targets = list.len();
|
||||
self.targets = Some(list.into_iter());
|
||||
}
|
||||
}
|
||||
} else if let Some(dc) = self.targets.as_mut().and_then(Iterator::next) {
|
||||
if let Some((c, t)) = self.builder.build(&self.src, dc) {
|
||||
self.out.tiles.insert(c, t);
|
||||
}
|
||||
self.built += 1;
|
||||
} else {
|
||||
return Some(std::mem::replace(
|
||||
&mut self.out,
|
||||
Surface { format: self.src.format, default_pixel: self.src.default_pixel.clone(), tiles: Default::default() },
|
||||
));
|
||||
}
|
||||
if !more() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+644
-68
@@ -22,10 +22,16 @@
|
||||
//! poisons the tile: edits and saves check the health of the document they publish, plus
|
||||
//! [`check_since`] for failures that came and went during the operation. The
|
||||
//! infallible display API uses a temporary placeholder, never replacement pixel storage.
|
||||
//!
|
||||
//! No lock is held across a call into the scratch folder. Opening and measuring it run on a
|
||||
//! short-lived query thread, at most one per folder and question; callers wait a bounded time
|
||||
//! for the answer, and a late answer still applies if that folder is still the configured one.
|
||||
//! Status reads the UI makes every frame stay fast whatever the folder does.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard, Weak};
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard, Weak};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::scratch_file::{Extent, ScratchFile};
|
||||
@@ -235,6 +241,8 @@ struct Manager {
|
||||
next_space_check: AtomicU64,
|
||||
/// A sweep wrote successfully since the last resume: reset the retry backoff.
|
||||
recovering: AtomicBool,
|
||||
/// The last free-space query for the scratch directory got no answer.
|
||||
space_unmeasured: AtomicBool,
|
||||
registry: Mutex<Registry>,
|
||||
config: Mutex<Config>,
|
||||
evictions: AtomicU64,
|
||||
@@ -259,6 +267,8 @@ struct Config {
|
||||
backoff: Duration,
|
||||
/// Explicit scratch size limit ([`set_size_cap`]); the free-space reserve always applies.
|
||||
size_cap: Option<u64>,
|
||||
/// Scratch bytes the volume allows, as of the last answer; `None` = unmeasured.
|
||||
room: Option<u64>,
|
||||
}
|
||||
|
||||
struct Pause {
|
||||
@@ -272,6 +282,51 @@ const RETRY_MAX: Duration = Duration::from_secs(60);
|
||||
const SPACE_CHECK_EVERY: u64 = 64 << 20;
|
||||
/// Leave at least max(1 GiB, 5 % of the volume) free for the system and other programs.
|
||||
const RESERVE_MIN: u64 = 1 << 30;
|
||||
/// How long a caller waits for the scratch folder to answer. A healthy disk answers in far less;
|
||||
/// the query goes on after this and its answer still counts when it comes.
|
||||
const QUERY_WAIT: Duration = Duration::from_secs(2);
|
||||
/// Most folder queries in flight at once. A system call on a dead hard mount can't be cancelled,
|
||||
/// so each stuck one keeps its thread, and every other folder tried on that mount adds one.
|
||||
const MAX_QUERIES: usize = 16;
|
||||
|
||||
/// A question in flight about a scratch folder (open it and/or measure it).
|
||||
struct Query {
|
||||
dir: PathBuf,
|
||||
prepare: bool,
|
||||
deadline: Instant,
|
||||
done: Arc<QueryDone>,
|
||||
}
|
||||
|
||||
/// Set once a query's answer has been applied (or discarded).
|
||||
#[derive(Default)]
|
||||
struct QueryDone {
|
||||
finished: Mutex<bool>,
|
||||
wake: Condvar,
|
||||
}
|
||||
|
||||
impl QueryDone {
|
||||
fn finish(&self) {
|
||||
*self.finished.lock().unwrap_or_else(PoisonError::into_inner) = true;
|
||||
self.wake.notify_all();
|
||||
}
|
||||
|
||||
fn finished(&self) -> bool {
|
||||
*self.finished.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Wait until the query finishes or `deadline` passes; a deadline already past returns at once.
|
||||
fn wait_until(&self, deadline: Instant) {
|
||||
let Some(left) = deadline.checked_duration_since(Instant::now()) else { return };
|
||||
let done = self.finished.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
drop(self.wake.wait_timeout_while(done, left, |done| !*done).unwrap_or_else(PoisonError::into_inner));
|
||||
}
|
||||
}
|
||||
|
||||
static QUERIES: Mutex<Vec<Query>> = Mutex::new(Vec::new());
|
||||
/// Query threads alive, counted until they finish, including closing any file they opened;
|
||||
/// `QUERIES` only dedupes questions.
|
||||
static QUERY_THREADS: AtomicUsize = AtomicUsize::new(0);
|
||||
static QUERY_HOOK: RwLock<Option<fn(&Path)>> = RwLock::new(None);
|
||||
|
||||
static M: Manager = Manager {
|
||||
failed: AtomicUsize::new(0),
|
||||
@@ -284,8 +339,9 @@ static M: Manager = Manager {
|
||||
space_limit: AtomicU64::new(u64::MAX),
|
||||
next_space_check: AtomicU64::new(0),
|
||||
recovering: AtomicBool::new(false),
|
||||
space_unmeasured: AtomicBool::new(false),
|
||||
registry: Mutex::new(Registry { cells: Vec::new(), hand: 0 }),
|
||||
config: Mutex::new(Config { dir: None, file: None, last_error: None, budget: 0, paused: None, backoff: RETRY_FIRST, size_cap: None }),
|
||||
config: Mutex::new(Config { dir: None, file: None, last_error: None, budget: 0, paused: None, backoff: RETRY_FIRST, size_cap: None, room: None }),
|
||||
evictions: AtomicU64::new(0),
|
||||
reloads: AtomicU64::new(0),
|
||||
written: AtomicU64::new(0),
|
||||
@@ -345,27 +401,73 @@ impl Manager {
|
||||
self.set_active(c.budget);
|
||||
}
|
||||
|
||||
/// Open the scratch file and check its volume's room; pause (and say why) if either fails.
|
||||
/// The caller holds the config lock. Returns whether spilling can go ahead.
|
||||
fn prepare(&self, c: &mut Config) -> bool {
|
||||
let Some(dir) = c.dir.clone() else { return false };
|
||||
if c.file.is_none() {
|
||||
match std::fs::create_dir_all(&dir).and_then(|()| ScratchFile::create(&dir)) {
|
||||
Ok(f) => c.file = Some(Arc::new(f)),
|
||||
Err(e) => {
|
||||
self.pause(c, &format!("could not create a scratch file in {}: {e}", dir.display()));
|
||||
return false;
|
||||
}
|
||||
/// Apply a finished folder query. `file` is the scratch file a `prepare` query opened (or the
|
||||
/// error), `sampled_used` the scratch bytes in use just before the volume was asked, `space`
|
||||
/// what the volume reported. Discarded if the folder changed meanwhile.
|
||||
fn settle(&self, dir: &Path, prepare: bool, file: Option<std::io::Result<ScratchFile>>, sampled_used: u64, space: Option<(u64, u64)>, done: &QueryDone) {
|
||||
// Declared before the guard so a rejected file closes after the lock is released.
|
||||
let mut _spare: Option<ScratchFile> = None;
|
||||
let mut c = self.config();
|
||||
// Under the config lock, so a caller holding the lock can tell answered from not.
|
||||
done.finish();
|
||||
if c.dir.as_deref() != Some(dir) {
|
||||
return;
|
||||
}
|
||||
match file {
|
||||
Some(Ok(f)) if c.file.is_none() => c.file = Some(Arc::new(f)),
|
||||
Some(Ok(f)) => _spare = Some(f),
|
||||
Some(Err(e)) if c.file.is_none() => {
|
||||
self.pause(&mut c, &format!("could not create a scratch file in {}: {e}", dir.display()));
|
||||
return;
|
||||
}
|
||||
Some(Err(_)) | None => {}
|
||||
}
|
||||
let used = c.file.as_ref().map_or(0, |f| f.used());
|
||||
refresh_space(c, &dir, used);
|
||||
if used >= self.space_limit.load(Ordering::Relaxed) {
|
||||
let msg = no_room(&dir, c.size_cap);
|
||||
self.pause(c, &msg);
|
||||
return false;
|
||||
apply_space(&mut c, sampled_used, space);
|
||||
if !prepare {
|
||||
return;
|
||||
}
|
||||
true
|
||||
if c.file.is_none() {
|
||||
// The folder changed away and back while this ran.
|
||||
self.pause(&mut c, ¬_responding(dir));
|
||||
return;
|
||||
}
|
||||
if used >= self.space_limit.load(Ordering::Relaxed) {
|
||||
let msg = no_room(dir, c.size_cap);
|
||||
self.pause(&mut c, &msg);
|
||||
return;
|
||||
}
|
||||
if c.paused.is_some() {
|
||||
self.resume(&mut c);
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the scratch file and check its volume's room, waiting up to [`QUERY_WAIT`]; an answer
|
||||
/// that comes later is applied by [`Manager::settle`]. Pauses (and says why) on failure or
|
||||
/// silence. The caller holds no lock.
|
||||
fn prepare(&self, dir: &Path) {
|
||||
let done = ask(dir, true);
|
||||
let mut c = self.config();
|
||||
if c.dir.as_deref() != Some(dir) || done.as_ref().is_some_and(|d| d.finished()) {
|
||||
return;
|
||||
}
|
||||
// No answer in time: it still counts when it comes. Until then:
|
||||
let used = c.file.as_ref().map_or(0, |f| f.used());
|
||||
apply_space(&mut c, used, None);
|
||||
if c.file.is_none() || c.paused.is_some() {
|
||||
self.pause(&mut c, ¬_responding(dir));
|
||||
}
|
||||
}
|
||||
|
||||
/// Measure the volume's free space, waiting up to [`QUERY_WAIT`]. The caller holds no lock.
|
||||
fn measure(&self, dir: &Path) {
|
||||
let done = ask(dir, false);
|
||||
let mut c = self.config();
|
||||
if c.dir.as_deref() != Some(dir) || done.as_ref().is_some_and(|d| d.finished()) {
|
||||
return;
|
||||
}
|
||||
let used = c.file.as_ref().map_or(0, |f| f.used());
|
||||
apply_space(&mut c, used, None);
|
||||
}
|
||||
|
||||
/// Retry a paused scratch disk once its backoff has elapsed. Cheap when not paused.
|
||||
@@ -373,40 +475,44 @@ impl Manager {
|
||||
if !self.paused.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
let mut c = match self.config.try_lock() {
|
||||
Ok(c) => c,
|
||||
Err(std::sync::TryLockError::Poisoned(p)) => p.into_inner(),
|
||||
// Someone else is configuring or retrying.
|
||||
Err(std::sync::TryLockError::WouldBlock) => return,
|
||||
};
|
||||
let c = self.config();
|
||||
let due = c.paused.as_ref().is_some_and(|p| Instant::now() >= p.retry_at);
|
||||
if !due {
|
||||
return;
|
||||
}
|
||||
if c.dir.is_none() || c.budget == 0 {
|
||||
c.paused = None;
|
||||
self.paused.store(false, Ordering::Release);
|
||||
return;
|
||||
}
|
||||
if self.prepare(&mut c) {
|
||||
self.resume(&mut c);
|
||||
self.retry_now(c);
|
||||
}
|
||||
|
||||
/// Retry a paused scratch disk now (the guard is released before the folder is asked).
|
||||
fn retry_now(&self, mut c: std::sync::MutexGuard<'_, Config>) {
|
||||
let dir = match c.dir.clone() {
|
||||
Some(dir) if c.budget > 0 => dir,
|
||||
_ => {
|
||||
c.paused = None;
|
||||
self.paused.store(false, Ordering::Release);
|
||||
return;
|
||||
}
|
||||
};
|
||||
// Push the next retry out so other threads don't all wait on this one.
|
||||
let wait = c.backoff;
|
||||
if let Some(p) = &mut c.paused {
|
||||
p.retry_at = Instant::now().checked_add(wait).unwrap_or_else(Instant::now);
|
||||
}
|
||||
drop(c);
|
||||
self.prepare(&dir);
|
||||
}
|
||||
|
||||
/// The scratch file, if spilling is on and the volume still has room.
|
||||
fn file(&self) -> Option<Arc<ScratchFile>> {
|
||||
let mut c = self.config();
|
||||
if self.budget.load(Ordering::Relaxed) == 0 {
|
||||
return None;
|
||||
}
|
||||
if c.file.is_none() && !self.prepare(&mut c) {
|
||||
return None;
|
||||
}
|
||||
c.file.clone()
|
||||
self.config().file.clone()
|
||||
}
|
||||
|
||||
/// Whether the scratch file may grow further; re-reads free space every
|
||||
/// [`SPACE_CHECK_EVERY`] bytes and pauses spilling when the volume runs low.
|
||||
/// Whether the scratch file may grow further; asks for free space every
|
||||
/// [`SPACE_CHECK_EVERY`] bytes (in the background, never waiting) and pauses spilling when the
|
||||
/// volume runs low.
|
||||
fn has_room(&self, file: &ScratchFile) -> bool {
|
||||
let used = file.used();
|
||||
if used < self.next_space_check.load(Ordering::Relaxed) && used < self.space_limit.load(Ordering::Relaxed) {
|
||||
@@ -414,8 +520,20 @@ impl Manager {
|
||||
}
|
||||
let mut c = self.config();
|
||||
let Some(dir) = c.dir.clone() else { return false };
|
||||
refresh_space(&c, &dir, used);
|
||||
if used < self.space_limit.load(Ordering::Relaxed) {
|
||||
// Ask in the background: this can be any thread, the UI's too. The answer moves the limit.
|
||||
drop(c);
|
||||
let query = start_query(&dir, false);
|
||||
let c = self.config();
|
||||
// A rejected request must remain due. Don't overwrite a new folder's state or an
|
||||
// answer that arrived before this lock was reacquired.
|
||||
if c.dir.as_deref() == Some(dir.as_path()) && !query.as_ref().is_some_and(|(done, _)| done.finished()) {
|
||||
if query.is_some() {
|
||||
self.next_space_check.store(used.saturating_add(SPACE_CHECK_EVERY), Ordering::Relaxed);
|
||||
} else {
|
||||
self.space_unmeasured.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if c.paused.is_none() {
|
||||
@@ -488,14 +606,128 @@ impl Manager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Free space on the volume holding `dir`, minus the reserve, sets how far the file may grow.
|
||||
fn refresh_space(c: &Config, dir: &Path, used: u64) {
|
||||
let room = free_space(dir).map_or(u64::MAX, |(available, total)| used.saturating_add(available.saturating_sub(RESERVE_MIN.max(total / 20))));
|
||||
let limit = c.size_cap.map_or(room, |cap| cap.min(room));
|
||||
M.space_limit.store(limit, Ordering::Relaxed);
|
||||
/// Record a volume's answer (`None` = it didn't say) and derive the growth limit from it.
|
||||
fn apply_space(c: &mut Config, used: u64, space: Option<(u64, u64)>) {
|
||||
M.space_unmeasured.store(space.is_none(), Ordering::Relaxed);
|
||||
c.room = space.map(|(available, total)| used.saturating_add(available.saturating_sub(RESERVE_MIN.max(total / 20))));
|
||||
store_limit(c);
|
||||
M.next_space_check.store(used.saturating_add(SPACE_CHECK_EVERY), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Publish the scratch size the volume and the size limit allow.
|
||||
fn store_limit(c: &Config) {
|
||||
let room = c.room.unwrap_or(u64::MAX);
|
||||
M.space_limit.store(c.size_cap.map_or(room, |cap| cap.min(room)), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn not_responding(dir: &Path) -> String {
|
||||
format!("scratch disk {} is not responding", dir.display())
|
||||
}
|
||||
|
||||
/// Start (or join) a query about `dir`: the same question is never asked by a second thread, and
|
||||
/// at most [`MAX_QUERIES`] run at once. `None` if no thread could be started.
|
||||
fn start_query(dir: &Path, prepare: bool) -> Option<(Arc<QueryDone>, Instant)> {
|
||||
let mut queries = QUERIES.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(q) = queries.iter().find(|q| q.prepare == prepare && q.dir.as_path() == dir) {
|
||||
return Some((q.done.clone(), q.deadline));
|
||||
}
|
||||
if QUERY_THREADS.load(Ordering::Acquire) >= MAX_QUERIES {
|
||||
return None;
|
||||
}
|
||||
let now = Instant::now();
|
||||
let deadline = now.checked_add(QUERY_WAIT).unwrap_or(now);
|
||||
let done = Arc::new(QueryDone::default());
|
||||
queries.push(Query { dir: dir.to_path_buf(), prepare, deadline, done: done.clone() });
|
||||
let (job_dir, job_done) = (dir.to_path_buf(), done.clone());
|
||||
QUERY_THREADS.fetch_add(1, Ordering::AcqRel);
|
||||
let spawned = std::thread::Builder::new().name("pc-scratch-query".into()).spawn(move || run_query(job_dir, prepare, job_done));
|
||||
if spawned.is_err() {
|
||||
QUERY_THREADS.fetch_sub(1, Ordering::AcqRel);
|
||||
queries.pop();
|
||||
return None;
|
||||
}
|
||||
Some((done, deadline))
|
||||
}
|
||||
|
||||
/// Ask about `dir` and wait up to [`QUERY_WAIT`] for the answer. The caller holds no lock.
|
||||
fn ask(dir: &Path, prepare: bool) -> Option<Arc<QueryDone>> {
|
||||
let (done, deadline) = start_query(dir, prepare)?;
|
||||
done.wait_until(deadline);
|
||||
Some(done)
|
||||
}
|
||||
|
||||
/// The query thread: touches the folder, then hands the answer to [`Manager::settle`].
|
||||
fn run_query(dir: PathBuf, prepare: bool, done: Arc<QueryDone>) {
|
||||
let hook = *QUERY_HOOK.read().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(hook) = hook {
|
||||
hook(&dir);
|
||||
}
|
||||
// Before measuring: writes made during the query come off the free space and must not be
|
||||
// counted again on top of it. Another folder's file says nothing about this one.
|
||||
let (open, used) = {
|
||||
let c = M.config();
|
||||
let current = c.file.as_ref().filter(|_| c.dir.as_deref() == Some(dir.as_path()));
|
||||
(prepare && current.is_none(), current.map_or(0, |f| f.used()))
|
||||
};
|
||||
let file = open.then(|| std::fs::create_dir_all(&dir).and_then(|()| ScratchFile::create(&dir)));
|
||||
let space = free_space(&dir);
|
||||
// Forget it first: a caller that joined it can rely on the answer, and a later caller asks anew.
|
||||
QUERIES.lock().unwrap_or_else(PoisonError::into_inner).retain(|q| !Arc::ptr_eq(&q.done, &done));
|
||||
M.settle(&dir, prepare, file, used, space, &done);
|
||||
QUERY_THREADS.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
|
||||
/// Whether a query about `dir` is past its wait without an answer.
|
||||
fn query_overdue(dir: Option<&Path>) -> bool {
|
||||
let Some(dir) = dir else { return false };
|
||||
let now = Instant::now();
|
||||
let queries = QUERIES.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
queries.iter().any(|q| q.dir.as_path() == dir && now >= q.deadline)
|
||||
}
|
||||
|
||||
/// Scratch files on their way out, oldest first.
|
||||
struct Retired {
|
||||
files: VecDeque<(Arc<ScratchFile>, Arc<QueryDone>)>,
|
||||
/// Closer threads alive.
|
||||
closers: usize,
|
||||
}
|
||||
|
||||
/// Most closer threads at once: enough that one close stuck on a dead mount doesn't hold up the
|
||||
/// files behind it, few enough that stuck closes can't pile up threads.
|
||||
const MAX_CLOSERS: usize = 4;
|
||||
|
||||
static RETIRED: Mutex<Retired> = Mutex::new(Retired { files: VecDeque::new(), closers: 0 });
|
||||
|
||||
/// Let go of a scratch file off this thread: the last reference closes it, which can flush to its
|
||||
/// folder, and a dead mount blocks that, while leaving a dead folder is how a user recovers. The
|
||||
/// returned handle finishes when this reference is gone.
|
||||
fn retire(file: Arc<ScratchFile>) -> Arc<QueryDone> {
|
||||
let done = Arc::new(QueryDone::default());
|
||||
let mut retired = RETIRED.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
retired.files.push_back((file, done.clone()));
|
||||
// If no thread can start, the file waits in the queue for the next one rather than closing here.
|
||||
if retired.closers < MAX_CLOSERS && std::thread::Builder::new().name("pc-scratch-close".into()).spawn(close_retired).is_ok() {
|
||||
retired.closers += 1;
|
||||
}
|
||||
done
|
||||
}
|
||||
|
||||
fn close_retired() {
|
||||
loop {
|
||||
let next = {
|
||||
let mut retired = RETIRED.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let next = retired.files.pop_front();
|
||||
if next.is_none() {
|
||||
retired.closers = retired.closers.saturating_sub(1);
|
||||
}
|
||||
next
|
||||
};
|
||||
let Some((file, done)) = next else { return };
|
||||
drop(file);
|
||||
done.finish();
|
||||
}
|
||||
}
|
||||
|
||||
fn no_room(dir: &Path, cap: Option<u64>) -> String {
|
||||
match cap {
|
||||
Some(cap) => format!("scratch disk {} reached its size limit ({} MB) or is low on free space", dir.display(), cap >> 20),
|
||||
@@ -503,16 +735,97 @@ fn no_room(dir: &Path, cap: Option<u64>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// (available, total) bytes of the volume holding `dir`: the mount point that is its longest
|
||||
/// prefix. `None` if unknown, which disables only the free-space check, not spilling.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// (available, total) bytes of the volume holding `dir`, asked of the directory itself so that a
|
||||
/// network folder or any other mount reports its own numbers: `GetDiskFreeSpaceEx` on Windows,
|
||||
/// `statvfs` on Unix. Available is what the current user can write (per-user quotas on Windows, the
|
||||
/// root reserve on Unix). `None` if the system can't say (the query failed, or it reports a total
|
||||
/// of zero, as some FUSE and WebDAV mounts do), which disables only the free-space check, not
|
||||
/// spilling; [`free_space_unmeasured`] tells the user.
|
||||
#[cfg(any(unix, windows))]
|
||||
fn free_space(dir: &Path) -> Option<(u64, u64)> {
|
||||
let dir = std::fs::canonicalize(dir).ok()?;
|
||||
let disks = sysinfo::Disks::new_with_refreshed_list_specifics(sysinfo::DiskRefreshKind::nothing().with_storage()).ok()?;
|
||||
disks.iter().filter(|d| dir.starts_with(d.mount_point())).max_by_key(|d| d.mount_point().as_os_str().len()).map(|d| (d.available_space(), d.total_space()))
|
||||
let (available, total) = volume_space(&dir)?;
|
||||
known_space(with_purgeable_space(&dir, available, total), total)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
/// A zero total means the system could not say (a failed query, or a mount that reports no
|
||||
/// capacity); treating that as an empty disk would pause spilling, so it counts as unknown.
|
||||
#[cfg(any(unix, windows))]
|
||||
fn known_space(available: u64, total: u64) -> Option<(u64, u64)> {
|
||||
(total != 0).then_some((available, total))
|
||||
}
|
||||
|
||||
/// (available, total) bytes of the volume holding `dir`, from `statvfs`.
|
||||
#[cfg(unix)]
|
||||
fn volume_space(dir: &Path) -> Option<(u64, u64)> {
|
||||
let vfs = rustix::io::retry_on_intr(|| rustix::fs::statvfs(dir)).ok()?;
|
||||
Some((vfs.f_bavail.saturating_mul(vfs.f_frsize), vfs.f_blocks.saturating_mul(vfs.f_frsize)))
|
||||
}
|
||||
|
||||
/// (available, total) bytes of the volume holding `dir`, from `GetDiskFreeSpaceEx`. `dir` is
|
||||
/// canonical, so verbatim (`\\?\C:\x`, `\\?\UNC\server\share\x`), which also reaches paths past
|
||||
/// MAX_PATH and keeps trailing dots significant; winsafe takes `&str`, so a non-UTF-8 folder name
|
||||
/// uses its nearest UTF-8 ancestor (the same volume unless a mount point has such a name).
|
||||
#[cfg(windows)]
|
||||
fn volume_space(dir: &Path) -> Option<(u64, u64)> {
|
||||
disk_free_space(dir.ancestors().find_map(Path::to_str)?)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn disk_free_space(dir: &str) -> Option<(u64, u64)> {
|
||||
// GetDiskFreeSpaceEx requires the trailing backslash on UNC paths.
|
||||
let arg = if dir.ends_with('\\') { dir.to_string() } else { format!("{dir}\\") };
|
||||
let (mut available, mut total) = (0, 0);
|
||||
winsafe::GetDiskFreeSpaceEx(Some(&arg), Some(&mut available), Some(&mut total), None).ok()?;
|
||||
Some((available, total))
|
||||
}
|
||||
|
||||
/// `statvfs` doesn't count purgeable space (local snapshots and caches macOS frees on demand) but
|
||||
/// sysinfo does: when the listed disk with the longest mount point holding `dir` is this volume,
|
||||
/// use its available figure. A listed disk counts as this volume when the mount point's own
|
||||
/// `statvfs` gives the same numbers (APFS volumes in one container share them, and firmlinks give
|
||||
/// `/Users` and `/` different device ids, so ids can't be compared); a change between the two
|
||||
/// readings just keeps the `statvfs` figure. sysinfo asks every mounted volume for its properties,
|
||||
/// so an unrelated dead mount must not hold up this measurement: the lookup runs on a helper thread
|
||||
/// that is waited for at most [`PURGEABLE_WAIT`]. Never fails.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn with_purgeable_space(dir: &Path, available: u64, total: u64) -> u64 {
|
||||
static LISTING: AtomicBool = AtomicBool::new(false);
|
||||
// A listing already running may be stuck on some mount: don't start another.
|
||||
if LISTING.swap(true, Ordering::AcqRel) {
|
||||
return available;
|
||||
}
|
||||
let dir = dir.to_path_buf();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let spawned = std::thread::Builder::new().name("pc-scratch-disks".into()).spawn(move || {
|
||||
let found: Option<u64> = sysinfo::Disks::new_with_refreshed_list_specifics(sysinfo::DiskRefreshKind::nothing().with_storage()).ok().and_then(|disks| {
|
||||
disks
|
||||
.iter()
|
||||
.filter(|d| dir.starts_with(d.mount_point()))
|
||||
.max_by_key(|d| d.mount_point().as_os_str().len())
|
||||
.filter(|d| volume_space(d.mount_point()) == Some((available, total)))
|
||||
.map(|d| d.available_space())
|
||||
});
|
||||
LISTING.store(false, Ordering::Release);
|
||||
let _ = tx.send(found);
|
||||
});
|
||||
if spawned.is_err() {
|
||||
LISTING.store(false, Ordering::Release);
|
||||
return available;
|
||||
}
|
||||
rx.recv_timeout(PURGEABLE_WAIT).ok().flatten().unwrap_or(available)
|
||||
}
|
||||
|
||||
/// How long a measurement waits for the mounted-volume listing before using the `statvfs` figure.
|
||||
#[cfg(target_os = "macos")]
|
||||
const PURGEABLE_WAIT: Duration = Duration::from_millis(500);
|
||||
|
||||
#[cfg(all(any(unix, windows), not(target_os = "macos")))]
|
||||
fn with_purgeable_space(_dir: &Path, available: u64, _total: u64) -> u64 {
|
||||
available
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn free_space(_dir: &Path) -> Option<(u64, u64)> {
|
||||
None
|
||||
}
|
||||
@@ -521,7 +834,11 @@ fn free_space(_dir: &Path) -> Option<(u64, u64)> {
|
||||
fn maybe_evict() {
|
||||
let budget = M.budget.load(Ordering::Relaxed);
|
||||
if budget == 0 {
|
||||
M.retry();
|
||||
// The supervisor retries when there is one; this can be any thread, the UI's too, and a
|
||||
// retry waits for the folder.
|
||||
if MAINTENANCE.load(Ordering::Acquire) == 0 {
|
||||
M.retry();
|
||||
}
|
||||
return;
|
||||
}
|
||||
let resident = M.resident.load(Ordering::Relaxed);
|
||||
@@ -591,25 +908,28 @@ pub fn set_size_cap(cap: Option<u64>) {
|
||||
return;
|
||||
}
|
||||
c.size_cap = cap;
|
||||
store_limit(&c);
|
||||
M.next_space_check.store(0, Ordering::Relaxed);
|
||||
if let Some(p) = &mut c.paused {
|
||||
p.retry_at = Instant::now();
|
||||
if c.paused.is_some() {
|
||||
c.backoff = RETRY_FIRST;
|
||||
M.retry_now(c);
|
||||
}
|
||||
drop(c);
|
||||
M.retry();
|
||||
}
|
||||
|
||||
/// Turn the scratch disk on (`dir` and a non-zero `budget_bytes`) or off. Tiles already on disk
|
||||
/// stay readable either way. Changing the directory starts a new scratch file there; the old one
|
||||
/// is deleted once its last tile is freed or changed. A directory that can't be used is kept and
|
||||
/// retried with backoff (spilling stays paused meanwhile); the error is returned and reported.
|
||||
/// Waits up to 2 s for the folder; a folder that doesn't answer counts as unusable until it does.
|
||||
pub fn configure(dir: Option<&Path>, budget_bytes: usize) -> Result<(), String> {
|
||||
let mut c = M.config();
|
||||
let dir = dir.filter(|_| budget_bytes > 0).map(Path::to_path_buf);
|
||||
if dir != c.dir {
|
||||
c.file = None;
|
||||
}
|
||||
let mut c = M.config();
|
||||
let old = if dir != c.dir {
|
||||
c.room = None;
|
||||
c.file.take()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
c.dir = dir.clone();
|
||||
c.budget = if dir.is_some() { budget_bytes } else { 0 };
|
||||
c.backoff = RETRY_FIRST;
|
||||
@@ -617,7 +937,22 @@ pub fn configure(dir: Option<&Path>, budget_bytes: usize) -> Result<(), String>
|
||||
c.last_error = None;
|
||||
M.paused.store(false, Ordering::Release);
|
||||
M.next_space_check.store(0, Ordering::Relaxed);
|
||||
if dir.is_some() && !M.prepare(&mut c) {
|
||||
drop(c);
|
||||
let start = Instant::now();
|
||||
let closing = old.map(retire);
|
||||
if let Some(dir) = &dir {
|
||||
M.prepare(dir);
|
||||
}
|
||||
// One wait for the whole change: closing the old file gets what the new folder left over.
|
||||
if let Some(closing) = closing {
|
||||
closing.wait_until(start.checked_add(QUERY_WAIT).unwrap_or(start));
|
||||
}
|
||||
let c = M.config();
|
||||
if c.dir != dir {
|
||||
// A newer configure owns the state now.
|
||||
return Ok(());
|
||||
}
|
||||
if c.paused.is_some() {
|
||||
return Err(c.last_error.clone().unwrap_or_default());
|
||||
}
|
||||
M.set_active(c.budget);
|
||||
@@ -666,6 +1001,8 @@ pub struct SpillStats {
|
||||
pub paused: bool,
|
||||
/// Scratch file size limit ([`set_size_cap`]); `None` = only the free-space reserve.
|
||||
pub size_cap_bytes: Option<u64>,
|
||||
/// Spilling is on but the scratch directory's volume won't report its free space ([`free_space_unmeasured`]).
|
||||
pub free_space_unmeasured: bool,
|
||||
}
|
||||
|
||||
pub fn stats() -> SpillStats {
|
||||
@@ -682,6 +1019,7 @@ pub fn stats() -> SpillStats {
|
||||
last_error: c.last_error.clone(),
|
||||
paused: c.paused.is_some(),
|
||||
size_cap_bytes: c.size_cap,
|
||||
free_space_unmeasured: enabled() && (M.space_unmeasured.load(Ordering::Relaxed) || query_overdue(c.dir.as_deref())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -693,17 +1031,24 @@ pub fn last_error() -> Option<String> {
|
||||
/// Uncompressed tile bytes the scratch disk can still take before it reaches its size limit
|
||||
/// ([`set_size_cap`]) or the volume's free-space reserve, so an import can admit tile pixels
|
||||
/// beyond physical RAM. `None` while spilling is off or paused, and when neither the free space
|
||||
/// nor a size limit is known (nothing to promise). Tiles are written compressed; this counts
|
||||
/// them uncompressed, less 1/64 for the allocator's block rounding, so it never over-promises.
|
||||
/// nor a size limit is known (nothing to promise), which includes a folder that doesn't answer
|
||||
/// within 2 s. Tiles are written compressed; this counts them uncompressed, less 1/64 for the allocator's block rounding, so it never over-promises.
|
||||
pub fn scratch_capacity() -> Option<u64> {
|
||||
if !enabled() || paused() {
|
||||
return None;
|
||||
}
|
||||
let (dir, used, cap) = {
|
||||
let c = M.config();
|
||||
(c.dir.clone()?, c.file.as_ref().map_or(0, |f| f.used()), c.size_cap)
|
||||
};
|
||||
let room = free_space(&dir).map(|(available, total)| available.saturating_sub(RESERVE_MIN.max(total / 20)));
|
||||
let dir = M.config().dir.clone()?;
|
||||
M.measure(&dir);
|
||||
let c = M.config();
|
||||
// A slow query must not describe a directory configured meanwhile, and a sweep can also have
|
||||
// paused spilling meanwhile.
|
||||
if c.dir.as_deref() != Some(dir.as_path()) || c.paused.is_some() {
|
||||
return None;
|
||||
}
|
||||
let used = c.file.as_ref().map_or(0, |f| f.used());
|
||||
let cap = c.size_cap;
|
||||
let room = c.room.map(|room| room.saturating_sub(used));
|
||||
drop(c);
|
||||
let room = match (room, cap) {
|
||||
(Some(room), Some(cap)) => room.min(cap.saturating_sub(used)),
|
||||
(Some(room), None) => room,
|
||||
@@ -713,6 +1058,21 @@ pub fn scratch_capacity() -> Option<u64> {
|
||||
Some(room - room / 64)
|
||||
}
|
||||
|
||||
/// Whether spilling is on but the scratch directory's volume won't report its free space, so the
|
||||
/// reserve doesn't apply and imports earn scratch room only up to a size limit. Two short locks,
|
||||
/// neither ever held across a query, so it is safe to call every frame. A query past its wait
|
||||
/// counts as unmeasured even with nobody waiting on it.
|
||||
pub fn free_space_unmeasured() -> bool {
|
||||
if !enabled() {
|
||||
return false;
|
||||
}
|
||||
if M.space_unmeasured.load(Ordering::Relaxed) {
|
||||
return true;
|
||||
}
|
||||
let c = M.config();
|
||||
query_overdue(c.dir.as_deref())
|
||||
}
|
||||
|
||||
/// Whether spilling is on (tiles beyond the budget go to disk).
|
||||
pub fn enabled() -> bool {
|
||||
M.budget.load(Ordering::Relaxed) > 0
|
||||
@@ -762,6 +1122,18 @@ pub fn scratch_handle_for_tests() -> Option<std::fs::File> {
|
||||
M.config().file.as_ref().and_then(|f| f.duplicate_handle().ok())
|
||||
}
|
||||
|
||||
/// Runs at the start of every folder query, off every lock: tests stall it to simulate a dead mount.
|
||||
#[doc(hidden)]
|
||||
pub fn set_query_hook_for_tests(hook: Option<fn(&Path)>) {
|
||||
*QUERY_HOOK.write().unwrap_or_else(PoisonError::into_inner) = hook;
|
||||
}
|
||||
|
||||
/// Query threads still alive, so a test can wait until a stalled query has fully settled.
|
||||
#[doc(hidden)]
|
||||
pub fn query_threads_for_tests() -> usize {
|
||||
QUERY_THREADS.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Evict down to the budget now, on this thread (tests, and before a measurement).
|
||||
pub fn settle() {
|
||||
let budget = M.budget.load(Ordering::Relaxed);
|
||||
@@ -784,6 +1156,210 @@ fn log_error(msg: &str) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn free_space_keeps_a_trailing_dot_folder() {
|
||||
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("photocraft-dot-{}", std::process::id()));
|
||||
let dir = base.join("x.");
|
||||
if std::fs::create_dir_all(&dir).is_err() {
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
return;
|
||||
}
|
||||
let space = free_space(&dir);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
assert!(space.is_some());
|
||||
}
|
||||
|
||||
// `free_space` returned `None` on Windows before: `canonicalize` gives `\\?\C:\..`, which never
|
||||
// started with the mount point `C:\`.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn free_space_finds_the_temp_volume_on_windows() {
|
||||
let temp = std::env::temp_dir();
|
||||
let (available, total) = free_space(&temp).unwrap();
|
||||
assert!(total > 0);
|
||||
assert!(available <= total);
|
||||
let mut temp_volume_total = 0;
|
||||
winsafe::GetDiskFreeSpaceEx(Some(temp.to_str().unwrap()), None, Some(&mut temp_volume_total), None).unwrap();
|
||||
assert_eq!(total, temp_volume_total);
|
||||
}
|
||||
|
||||
// The real redirector path: the administrative share of this machine's system drive.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn free_space_reads_a_unc_path() {
|
||||
let unc = Path::new(r"\\localhost\C$\Windows");
|
||||
if std::fs::canonicalize(unc).is_err() {
|
||||
eprintln!("the administrative share {} isn't reachable; skipping", unc.display());
|
||||
return;
|
||||
}
|
||||
let (_, unc_total) = free_space(unc).unwrap();
|
||||
let (_, local_total) = free_space(Path::new(r"C:\")).unwrap();
|
||||
assert_eq!(unc_total, local_total);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn free_space_reads_a_folder_past_max_path() {
|
||||
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("photocraft-long-{}", std::process::id()));
|
||||
let mut deep = base.clone();
|
||||
while deep.as_os_str().len() <= 300 {
|
||||
deep.push("a".repeat(40));
|
||||
}
|
||||
if std::fs::create_dir_all(&deep).is_err() {
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
return;
|
||||
}
|
||||
let space = free_space(&deep);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
assert!(space.is_some());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn free_space_reads_a_non_utf8_folder() {
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
let mut wide: Vec<u16> = format!("photocraft-nonutf8-{}-", std::process::id()).encode_utf16().collect();
|
||||
wide.push(0xD800);
|
||||
let dir = std::env::temp_dir().join(std::ffi::OsString::from_wide(&wide));
|
||||
if std::fs::create_dir_all(&dir).is_err() {
|
||||
return;
|
||||
}
|
||||
let space = free_space(&dir);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert!(space.is_some());
|
||||
}
|
||||
|
||||
// `/dev/shm` is tmpfs, which sysinfo never lists: the same situation as an unlisted NFS mount.
|
||||
// Before the directory itself was asked, it reported the numbers of `/`.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn free_space_reads_an_unlisted_mount() {
|
||||
let shm = Path::new("/dev/shm");
|
||||
if !shm.is_dir() {
|
||||
return;
|
||||
}
|
||||
let (available, total) = free_space(shm).unwrap();
|
||||
assert!(available <= total);
|
||||
// An independent oracle: `df` asks the same mount for its size.
|
||||
let Ok(out) = std::process::Command::new("df").args(["-B1", "--output=size"]).arg(shm).output() else {
|
||||
eprintln!("df couldn't be run; skipping the comparison");
|
||||
return;
|
||||
};
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let parsed = text.lines().rev().map(str::trim).find(|l| !l.is_empty()).and_then(|l| l.parse::<u64>().ok());
|
||||
let Some(parsed) = parsed.filter(|_| out.status.success()) else {
|
||||
eprintln!("df gave no size for {}; skipping the comparison", shm.display());
|
||||
return;
|
||||
};
|
||||
assert_eq!(total, parsed);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn free_space_reads_the_temp_volume_on_macos() {
|
||||
let temp = std::fs::canonicalize(std::env::temp_dir()).unwrap();
|
||||
assert_eq!(free_space(&temp).unwrap().1, volume_space(&temp).unwrap().1);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn free_space_reads_an_unlisted_mount_on_macos() {
|
||||
// `/dev` is devfs; a zero total counts as unknown, so compare only when it is known.
|
||||
if let Some((_, total)) = free_space(Path::new("/dev")) {
|
||||
assert_ne!(total, free_space(Path::new("/")).unwrap().1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
#[test]
|
||||
fn free_space_of_a_missing_directory_is_unknown() {
|
||||
let missing = std::env::temp_dir().join(format!("photocraft-missing-{}", std::process::id()));
|
||||
assert_eq!(free_space(&missing), None);
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
#[test]
|
||||
fn a_volume_with_no_total_is_unknown() {
|
||||
assert_eq!(known_space(0, 0), None);
|
||||
assert_eq!(known_space(5, 0), None);
|
||||
assert_eq!(known_space(0, 10), Some((0, 10)));
|
||||
assert_eq!(known_space(5, 10), Some((5, 10)));
|
||||
}
|
||||
|
||||
static CAPPED_GATE: (Mutex<bool>, Condvar) = (Mutex::new(false), Condvar::new());
|
||||
|
||||
fn hold_capped(dir: &Path) {
|
||||
if dir.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("photocraft-capped-")) {
|
||||
let mut open = CAPPED_GATE.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
while !*open {
|
||||
open = CAPPED_GATE.1.wait(open).unwrap_or_else(PoisonError::into_inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_threads_stay_capped_and_single_flight() {
|
||||
set_query_hook_for_tests(Some(hold_capped));
|
||||
let base = std::env::temp_dir().join(format!("photocraft-capped-{}", std::process::id()));
|
||||
let first = start_query(&base, false).unwrap();
|
||||
let again = start_query(&base, false).unwrap();
|
||||
assert!(Arc::ptr_eq(&first.0, &again.0) && first.1 == again.1, "the same question must not start a second thread");
|
||||
let mut started = 1;
|
||||
for i in 0..2 * MAX_QUERIES {
|
||||
if start_query(&base.join(format!("photocraft-capped-{i}")), false).is_some() {
|
||||
started += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(started, MAX_QUERIES);
|
||||
// Exercise the real growth path while every query slot is occupied. A separate manager
|
||||
// keeps this check independent of other tests' process-wide scratch configuration.
|
||||
let file = ScratchFile::create(&base).unwrap();
|
||||
let manager = Manager {
|
||||
failed: AtomicUsize::new(0),
|
||||
read_errors: AtomicU64::new(0),
|
||||
resident: AtomicUsize::new(0),
|
||||
live: AtomicUsize::new(0),
|
||||
budget: AtomicUsize::new(1),
|
||||
paused: AtomicBool::new(false),
|
||||
epoch: AtomicU64::new(0),
|
||||
space_limit: AtomicU64::new(u64::MAX),
|
||||
next_space_check: AtomicU64::new(0),
|
||||
recovering: AtomicBool::new(false),
|
||||
space_unmeasured: AtomicBool::new(false),
|
||||
registry: Mutex::new(Registry { cells: Vec::new(), hand: 0 }),
|
||||
config: Mutex::new(Config {
|
||||
dir: Some(base.join("growth")),
|
||||
file: None,
|
||||
last_error: None,
|
||||
budget: 1,
|
||||
paused: None,
|
||||
backoff: RETRY_FIRST,
|
||||
size_cap: None,
|
||||
room: None,
|
||||
}),
|
||||
evictions: AtomicU64::new(0),
|
||||
reloads: AtomicU64::new(0),
|
||||
written: AtomicU64::new(0),
|
||||
};
|
||||
let allowed = manager.has_room(&file);
|
||||
let next_check = manager.next_space_check.load(Ordering::Relaxed);
|
||||
let unmeasured = manager.space_unmeasured.load(Ordering::Relaxed);
|
||||
*CAPPED_GATE.0.lock().unwrap_or_else(PoisonError::into_inner) = true;
|
||||
CAPPED_GATE.1.notify_all();
|
||||
let start = Instant::now();
|
||||
while query_threads_for_tests() != 0 {
|
||||
assert!(start.elapsed() < Duration::from_secs(30), "queries never finished");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
set_query_hook_for_tests(None);
|
||||
assert!(allowed, "the last measured growth limit still applies");
|
||||
assert_eq!(next_check, 0, "a rejected growth query must stay due");
|
||||
assert!(unmeasured, "a rejected growth query must not report the old measurement as current");
|
||||
drop(file);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_read_retains_backing_and_blocks_commit_until_repaired() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-read-failure-{}", std::process::id()));
|
||||
|
||||
@@ -448,6 +448,27 @@ fn content_bounds_and_prune() {
|
||||
assert_eq!(s.content_bounds(), Rect::new(300, 10, 310, 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_in_batches_drops_what_prune_drops() {
|
||||
let mut whole = Surface::new(PixelFormat::RGBA8);
|
||||
whole.fill_rect(Rect::new(300, 10, 310, 20), &[1.0, 1.0, 1.0, 1.0]);
|
||||
whole.write_pixel(-5, -5, &[0.0, 0.0, 0.0, 1.0]);
|
||||
whole.write_pixel(-5, -5, &[0.0, 0.0, 0.0, 0.0]);
|
||||
whole.fill_rect(Rect::new(600, 600, 610, 610), &[1.0, 0.0, 0.0, 1.0]);
|
||||
let mut stepped = whole.clone();
|
||||
whole.prune();
|
||||
let mut cursor = stepped.prune_cursor();
|
||||
let mut calls = 0;
|
||||
while !stepped.prune_batch(&mut cursor, 1) {
|
||||
calls += 1;
|
||||
assert!(calls < 100, "the prune scan never finished");
|
||||
}
|
||||
assert!(calls >= 2, "one tile per call visits every tile over several calls");
|
||||
assert_eq!(stepped.tile_count(), whole.tile_count());
|
||||
assert_eq!(stepped.content_bounds(), whole.content_bounds());
|
||||
assert_eq!(stepped.to_interleaved(whole.content_bounds()), whole.to_interleaved(whole.content_bounds()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interleaved_roundtrip_crossing_tiles() {
|
||||
let r = Rect::new(-20, 250, 280, 262);
|
||||
@@ -676,6 +697,66 @@ fn translated_matches_reading_the_moved_pixels() {
|
||||
let _ = s.translated(i32::MIN + 1, 3, all);
|
||||
}
|
||||
|
||||
/// Runs `steps` to the end with `more` always false, counting the calls it took.
|
||||
fn run_steps(mut steps: TranslateSteps) -> (Surface, usize) {
|
||||
for calls in 1..=1_000_000 {
|
||||
if let Some(out) = steps.step(&mut || false) {
|
||||
return (out, calls);
|
||||
}
|
||||
}
|
||||
panic!("the shift never finished")
|
||||
}
|
||||
|
||||
/// A shift in pieces gives the surface of the one-shot shift, bit for bit, at every depth and
|
||||
/// offset (whole tiles, off the grid, negative), over a non-zero default pixel, solid fills and
|
||||
/// sparse tiles.
|
||||
#[test]
|
||||
fn translate_steps_equal_translated() {
|
||||
for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] {
|
||||
let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]);
|
||||
let r = Rect::new(-37, 200, 530, 300);
|
||||
let v: Vec<f32> = (0..r.width() * r.height() * fmt.channels() as u32).map(|i| (i % 251) as f32 / 250.0).collect();
|
||||
s.write_region(r, &v);
|
||||
s.fill_rect(Rect::new(600, -300, 1700, 900), &vec![0.75; fmt.channels()]);
|
||||
s.write_pixel(3000, 5, &vec![0.5; fmt.channels()]);
|
||||
for (dx, dy) in [(0, 0), (256, -512), (1, 0), (-3, 7), (300, -257), (-1000, 999), (10, 7)] {
|
||||
let content = s.content_bounds();
|
||||
let (got, _) = run_steps(TranslateSteps::new(s.clone(), dx, dy, content));
|
||||
assert!(got == s.translated(dx, dy, content), "{fmt:?} by ({dx}, {dy})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each call of a shift in pieces builds at most one tile, so a large shift takes as many calls
|
||||
/// as it has source and target tiles, and none of them rebuilds everything.
|
||||
#[test]
|
||||
fn translate_steps_do_one_tile_per_call() {
|
||||
let mut s = Surface::new(PixelFormat::RGBA8);
|
||||
s.fill_rect(Rect::new(0, 0, 3 * TILE_SIZE, 2 * TILE_SIZE), &[0.1, 0.2, 0.3, 1.0]);
|
||||
s.write_pixel(5, 5, &[1.0, 0.0, 0.0, 1.0]);
|
||||
let content = s.content_bounds();
|
||||
let sources = s.tiles().count();
|
||||
let targets = s.translated(7, 3, content).tiles().count();
|
||||
let (got, calls) = run_steps(TranslateSteps::new(s.clone(), 7, 3, content));
|
||||
assert!(got == s.translated(7, 3, content));
|
||||
// One call per source tile scanned, one to start building, one per target tile built (a few
|
||||
// of them hold only the default pixel and are not kept) and one that hands the result over.
|
||||
assert!(calls >= sources + targets + 2, "{calls} calls for {sources} sources and {targets} targets");
|
||||
assert!(calls <= sources + targets + 2 + 8, "{calls} calls for {sources} sources and {targets} targets");
|
||||
// Asked to go on, a call does more than one unit.
|
||||
let mut steps = TranslateSteps::new(s.clone(), 7, 3, content);
|
||||
let mut left = 4;
|
||||
assert!(
|
||||
steps
|
||||
.step(&mut || {
|
||||
left -= 1;
|
||||
left > 0
|
||||
})
|
||||
.is_none()
|
||||
);
|
||||
assert!(steps.progress() > 0.0 && steps.progress() < 1.0);
|
||||
}
|
||||
|
||||
/// Many references to one payload, moved off the tile grid: the rebuilt tiles that read the
|
||||
/// same source tiles at the same offset are one tile, not a copy each.
|
||||
#[test]
|
||||
|
||||
@@ -4,6 +4,25 @@
|
||||
|
||||
use photocraft_raster::spill;
|
||||
|
||||
/// The room, once no query is outstanding. A query that outlives its 2 s wait on a slow machine
|
||||
/// counts as no answer, and its late answer would change the status between two reads, so ask again
|
||||
/// until the room and the status describe the same answer.
|
||||
fn answered_capacity() -> Option<u64> {
|
||||
let mut room = None;
|
||||
let started = std::time::Instant::now();
|
||||
for _ in 0..10 {
|
||||
room = spill::scratch_capacity();
|
||||
while spill::query_threads_for_tests() != 0 {
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(30), "scratch capacity query did not finish within 30 seconds: {:?}", spill::stats());
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
if room.is_none() == spill::free_space_unmeasured() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
room
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scratch_capacity_follows_spilling_the_size_limit_and_pauses() {
|
||||
let root = std::env::temp_dir().join(format!("photocraft-scratch-capacity-{}", std::process::id()));
|
||||
@@ -15,11 +34,31 @@ fn scratch_capacity_follows_spilling_the_size_limit_and_pauses() {
|
||||
|
||||
spill::configure(Some(&dir), 1 << 20).unwrap();
|
||||
assert!(spill::enabled() && !spill::paused());
|
||||
// With no size limit, the flag says exactly when the capacity is unknown.
|
||||
let unknown = answered_capacity().is_none();
|
||||
assert_eq!(spill::free_space_unmeasured(), unknown);
|
||||
// The free-space reserve applies; an unknown volume without a size limit promises nothing.
|
||||
if let Some(room) = spill::scratch_capacity() {
|
||||
assert!(room < u64::MAX / 2, "the reserve and margin are applied: {room}");
|
||||
}
|
||||
|
||||
let measurable = answered_capacity().is_some();
|
||||
|
||||
// A folder that stops answering is flagged and clears once it answers again. Windows keeps the
|
||||
// open scratch file's folder, so this part needs a folder that can be removed.
|
||||
if std::fs::remove_dir_all(&dir).is_ok() {
|
||||
assert_eq!(spill::scratch_capacity(), None);
|
||||
assert!(spill::free_space_unmeasured());
|
||||
assert!(spill::stats().free_space_unmeasured);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let unknown = answered_capacity().is_none();
|
||||
assert_eq!(spill::free_space_unmeasured(), unknown);
|
||||
assert_eq!(spill::stats().free_space_unmeasured, unknown);
|
||||
if measurable {
|
||||
assert!(!unknown, "the folder answers again: its room must be known again");
|
||||
}
|
||||
}
|
||||
|
||||
// The Scratch Size Limit bounds it, less the 1/64 margin, whatever the volume has free.
|
||||
let cap = 64u64 << 20;
|
||||
spill::set_size_cap(Some(cap));
|
||||
@@ -36,5 +75,6 @@ fn scratch_capacity_follows_spilling_the_size_limit_and_pauses() {
|
||||
spill::set_size_cap(None);
|
||||
spill::configure(None, 0).unwrap();
|
||||
assert_eq!(spill::scratch_capacity(), None);
|
||||
assert!(!spill::free_space_unmeasured());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
//! A scratch folder that stops answering (a dead hard-mounted network share) must not freeze
|
||||
//! anything: status reads stay prompt, opening and measuring wait a bounded time, retries do not
|
||||
//! pile up threads, leaving the folder works, and a late answer applies only to the folder it
|
||||
//! was about.
|
||||
//!
|
||||
//! One test function: the spill manager is process-wide, so its steps must not interleave.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Condvar, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_geom::{Rect, TILE_SIZE};
|
||||
use photocraft_raster::{Surface, spill};
|
||||
|
||||
const TILE_BYTES: usize = (TILE_SIZE * TILE_SIZE) as usize * 4;
|
||||
|
||||
/// Folders whose name starts with "hung" stall their queries while this is on.
|
||||
static STALL: AtomicBool = AtomicBool::new(false);
|
||||
/// Queries that reached the stall since the last reset.
|
||||
static ENTERED: AtomicUsize = AtomicUsize::new(0);
|
||||
/// `true` once the stalled queries may go on.
|
||||
static GATE: (Mutex<bool>, Condvar) = (Mutex::new(false), Condvar::new());
|
||||
|
||||
fn stall(dir: &Path) {
|
||||
let hung = dir.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("hung"));
|
||||
if !STALL.load(Ordering::SeqCst) || !hung {
|
||||
return;
|
||||
}
|
||||
ENTERED.fetch_add(1, Ordering::SeqCst);
|
||||
let mut open = GATE.0.lock().unwrap();
|
||||
while !*open {
|
||||
open = GATE.1.wait(open).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn arm() {
|
||||
ENTERED.store(0, Ordering::SeqCst);
|
||||
*GATE.0.lock().unwrap() = false;
|
||||
STALL.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn release() {
|
||||
STALL.store(false, Ordering::SeqCst);
|
||||
*GATE.0.lock().unwrap() = true;
|
||||
GATE.1.notify_all();
|
||||
}
|
||||
|
||||
fn poll_until(what: &str, cond: impl Fn() -> bool) {
|
||||
let start = Instant::now();
|
||||
while !cond() {
|
||||
assert!(start.elapsed() < Duration::from_secs(30), "timed out waiting for {what}: {:?}", spill::stats());
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` and require that it returns well before a query's wait.
|
||||
fn prompt<T>(what: &str, f: impl FnOnce() -> T) -> T {
|
||||
let start = Instant::now();
|
||||
let out = f();
|
||||
assert!(start.elapsed() < Duration::from_millis(1500), "{what} took {:?}", start.elapsed());
|
||||
out
|
||||
}
|
||||
|
||||
/// A query's 2 s wait plus a scheduling allowance.
|
||||
const QUERY_DEADLINE: Duration = Duration::from_secs(6);
|
||||
|
||||
/// Run `f` and require that it returns within [`QUERY_DEADLINE`].
|
||||
fn bounded<T>(what: &str, f: impl FnOnce() -> T) -> T {
|
||||
let start = Instant::now();
|
||||
let out = f();
|
||||
assert!(start.elapsed() < QUERY_DEADLINE, "{what} took {:?}", start.elapsed());
|
||||
out
|
||||
}
|
||||
|
||||
fn rgba8() -> PixelFormat {
|
||||
PixelFormat { mode: ColorMode::Rgb, sample: SampleType::U8, alpha: true }
|
||||
}
|
||||
|
||||
/// Incompressible bytes, different per seed.
|
||||
fn noise(seed: u32, len: usize) -> Vec<u8> {
|
||||
let mut x = seed.wrapping_mul(2_654_435_761).max(1);
|
||||
(0..len)
|
||||
.map(|_| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
x as u8
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn surface(seed: u32, n: i32) -> Surface {
|
||||
let mut s = Surface::new(rgba8());
|
||||
for i in 0..n {
|
||||
let r = Rect::from_xywh(i * TILE_SIZE, 0, TILE_SIZE as u32, TILE_SIZE as u32);
|
||||
s.write_interleaved(r, &noise(seed + i as u32, TILE_BYTES));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_that_stops_answering_never_freezes_the_app() {
|
||||
let root = std::env::temp_dir().join(format!("photocraft-scratch-slow-{}", std::process::id()));
|
||||
let good = root.join("good");
|
||||
let good2 = root.join("good2");
|
||||
let hung1 = root.join("hung1");
|
||||
let hung2 = root.join("hung2");
|
||||
let hung3 = root.join("hung3");
|
||||
spill::set_query_hook_for_tests(Some(stall));
|
||||
|
||||
// A. A healthy folder.
|
||||
spill::configure(Some(&good), 1 << 20).unwrap();
|
||||
assert!(spill::enabled() && !spill::paused());
|
||||
let measurable = spill::scratch_capacity().is_some();
|
||||
|
||||
// B. Configuring a folder that never answers: status reads stay prompt meanwhile (they
|
||||
// blocked on the config lock before), and configure gives up after its wait.
|
||||
arm();
|
||||
let began = Instant::now();
|
||||
let configuring = {
|
||||
let hung1 = hung1.clone();
|
||||
std::thread::spawn(move || spill::configure(Some(&hung1), 1 << 20))
|
||||
};
|
||||
poll_until("the first query to start", || ENTERED.load(Ordering::SeqCst) == 1);
|
||||
prompt("last_error", spill::last_error);
|
||||
prompt("check_integrity", spill::check_integrity).ok();
|
||||
prompt("stats", spill::stats);
|
||||
prompt("free_space_unmeasured", spill::free_space_unmeasured);
|
||||
prompt("paused", spill::paused);
|
||||
let result = configuring.join().unwrap();
|
||||
assert!(began.elapsed() < QUERY_DEADLINE, "configure of a hung folder took {:?}", began.elapsed());
|
||||
assert!(result.as_ref().err().is_some_and(|e| e.contains("not responding")), "{result:?}");
|
||||
assert!(spill::paused() && !spill::enabled());
|
||||
assert_eq!(spill::stats().dir.as_deref(), Some(hung1.as_path()));
|
||||
|
||||
// C. Retries neither wait nor start more threads: the question is already being asked.
|
||||
for _ in 0..5 {
|
||||
spill::retry_now_for_tests();
|
||||
prompt("maintain_budget", spill::maintain_budget);
|
||||
}
|
||||
assert_eq!(ENTERED.load(Ordering::SeqCst), 1, "a retry started a second query");
|
||||
assert!(spill::paused());
|
||||
|
||||
// D. Leaving the dead folder works while its query is stuck.
|
||||
prompt("configure away from a hung folder", || spill::configure(Some(&good2), 1 << 20)).unwrap();
|
||||
assert!(spill::enabled() && !spill::paused());
|
||||
|
||||
// E. The stuck query's late answer is about a folder that is no longer current: discarded.
|
||||
release();
|
||||
poll_until("the stuck query to settle", || spill::query_threads_for_tests() == 0);
|
||||
let st = spill::stats();
|
||||
assert_eq!(st.dir.as_deref(), Some(good2.as_path()), "{st:?}");
|
||||
assert!(spill::enabled() && !spill::paused() && st.last_error.is_none(), "{st:?}");
|
||||
|
||||
// F. A late answer for the current folder applies: spilling resumes by itself.
|
||||
arm();
|
||||
let result = bounded("configure of a second hung folder", || spill::configure(Some(&hung2), 1 << 20));
|
||||
assert!(result.is_err());
|
||||
assert!(spill::paused());
|
||||
release();
|
||||
poll_until("the late answer to resume spilling", || spill::enabled() && !spill::paused() && spill::last_error().is_none());
|
||||
assert_eq!(spill::stats().dir.as_deref(), Some(hung2.as_path()));
|
||||
|
||||
// G. The open folder stops answering when measured: no answer counts as unknown, spilling
|
||||
// goes on, and asking again costs nothing.
|
||||
spill::configure(Some(&hung3), 1 << 20).unwrap();
|
||||
arm();
|
||||
assert_eq!(bounded("scratch_capacity", spill::scratch_capacity), None);
|
||||
assert!(spill::free_space_unmeasured());
|
||||
assert!(spill::stats().free_space_unmeasured);
|
||||
assert!(spill::enabled() && !spill::paused());
|
||||
for _ in 0..5 {
|
||||
assert_eq!(prompt("scratch_capacity", spill::scratch_capacity), None);
|
||||
}
|
||||
assert_eq!(ENTERED.load(Ordering::SeqCst), 1, "asking again started a second query");
|
||||
release();
|
||||
if measurable {
|
||||
poll_until("the late answer to measure the volume", || !spill::free_space_unmeasured());
|
||||
}
|
||||
|
||||
poll_until("the previous query to finish", || spill::query_threads_for_tests() == 0);
|
||||
|
||||
// H. The growth check never stalls eviction: tiles still spill while it is unanswered.
|
||||
spill::set_budget(8 * TILE_BYTES);
|
||||
arm();
|
||||
spill::set_size_cap(Some(1 << 50));
|
||||
let trigger_tiles = surface(1, 32);
|
||||
poll_until("the growth query to reach the stall", || ENTERED.load(Ordering::SeqCst) >= 1);
|
||||
let evictions = spill::stats().evictions;
|
||||
let tiles = surface(33, 32);
|
||||
prompt("settle", spill::settle);
|
||||
assert!(spill::stats().evictions > evictions, "{:?}", spill::stats());
|
||||
poll_until("the unanswered growth check to count as unknown", spill::free_space_unmeasured);
|
||||
release();
|
||||
if measurable {
|
||||
poll_until("the growth check to be answered", || !spill::free_space_unmeasured());
|
||||
}
|
||||
spill::set_size_cap(None);
|
||||
|
||||
// Cleanup.
|
||||
spill::set_query_hook_for_tests(None);
|
||||
drop(tiles);
|
||||
drop(trigger_tiles);
|
||||
spill::configure(None, 0).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ name = "photocraft-tablet"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Pen tablet pressure, tilt, rotation and eraser end on macOS (AppKit) and Linux X11 (XInput2), and barrel button on Windows"
|
||||
description = "Pen tablet pressure, tilt, rotation and eraser end on macOS (AppKit), Linux X11 (XInput2) and Windows (WinTab), and barrel button on Windows"
|
||||
|
||||
# The one isolated `unsafe` helper crate (see AGENTS.md, Never crash): the AppKit event
|
||||
# monitor on macOS and the WH_GETMESSAGE pointer hook on Windows need platform interop. Only
|
||||
@@ -31,6 +31,15 @@ objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
x11rb = { version = "=0.13.2", default-features = false, features = ["xinput"] }
|
||||
|
||||
# WinTab 1.4: a system context on PhotoCraft's real window supplies pressure, tilt, rotation and
|
||||
# the eraser end while Windows Ink is disabled. `wintab` safely wraps the vendor's wintab32.dll,
|
||||
# loaded at run time; only the Windows target builds it. `windows` is pinned to the version
|
||||
# `wintab` uses.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
log = { workspace = true }
|
||||
wintab = "=0.1.1"
|
||||
windows = { version = "=0.62.2", features = ["Win32_Foundation"] }
|
||||
|
||||
# Tests build real tablet NSEvents (from CGEvents) and read them through the monitor's path.
|
||||
[target.'cfg(target_os = "macos")'.dev-dependencies]
|
||||
objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "block2", "NSEvent", "NSGraphicsContext", "objc2-core-graphics", "NSApplication", "NSResponder"] }
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
//! - **Windows** ([`windows::Monitor`]): a thread-local message hook inspects `WM_POINTER*`
|
||||
//! messages on the UI thread's message queue to read `PEN_FLAG_BARREL` (`GetPointerPenInfo`),
|
||||
//! which winit 0.30 drops by mapping pen inputs to touch events.
|
||||
//! - **Windows WinTab** ([`wintab`]): with Windows Ink disabled for the tablet, a WinTab 1.4
|
||||
//! system context on PhotoCraft's window supplies pressure, tilt, rotation and the eraser end.
|
||||
//! The vendor driver still moves the cursor; [`wintab::poll`] is called once per frame.
|
||||
//! AppKit's monitor API and Windows' thread hook need OS interop, so `macos.rs` and `windows.rs`
|
||||
//! allow `unsafe` (an isolated, tested helper crate with `SAFETY:`
|
||||
//! comments on every block).
|
||||
@@ -37,6 +40,8 @@ pub mod xi;
|
||||
pub mod macos;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub mod windows;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub mod wintab;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod x11;
|
||||
|
||||
|
||||
@@ -102,6 +102,9 @@ unsafe extern "system" fn get_msg_proc(code: i32, w_param: usize, l_param: isize
|
||||
// SAFETY: Win32 guarantees that for code >= 0, l_param points to a valid MSG struct
|
||||
// dispatched to this thread's message queue.
|
||||
let msg = unsafe { &*(l_param as *const MSG) };
|
||||
// The WinTab backend shares this thread hook: it decodes the driver's proximity
|
||||
// messages (and ignores everything else) to clear a pen that left the tablet.
|
||||
crate::wintab::on_message(msg.message, msg.w_param, msg.l_param);
|
||||
match msg.message {
|
||||
WM_POINTERDOWN | WM_POINTERUPDATE => {
|
||||
let pointer_id = (msg.w_param & 0xFFFF) as u32;
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
//! WinTab 1.4 backend for Windows.
|
||||
//!
|
||||
//! The app opens a WinTab context on its real top-level window and polls queued packets once per
|
||||
//! frame. This module only translates Wintab packets into [`Sample`]s; it does not synthesise
|
||||
//! pointer events. With Windows Ink disabled for the tablet, the vendor driver provides the
|
||||
//! mouse cursor while this module provides pressure, tilt, rotation and the eraser flag.
|
||||
//!
|
||||
//! Devices without orientation axes (pressure-only tablets) are opened with a packet that asks
|
||||
//! only for the fields the driver reports; their tilt is neutral rather than a made-up value.
|
||||
//!
|
||||
//! The context is thread-local because Wintab contexts belong to the thread and window that
|
||||
//! opened them. [`install`] and [`poll`] must therefore run on the UI thread.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::ffi::c_void;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use windows::Win32::Foundation::{HWND, LPARAM, WPARAM};
|
||||
|
||||
use crate::{Error, Sample};
|
||||
|
||||
wintab::packet! {
|
||||
struct PenPacket { status, buttons, x, y, normal_pressure, orientation }
|
||||
}
|
||||
|
||||
wintab::packet! {
|
||||
struct PressurePacket { status, buttons, x, y, normal_pressure }
|
||||
}
|
||||
|
||||
/// The open context. A device that reports orientation gets tilt and rotation; a pressure-only
|
||||
/// device gets a packet without the orientation field, so a zeroed field never becomes a tilt.
|
||||
enum Backend {
|
||||
Oriented { context: wintab::Context<PenPacket>, axes: [wintab::Axis; 3] },
|
||||
PressureOnly { context: wintab::Context<PressurePacket> },
|
||||
}
|
||||
|
||||
struct State {
|
||||
backend: Backend,
|
||||
pressure_axis: wintab::Axis,
|
||||
last_packet: Instant,
|
||||
emitted: bool,
|
||||
focused: bool,
|
||||
/// The pen is inside the tablet's sensing range (`WT_PROXIMITY`, hardware transitions).
|
||||
proximity_in: bool,
|
||||
/// Requests a frame when a WinTab message arrives, so pressure-only strokes update without
|
||||
/// cursor movement.
|
||||
wake: Box<dyn Fn()>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static STATE: RefCell<Option<State>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Opens a WinTab system context on `hwnd`.
|
||||
///
|
||||
/// Call on the UI thread. A previous context on this thread is replaced, so the caller keeps the
|
||||
/// app's normal single-window lifetime. The context is polled with [`poll`]. `wake` is called from
|
||||
/// the thread's message hook for every WinTab message: a frame is then requested even when the
|
||||
/// pen only changes pressure (no cursor movement, no other input event).
|
||||
pub fn install(hwnd: isize, wake: Box<dyn Fn()>) -> Result<(), Error> {
|
||||
if hwnd == 0 {
|
||||
return Err(Error::Unsupported("no window handle".into()));
|
||||
}
|
||||
let wintab = wintab::Wintab::load().map_err(|e| Error::Platform(e.to_string()))?;
|
||||
let device = wintab.device(0).ok_or_else(|| Error::Unsupported("no Wintab digitizer".into()))?;
|
||||
let pressure_axis = device.pressure.ok_or_else(|| Error::Unsupported("Wintab device has no pressure axis".into()))?;
|
||||
let hwnd = HWND(hwnd as *mut c_void);
|
||||
let options = wintab::ContextOptions::new().system(true).name("PhotoCraft WinTab");
|
||||
// Ask only for the fields the device reports: a pressure-only tablet never fills
|
||||
// orientation, and reading a zeroed orientation would invent a maximum tilt.
|
||||
let backend = match device.orientation {
|
||||
Some(axes) => {
|
||||
let context = wintab.open::<PenPacket>(hwnd, &options).map_err(|e| Error::Platform(e.to_string()))?;
|
||||
if let Err(error) = context.overlap(true) {
|
||||
log::warn!("WinTab: could not take overlap priority: {error}");
|
||||
}
|
||||
Backend::Oriented { context, axes }
|
||||
}
|
||||
None => {
|
||||
let context = wintab.open::<PressurePacket>(hwnd, &options).map_err(|e| Error::Platform(e.to_string()))?;
|
||||
if let Err(error) = context.overlap(true) {
|
||||
log::warn!("WinTab: could not take overlap priority: {error}");
|
||||
}
|
||||
Backend::PressureOnly { context }
|
||||
}
|
||||
};
|
||||
STATE.with_borrow_mut(|slot| {
|
||||
*slot = Some(State { backend, pressure_axis, last_packet: Instant::now(), emitted: false, focused: false, proximity_in: true, wake });
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drains queued packets and reports the newest sample.
|
||||
///
|
||||
/// Reports `Some` while a pen is in use, `None` once the pen has left the tablet. Leaving is the
|
||||
/// packet's proximity status, not a quiet period: a pen held still may send no packets for a
|
||||
/// while, and treating that as left painted a held airbrush build-up at mouse pressure. A long
|
||||
/// timeout remains only as a fallback for drivers that never report the leave.
|
||||
///
|
||||
/// Coordinates in the packet are not used: with Windows Ink off, the vendor driver moves the
|
||||
/// normal cursor, and PhotoCraft's existing pointer path supplies the position.
|
||||
///
|
||||
/// `focused` is whether the app's window has focus. Another tablet application can take the top
|
||||
/// WinTab overlap priority; when PhotoCraft is activated again it has to ask for it back. The
|
||||
/// window procedure belongs to winit, so focus from the app's input is the activation signal.
|
||||
pub fn poll(focused: bool, callback: &dyn Fn(Option<Sample>)) {
|
||||
STATE.with_borrow_mut(|slot| {
|
||||
let Some(state) = slot.as_mut() else { return };
|
||||
if focused && !state.focused {
|
||||
let result = match &state.backend {
|
||||
Backend::Oriented { context, .. } => context.overlap(true),
|
||||
Backend::PressureOnly { context } => context.overlap(true),
|
||||
};
|
||||
if let Err(error) = result {
|
||||
log::warn!("WinTab: could not take overlap priority: {error}");
|
||||
}
|
||||
} else if !focused && state.focused {
|
||||
let result = match &state.backend {
|
||||
Backend::Oriented { context, .. } => context.overlap(false),
|
||||
Backend::PressureOnly { context } => context.overlap(false),
|
||||
};
|
||||
if let Err(error) = result {
|
||||
log::warn!("WinTab: could not release overlap priority: {error}");
|
||||
}
|
||||
}
|
||||
state.focused = focused;
|
||||
let State { backend, pressure_axis, last_packet, emitted, proximity_in, .. } = state;
|
||||
match backend {
|
||||
Backend::Oriented { context, axes } => {
|
||||
let mut packets = Vec::new();
|
||||
context.drain(&mut packets);
|
||||
for packet in packets {
|
||||
if packet.status.out_of_context() {
|
||||
if *emitted {
|
||||
*emitted = false;
|
||||
callback(None);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let sample = sample(&packet, pressure_axis, axes);
|
||||
*last_packet = Instant::now();
|
||||
*emitted = true;
|
||||
callback(Some(sample));
|
||||
}
|
||||
}
|
||||
Backend::PressureOnly { context } => {
|
||||
let mut packets = Vec::new();
|
||||
context.drain(&mut packets);
|
||||
for packet in packets {
|
||||
if packet.status.out_of_context() {
|
||||
if *emitted {
|
||||
*emitted = false;
|
||||
callback(None);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let sample = sample_pressure(&packet, pressure_axis);
|
||||
*last_packet = Instant::now();
|
||||
*emitted = true;
|
||||
callback(Some(sample));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !*proximity_in && *emitted {
|
||||
*emitted = false;
|
||||
callback(None);
|
||||
}
|
||||
if *emitted && last_packet.elapsed() >= Duration::from_secs(60) {
|
||||
*emitted = false;
|
||||
callback(None);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Handles a WinTab window message from the thread's message hook (`windows.rs`).
|
||||
///
|
||||
/// A hardware proximity leave is a `WT_PROXIMITY` message, not a packet status: the context's
|
||||
/// `TPS_PROXIMITY` status only says the cursor left the context. Clearing the feed here covers
|
||||
/// drivers that send the hardware leave without a following out-of-context packet.
|
||||
pub(crate) fn on_message(message: u32, wparam: usize, lparam: isize) {
|
||||
// This runs inside the Win32 hook, where a panic aborts the app: a driver call under `poll`
|
||||
// that pumps this thread's messages would find `STATE` borrowed. Such a message is skipped.
|
||||
let _ = STATE.try_with(|cell| {
|
||||
let Ok(mut slot) = cell.try_borrow_mut() else { return };
|
||||
let Some(state) = slot.as_mut() else { return };
|
||||
let decoded = match &state.backend {
|
||||
Backend::Oriented { context, .. } => context.message(message, WPARAM(wparam), LPARAM(lparam)),
|
||||
Backend::PressureOnly { context } => context.message(message, WPARAM(wparam), LPARAM(lparam)),
|
||||
};
|
||||
let win_message = decoded.is_some();
|
||||
if let Some(wintab::Message::Proximity { entering, hardware }) = decoded
|
||||
&& hardware
|
||||
{
|
||||
state.proximity_in = entering;
|
||||
}
|
||||
if win_message {
|
||||
// Packets can arrive with no cursor movement; the frame then polls them.
|
||||
(state.wake)();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Closes the context on this thread.
|
||||
pub fn uninstall() {
|
||||
STATE.with_borrow_mut(|slot| *slot = None);
|
||||
}
|
||||
|
||||
/// One packet from a device with orientation axes as the UI's pen sample.
|
||||
///
|
||||
/// Angles come from the device's own axes (`TU_CIRCLE`), falling back to Wintab's usual tenths
|
||||
/// of a degree when an axis does not measure angles.
|
||||
fn sample(packet: &PenPacket, pressure: &wintab::Axis, orientation: &[wintab::Axis; 3]) -> Sample {
|
||||
let raw = packet.orientation;
|
||||
let degrees = |index: usize, value: i32| orientation[index].degrees(value).map_or(value as f32 / 10.0, |degrees| degrees as f32);
|
||||
let azimuth = degrees(0, raw.azimuth).to_radians();
|
||||
// Wintab altitude is the angle from the tablet plane (0 = flat, 90 = upright); W3C tilt is
|
||||
// the angle from the perpendicular, per axis: atan2 of the in-plane projection over height.
|
||||
// Wintab azimuth 0 points at the tablet's top and grows clockwise, while W3C +x is right and
|
||||
// +y towards the user, so the in-plane components are (sin(azimuth), -cos(azimuth)).
|
||||
let elevation = degrees(1, raw.altitude).abs().to_radians();
|
||||
let in_plane_x = elevation.cos() * azimuth.sin();
|
||||
let in_plane_y = -(elevation.cos() * azimuth.cos());
|
||||
let height = elevation.sin();
|
||||
Sample {
|
||||
pressure: pressure.normalize(packet.normal_pressure as i32),
|
||||
tilt_x: in_plane_x.atan2(height).to_degrees(),
|
||||
tilt_y: in_plane_y.atan2(height).to_degrees(),
|
||||
rotation: degrees(2, raw.twist),
|
||||
eraser: packet.status.inverted(),
|
||||
}
|
||||
.sanitized()
|
||||
}
|
||||
|
||||
/// One packet from a device without orientation axes: pressure and the eraser end, neutral tilt.
|
||||
fn sample_pressure(packet: &PressurePacket, pressure: &wintab::Axis) -> Sample {
|
||||
Sample { pressure: pressure.normalize(packet.normal_pressure as i32), tilt_x: 0.0, tilt_y: 0.0, rotation: 0.0, eraser: packet.status.inverted() }
|
||||
.sanitized()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use wintab::Units;
|
||||
|
||||
fn pressure_axis() -> wintab::Axis {
|
||||
wintab::Axis { min: 0, max: 32767, units: Units::None, resolution: 0.0 }
|
||||
}
|
||||
|
||||
fn angle_axis() -> wintab::Axis {
|
||||
wintab::Axis { min: 0, max: 3599, units: Units::Circle, resolution: 3600.0 }
|
||||
}
|
||||
|
||||
fn axes() -> [wintab::Axis; 3] {
|
||||
[angle_axis(), angle_axis(), angle_axis()]
|
||||
}
|
||||
|
||||
fn packet(normal_pressure: u32) -> PenPacket {
|
||||
PenPacket { status: wintab::Status(0), buttons: wintab::Buttons(0), x: 0, y: 0, normal_pressure, orientation: wintab::Orientation::default() }
|
||||
}
|
||||
|
||||
fn pressure_packet(normal_pressure: u32) -> PressurePacket {
|
||||
PressurePacket { status: wintab::Status(0), buttons: wintab::Buttons(0), x: 0, y: 0, normal_pressure }
|
||||
}
|
||||
|
||||
/// Pressure is normalized through the device's own axis.
|
||||
#[test]
|
||||
fn pressure_maps_through_the_device_axis() {
|
||||
let axes = axes();
|
||||
let s = sample(&packet(16384), &pressure_axis(), &axes);
|
||||
assert!((s.pressure - 0.5).abs() < 0.01, "{}", s.pressure);
|
||||
let s = sample(&packet(0), &pressure_axis(), &axes);
|
||||
assert_eq!(s.pressure, 0.0);
|
||||
}
|
||||
|
||||
/// The inverted status bit is the eraser end.
|
||||
#[test]
|
||||
fn eraser_comes_from_the_inverted_status() {
|
||||
let axes = axes();
|
||||
let inverted = PenPacket { status: wintab::Status(wintab::sys::TPS_INVERT), ..packet(0) };
|
||||
assert!(sample(&inverted, &pressure_axis(), &axes).eraser);
|
||||
assert!(!sample(&packet(0), &pressure_axis(), &axes).eraser);
|
||||
}
|
||||
|
||||
/// Orientation axes are converted to degrees for the W3C tilt projection.
|
||||
#[test]
|
||||
fn orientation_axes_report_degrees() {
|
||||
let axes = axes();
|
||||
let tilted = PenPacket { orientation: wintab::Orientation { azimuth: 450, altitude: 300, twist: 900 }, ..packet(0) };
|
||||
let sample = sample(&tilted, &pressure_axis(), &axes);
|
||||
assert!((sample.tilt_x - 50.8).abs() < 0.1, "{}", sample.tilt_x);
|
||||
assert!((sample.tilt_y + 50.8).abs() < 0.1, "{}", sample.tilt_y);
|
||||
assert!((sample.rotation - 90.0).abs() < 0.1, "{}", sample.rotation);
|
||||
}
|
||||
|
||||
/// A pressure-only device keeps pressure and the eraser end, with neutral tilt.
|
||||
#[test]
|
||||
fn pressure_only_devices_get_pressure_and_neutral_tilt() {
|
||||
let s = sample_pressure(&pressure_packet(16384), &pressure_axis());
|
||||
assert!((s.pressure - 0.5).abs() < 0.01, "{}", s.pressure);
|
||||
assert_eq!((s.tilt_x, s.tilt_y, s.rotation), (0.0, 0.0, 0.0));
|
||||
let inverted = PressurePacket { status: wintab::Status(wintab::sys::TPS_INVERT), ..pressure_packet(0) };
|
||||
assert!(sample_pressure(&inverted, &pressure_axis()).eraser);
|
||||
}
|
||||
|
||||
/// Wintab azimuth 0 is the tablet top; W3C axes are right and toward the user.
|
||||
#[test]
|
||||
fn cardinal_azimuths_match_w3c_tilt() {
|
||||
let axes = axes();
|
||||
let tilt = |azimuth: i32| {
|
||||
let p = PenPacket { orientation: wintab::Orientation { azimuth, altitude: 450, twist: 0 }, ..packet(0) };
|
||||
sample(&p, &pressure_axis(), &axes)
|
||||
};
|
||||
let top = tilt(0);
|
||||
assert!(top.tilt_x.abs() < 0.1 && (top.tilt_y + 45.0).abs() < 0.1, "{top:?}");
|
||||
let right = tilt(900);
|
||||
assert!((right.tilt_x - 45.0).abs() < 0.1 && right.tilt_y.abs() < 0.1, "{right:?}");
|
||||
let bottom = tilt(1800);
|
||||
assert!(bottom.tilt_x.abs() < 0.1 && (bottom.tilt_y - 45.0).abs() < 0.1, "{bottom:?}");
|
||||
let left = tilt(2700);
|
||||
assert!((left.tilt_x + 45.0).abs() < 0.1 && left.tilt_y.abs() < 0.1, "{left:?}");
|
||||
}
|
||||
|
||||
/// An upright pen has no tilt; a flat one has the most.
|
||||
#[test]
|
||||
fn an_upright_pen_has_no_tilt_and_a_flat_one_has_the_most() {
|
||||
let axes = axes();
|
||||
let upright = PenPacket { orientation: wintab::Orientation { azimuth: 0, altitude: 900, twist: 0 }, ..packet(0) };
|
||||
let s = sample(&upright, &pressure_axis(), &axes);
|
||||
assert!(s.tilt_x.abs() < 0.1 && s.tilt_y.abs() < 0.1, "{s:?}");
|
||||
let flat = PenPacket { orientation: wintab::Orientation { azimuth: 0, altitude: 0, twist: 0 }, ..packet(0) };
|
||||
let s = sample(&flat, &pressure_axis(), &axes);
|
||||
assert!(s.tilt_x.abs() < 0.1 && (s.tilt_y + 90.0).abs() < 0.1, "{s:?}");
|
||||
}
|
||||
}
|
||||
+43
-7
@@ -136,18 +136,30 @@ fn os_locale() -> Option<String> {
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn os_locale() -> Option<String> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
let out = std::process::Command::new("reg")
|
||||
.args(["query", "HKCU\\Control Panel\\International", "/v", "LocaleName"])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()
|
||||
.ok()?;
|
||||
let out = locale_query().output().ok()?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
// " LocaleName REG_SZ ja-JP"
|
||||
text.lines().find(|l| l.contains("LocaleName")).and_then(|l| l.split_whitespace().last()).map(str::to_string)
|
||||
}
|
||||
|
||||
/// `reg query` for the UI locale, with `reg.exe` by full path: by bare name, Windows first looks in
|
||||
/// the app's own folder, so a `reg.exe` lying next to a portable PhotoCraft would start (#9666).
|
||||
#[cfg(target_os = "windows")]
|
||||
fn locale_query() -> std::process::Command {
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
let mut cmd = std::process::Command::new(windows_root(std::env::var_os("SystemRoot")).join("System32").join("reg.exe"));
|
||||
cmd.args(["query", "HKCU\\Control Panel\\International", "/v", "LocaleName"]).creation_flags(CREATE_NO_WINDOW);
|
||||
cmd
|
||||
}
|
||||
|
||||
/// The Windows folder for the `SystemRoot` value `system_root`: `C:\Windows` when it is unset or
|
||||
/// not an absolute path (a relative one would resolve against the working directory).
|
||||
#[cfg(target_os = "windows")]
|
||||
fn windows_root(system_root: Option<std::ffi::OsString>) -> std::path::PathBuf {
|
||||
system_root.map(std::path::PathBuf::from).filter(|p| p.is_absolute()).unwrap_or_else(|| std::path::PathBuf::from(r"C:\Windows"))
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
fn os_locale() -> Option<String> {
|
||||
None
|
||||
@@ -654,6 +666,30 @@ mod tests {
|
||||
use super::*;
|
||||
use CjkScript::*;
|
||||
|
||||
/// `reg.exe` runs from System32, not from wherever a bare name would find one first (#9666),
|
||||
/// and the query still answers the UI locale.
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn locale_query_runs_the_system_reg() {
|
||||
let cmd = locale_query();
|
||||
let system = windows_root(std::env::var_os("SystemRoot")).join("System32").join("reg.exe");
|
||||
assert_eq!(std::path::Path::new(cmd.get_program()), system);
|
||||
assert!(os_locale().is_some_and(|l| !l.is_empty()));
|
||||
}
|
||||
|
||||
/// `SystemRoot` unset or relative (which would resolve against the working directory) falls
|
||||
/// back to `C:\Windows`.
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn the_windows_folder_falls_back_when_system_root_is_unset_or_relative() {
|
||||
use std::path::PathBuf;
|
||||
assert_eq!(windows_root(Some(r"D:\WinNT".into())), PathBuf::from(r"D:\WinNT"));
|
||||
assert_eq!(windows_root(None), PathBuf::from(r"C:\Windows"));
|
||||
assert_eq!(windows_root(Some(r"Windows".into())), PathBuf::from(r"C:\Windows"));
|
||||
assert_eq!(windows_root(Some(r"\Windows".into())), PathBuf::from(r"C:\Windows"));
|
||||
assert_eq!(windows_root(Some("".into())), PathBuf::from(r"C:\Windows"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_locale_scripts_are_distinct_from_the_non_cjk_default() {
|
||||
assert_eq!(locale_script(Some("ja_JP.UTF-8")), Some(Japanese));
|
||||
|
||||
@@ -40,6 +40,9 @@ serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# Display order of right-to-left labels (`bidi_text.rs`); already linked through usvg.
|
||||
unicode-bidi = "0.3"
|
||||
# Context-sensitive dotted/dotless I mapping for Azerbaijani and Turkish UI text.
|
||||
icu_casemap = "2.3"
|
||||
icu_locale_core = "2.3"
|
||||
base64 = "0.23"
|
||||
# Inflating the translation catalogs, stored deflated (build.rs); already linked through photocraft-io.
|
||||
flate2 = { workspace = true }
|
||||
|
||||
@@ -245,8 +245,12 @@ impl eframe::App for PhotocraftApp {
|
||||
self.finish_type_reset_logic(ctx);
|
||||
}
|
||||
|
||||
/// Drain the platform's optional WinTab queue before the frame's input is processed.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
|
||||
let frame_start = gpu_canvas::now_ms();
|
||||
if let Some(tablet_poll) = self.services.tablet_poll.as_mut() {
|
||||
tablet_poll(raw_input.focused);
|
||||
}
|
||||
// An undecorated window gets its caption back when the toolkit changes its flags
|
||||
// (maximize, restore, …): take it off again before the frame is laid out (#2246).
|
||||
if let Some(window_frame) = self.services.window_frame.as_mut() {
|
||||
|
||||
@@ -169,6 +169,8 @@ impl PhotocraftApp {
|
||||
// A real UI pass consumes the one in-flight synthetic batch (see `inject_synthetic`).
|
||||
self.begin_synthetic_pass(&ctx);
|
||||
self.hover_layer = None;
|
||||
// The contextual task bar reports itself again if this frame draws it (#10890).
|
||||
self.ui.task_bar_shown = None;
|
||||
i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language));
|
||||
// Fonts registered via set_fonts only take effect next frame; named families would panic now.
|
||||
if !self.fonts_ready {
|
||||
|
||||
@@ -69,7 +69,7 @@ use display::texture_key;
|
||||
pub(crate) use display::{cache_key, canvas_display, display_doc, display_image};
|
||||
use display::{checker, hdr_preview, sync_display_lut};
|
||||
pub use drag::{Drag, fixed_size_px, marquee_corners, marquee_px, marquee_readout, readout_in, size_readout, square_px};
|
||||
pub(crate) use drag::{angle_readout, draw_readout, draw_value_readout};
|
||||
pub(crate) use drag::{angle_readout, doc_box_corners, draw_readout, draw_value_readout};
|
||||
#[cfg(test)]
|
||||
pub(crate) use drag::{marquee_drag_ants, marquee_preview_px};
|
||||
#[cfg(test)]
|
||||
@@ -601,7 +601,8 @@ fn update_canvas_navigation(app: &mut PhotocraftApp, view: &mut View, input: Can
|
||||
let bars_id = egui::Id::unique(("pc-canvas-bars-hover", input.idx));
|
||||
let over_bars = input.ctx.data(|d| d.get_temp::<bool>(bars_id)).unwrap_or(false);
|
||||
let nav_hovered = input.response.hovered() || input.free_hover || over_bars;
|
||||
// Interface › Enable Animations off: the wheel moves the canvas without a glide (#5721).
|
||||
// Like Photoshop, a wheel notch moves the canvas the whole step in one frame, without a
|
||||
// glide (`smooth` off; #5721, #9479).
|
||||
// General › Animated Zoom: the wheel zoom eases over the frames of a notch, or is one instant step.
|
||||
// Enhanced Controls › Enable Gestures off: two fingers on a touch screen neither zoom nor
|
||||
// turn the view (#204); the mouse and trackpad are unaffected.
|
||||
@@ -613,7 +614,7 @@ fn update_canvas_navigation(app: &mut PhotocraftApp, view: &mut View, input: Can
|
||||
app.session.prefs().general.animated_zoom,
|
||||
input.wheel_owner,
|
||||
nav_hovered,
|
||||
app.session.prefs().interface.enable_animations,
|
||||
false,
|
||||
touch_gestures,
|
||||
);
|
||||
if nav_hovered {
|
||||
@@ -1367,6 +1368,20 @@ fn paint_primary_overlays(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut
|
||||
crate::slice_ui::draw_overlay(app, painter, xf);
|
||||
crate::frame_tool::draw_overlay(app, painter, xf);
|
||||
crate::frame_tool::task_bar(app, ui, xf);
|
||||
// The Crop tool's contextual task bar under its frame (#10890), on the frame's own tile only:
|
||||
// the other tiles would map the active document's frame with their own transform.
|
||||
if app.session.active_index() == Some(idx) {
|
||||
// Done asks for a fit of the cropped document (`commit_crop`): like a view menu row
|
||||
// above, the stored camera wins over this frame's copy, or the write-back drops it.
|
||||
let before = app.ui.views.get(idx).cloned();
|
||||
crate::crop_task_bar::draw(app, ui, xf);
|
||||
if let Some(now) = app.ui.views.get(idx)
|
||||
&& Some(now) != before.as_ref()
|
||||
{
|
||||
*view = now.clone();
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
crate::artboard_tool::draw_overlay(app, painter, xf);
|
||||
// Snap lines last: over the transform preview's pixels and the other overlays, which would
|
||||
// otherwise hide where the moving content lines up.
|
||||
@@ -1879,7 +1894,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
app.session.prefs().general.animated_zoom,
|
||||
wheel_owner,
|
||||
hover_here,
|
||||
app.session.prefs().interface.enable_animations,
|
||||
false,
|
||||
app.session.prefs().enhanced_controls.touch_gestures,
|
||||
)
|
||||
.is_some());
|
||||
|
||||
@@ -294,6 +294,15 @@ pub(crate) fn marquee_drag_ants(d: &Drag, xf: &ViewXform, marquee: Option<[f64;
|
||||
marquee_ants(xf, d.tool, a, b)
|
||||
}
|
||||
|
||||
/// The corners on screen of the document-axis box dragged from `a` to `b`, clockwise from its
|
||||
/// top-left: a turned parallelogram in a rotated view, as the box the release creates (the Type
|
||||
/// tools' text box, the Move tool's layer marquee).
|
||||
pub(crate) fn doc_box_corners(xf: &ViewXform, a: [f64; 2], b: [f64; 2]) -> [Pos2; 4] {
|
||||
let (x0, x1) = (a[0].min(b[0]) as f32, a[0].max(b[0]) as f32);
|
||||
let (y0, y1) = (a[1].min(b[1]) as f32, a[1].max(b[1]) as f32);
|
||||
[xf.to_screen(x0, y0), xf.to_screen(x1, y0), xf.to_screen(x1, y1), xf.to_screen(x0, y1)]
|
||||
}
|
||||
|
||||
/// The size readout shown beside the cursor while dragging a marquee: the width and height values.
|
||||
pub fn marquee_readout(r: [f64; 4]) -> [String; 2] {
|
||||
[format!("{} px", r[2] - r[0]), format!("{} px", r[3] - r[1])]
|
||||
|
||||
@@ -99,10 +99,12 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option<bool>) {
|
||||
crate::vector_ui::freeform_finish_owned(app, &d.points, d.lasso.as_ref().map_or(&[], |l| l.straight()), owner);
|
||||
}
|
||||
}
|
||||
// Photoshop: a click without dragging opens Create Rectangle / Ellipse / … instead.
|
||||
// Photoshop: a click without dragging opens Create Rectangle / Ellipse / … instead. In Path
|
||||
// mode a click adds nothing: the dialog makes a shape layer, which Path mode never draws,
|
||||
// and the click's few pixels of travel would add a speck of a subpath to the work path.
|
||||
t if crate::vector_ui::is_shape_tool(t)
|
||||
&& crate::shape_dialog::is_click(d.start, &d.points, app.point_zoom())
|
||||
&& crate::shape_dialog::open(app, t, d.start).is_some() => {}
|
||||
&& (crate::vector_ui::draws_path(&app.ui.tool_options) || crate::shape_dialog::open(app, t, d.start).is_some()) => {}
|
||||
t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.live),
|
||||
Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]),
|
||||
Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::display::{canvas_display, checker, display_doc, display_image};
|
||||
use super::drag::{
|
||||
angle_readout, draw_marquee_readout, draw_value_readout, marquee_ants, marquee_drag_ants, marquee_preview_px, single_line_drag_px, size_readout,
|
||||
angle_readout, doc_box_corners, draw_marquee_readout, draw_value_readout, marquee_ants, marquee_drag_ants, marquee_preview_px, single_line_drag_px,
|
||||
size_readout,
|
||||
};
|
||||
use super::gesture::constrained_polygon_point;
|
||||
use super::strokes::{EngineStroke, SPOT_HEALING_TRAIL, draw_smoothing_string, strokes_live};
|
||||
@@ -615,8 +616,8 @@ pub(super) fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter
|
||||
painter.circle_filled(b, 3.0, Color32::WHITE);
|
||||
}
|
||||
Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => {
|
||||
let r = Rect::from_two_pos(xf.to_screen(d.start[0] as f32, d.start[1] as f32), xf.to_screen(last[0] as f32, last[1] as f32));
|
||||
let pts = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom(), r.left_top()];
|
||||
let [p0, p1, p2, p3] = doc_box_corners(xf, d.start, last);
|
||||
let pts = [p0, p1, p2, p3, p0];
|
||||
painter.add(egui::Shape::line(pts.to_vec(), Stroke::new(1.0, Color32::WHITE)));
|
||||
painter.add(egui::Shape::dashed_line(&pts, Stroke::new(1.0, Color32::BLACK), 3.0, 3.0));
|
||||
}
|
||||
|
||||
@@ -36,8 +36,9 @@
|
||||
//! (the Photoshop behaviour, measured frame by frame on a screen recording). Zooming reads the
|
||||
//! wheel events themselves and ignores egui's smoothed tail.
|
||||
//!
|
||||
//! In both modes panning keeps the smoothed delta, and ⇧/Shift snap zoom reads the wheel events
|
||||
//! and stays instant. The Alt state is taken from the wheel events (and the Alt key's own press
|
||||
//! In both modes the canvas pans by this frame's wheel events, the whole notch at once with no
|
||||
//! glide, as in Photoshop (#9479), while [`read`] keeps egui's smoothed delta; ⇧/Shift snap zoom
|
||||
//! reads the wheel events and stays instant. The Alt state is taken from the wheel events (and the Alt key's own press
|
||||
//! and release, `wheel_events`) and kept until the next wheel event: releasing Alt while the tail
|
||||
//! is still settling must not turn it into a pan.
|
||||
|
||||
@@ -366,9 +367,10 @@ fn alt_gesture(m: &Modifiers) -> bool {
|
||||
m.alt && (!m.command || (m.ctrl && !m.mac_cmd && !m.shift))
|
||||
}
|
||||
|
||||
/// [`read`], choosing how a plain wheel scroll pans: `smooth` glides it over a few frames (egui's
|
||||
/// smoothed delta); off, as with Interface › Enable Animations off, the view moves the whole notch
|
||||
/// in the frame the wheel turns and stops there (#5721), as scroll areas already do.
|
||||
/// [`read`], choosing how a wheel scroll pans: `smooth` glides it over a few frames (egui's
|
||||
/// smoothed delta, as in the Liquify and Camera Raw previews); off, the view moves the whole notch
|
||||
/// in the frame the wheel turns and stops there (#5721). The canvas pans with it off, as Photoshop
|
||||
/// does (#9479).
|
||||
/// `touch_gestures` is Preferences › Enhanced Controls › Enable Gestures: off, a touch screen's
|
||||
/// two-finger pinch doesn't zoom ([`pinch_factor`]).
|
||||
/// `animated_zoom` is Preferences › General › Animated Zoom: on, the wheel zoom is eased over the
|
||||
@@ -384,16 +386,16 @@ pub fn read_with(
|
||||
smooth: bool,
|
||||
touch_gestures: bool,
|
||||
) -> Option<Wheel> {
|
||||
let notch = ctx.options(|o| o.input_options.line_scroll_speed);
|
||||
let options = ctx.options(|o| o.input_options);
|
||||
let notch = options.line_scroll_speed;
|
||||
|
||||
// --- Modifier tracking (always runs for all callers) ---
|
||||
let (scroll, zoom_delta, latest_alt, latest_shift, wheel, page) = ctx.input(|i| {
|
||||
let (smoothed, zoom_delta, latest_alt, latest_shift, wheel, page) = ctx.input(|i| {
|
||||
let wheel = wheel_events(i);
|
||||
let latest_alt = wheel.last().map(|(_, _, m, _)| alt_gesture(m));
|
||||
let latest_shift = wheel.last().map(|(_, _, m, _)| m.shift && !m.command && !m.ctrl);
|
||||
let latest_alt = wheel.last().map(|(_, _, m, _)| gesture_mode(m).0);
|
||||
let latest_shift = wheel.last().map(|(_, _, m, _)| gesture_mode(m).1);
|
||||
(i.smooth_scroll_delta, pinch_factor(i, touch_gestures), latest_alt, latest_shift, wheel, i.content_rect().height())
|
||||
});
|
||||
let wheel = mark_unsmoothed(ctx, wheel);
|
||||
let alt = match latest_alt {
|
||||
Some(a) => {
|
||||
ctx.data_mut(|d| d.insert_temp(alt_id(), a));
|
||||
@@ -408,6 +410,8 @@ pub fn read_with(
|
||||
}
|
||||
None => ctx.data(|d| d.get_temp::<bool>(shift_id())).unwrap_or(false),
|
||||
};
|
||||
let scroll = if smooth { smoothed } else { unsmoothed_scroll(&wheel, (alt, shift), &options, page) };
|
||||
let wheel = mark_unsmoothed(ctx, wheel);
|
||||
|
||||
if !hovered {
|
||||
return None;
|
||||
@@ -510,17 +514,55 @@ pub fn read_with(
|
||||
let eased = ease_zoom_delta(ctx, owner, along(raw - instant)) + along(instant);
|
||||
// The plain wheel zooms through `y`; its sideways part (⌘/Ctrl + wheel, a trackpad's
|
||||
// horizontal scroll) is not a zoom event, so it pans like any scroll: smoothed, or
|
||||
// with Enable Animations off at once (#5721).
|
||||
if alt { Vec2::new(0.0, eased) } else { Vec2::new(if smooth { scroll.x } else { raw.x }, eased) }
|
||||
// unsmoothed at once (#5721, #9479).
|
||||
if alt { Vec2::new(0.0, eased) } else { Vec2::new(scroll.x, eased) }
|
||||
} else {
|
||||
ctx.data_mut(|d| d.remove::<ZoomEase>(zoom_ease_id(owner)));
|
||||
// Unsmoothed, a plain scroll pans by this frame's own wheel events (none: no tail).
|
||||
if smooth || alt || shift { scroll } else { raw }
|
||||
// Unsmoothed, a scroll pans by this frame's own wheel events (none: no tail).
|
||||
scroll
|
||||
};
|
||||
classify(Input { scroll, raw, zoom_delta, alt, shift, zoom_with_wheel, pinch_zooms, animated_zoom, notch })
|
||||
}
|
||||
}
|
||||
|
||||
/// The ⌥/Alt and ⇧/Shift gesture a wheel event belongs to: ⌥ as [`alt_gesture`] decides; ⇧ with
|
||||
/// ⌘/Ctrl is not one (it scrolls sideways, [`configure`]), so it belongs to the plain wheel.
|
||||
fn gesture_mode(m: &Modifiers) -> (bool, bool) {
|
||||
(alt_gesture(m), m.shift && !m.command && !m.ctrl)
|
||||
}
|
||||
|
||||
/// This frame's wheel scroll without egui's smoothing (points, content direction): what egui's
|
||||
/// smoothed delta spreads over the next frames, all of it now and no tail after. ⇧ or ⌘/Ctrl fold
|
||||
/// it sideways as egui does ([`configure`]), so every pan, plain or sideways, moves at once.
|
||||
/// Only the wheel events of the gesture in progress (`mode`, the ⌥ and ⇧ of [`gesture_mode`])
|
||||
/// count: a ⌥ zoom notch in the same frame as a plain pan notch doesn't pan too.
|
||||
fn unsmoothed_scroll(wheel: &[(MouseWheelUnit, Vec2, Modifiers, TouchPhase)], mode: (bool, bool), options: &egui::InputOptions, page: f32) -> Vec2 {
|
||||
wheel.iter().fold(Vec2::ZERO, |sum, (unit, delta, modifiers, phase)| {
|
||||
// egui scrolls only by `Move` events; a trackpad's `Start`, `End` or `Cancel` delta
|
||||
// (`WheelState::on_wheel_event`) is not a scroll.
|
||||
if *phase != TouchPhase::Move || gesture_mode(modifiers) != mode {
|
||||
return sum;
|
||||
}
|
||||
// egui turns these into its own zoom, not a scroll.
|
||||
if modifiers.matches_any(options.zoom_modifier) {
|
||||
return sum;
|
||||
}
|
||||
let d = *delta
|
||||
* match unit {
|
||||
MouseWheelUnit::Point => 1.0,
|
||||
MouseWheelUnit::Line => options.line_scroll_speed,
|
||||
MouseWheelUnit::Page => page,
|
||||
};
|
||||
let sideways = modifiers.matches_any(options.horizontal_scroll_modifier);
|
||||
let upright = modifiers.matches_any(options.vertical_scroll_modifier);
|
||||
sum + match (sideways, upright) {
|
||||
(true, false) => Vec2::new(d.x + d.y, 0.0),
|
||||
(false, true) => Vec2::new(0.0, d.x + d.y),
|
||||
_ => d,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn is_alt_key(key: Key) -> bool {
|
||||
matches!(key, Key::AltLeft | Key::AltRight)
|
||||
}
|
||||
|
||||
@@ -87,7 +87,41 @@ fn unsmoothed_wheel_pans_at_once_without_a_glide() {
|
||||
assert!(smooth[1..].iter().any(|p| p.y != 0.0), "and the rest follows");
|
||||
}
|
||||
|
||||
/// Interface › Enable Animations off only stops the *pan* gliding. A plain wheel that zooms
|
||||
/// Unsmoothed, only `Move` wheel events pan, as egui scrolls by them alone: a trackpad's
|
||||
/// `Start`, `End` or `Cancel` event with a delta doesn't move the canvas.
|
||||
#[test]
|
||||
fn unsmoothed_pan_ignores_wheel_events_outside_the_move_phase() {
|
||||
let ctx = Context::default();
|
||||
configure(&ctx);
|
||||
let owner = Id::unique("test-unsmoothed-phase");
|
||||
let event = |phase: TouchPhase| Event::MouseWheel {
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
unit: MouseWheelUnit::Point,
|
||||
delta: Vec2::new(0.0, -30.0),
|
||||
phase,
|
||||
modifiers: Modifiers::NONE,
|
||||
};
|
||||
let pan_of = |n: u32, events: Vec<Event>| {
|
||||
let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() };
|
||||
let mut pan = Vec2::ZERO;
|
||||
let mut out = ctx.run_ui(raw, |ui| {
|
||||
if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), false, true, true, owner, true, false, true) {
|
||||
pan = d;
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
pan
|
||||
};
|
||||
for (n, phase) in [TouchPhase::Start, TouchPhase::End, TouchPhase::Cancel].into_iter().enumerate() {
|
||||
let n = u32::try_from(n).unwrap_or(0) * 2;
|
||||
assert_eq!(pan_of(n, vec![event(phase)]), Vec2::ZERO, "{phase:?} doesn't pan");
|
||||
assert_eq!(pan_of(n + 1, Vec::new()), Vec2::ZERO, "nor after {phase:?}");
|
||||
}
|
||||
let moved = pan_of(10, vec![event(TouchPhase::Start), event(TouchPhase::Move), event(TouchPhase::End)]);
|
||||
assert!(near(moved, Vec2::new(0.0, -30.0)), "only the Move delta pans: {moved:?}");
|
||||
}
|
||||
|
||||
/// Pan smoothing off (the canvas, #9479) only stops the *pan* gliding. A plain wheel that zooms
|
||||
/// (Zoom with Scroll Wheel) with Animated Zoom on must still ease over the frames of a notch,
|
||||
/// exactly as it does with the pan smoothing on.
|
||||
#[test]
|
||||
@@ -372,7 +406,7 @@ fn animated_zoom_does_not_ease_a_trackpad() {
|
||||
assert!(frames[1..].iter().all(|f| *f == 1.0), "no tail after it: {frames:?}");
|
||||
}
|
||||
|
||||
/// Zoom with Scroll Wheel + Animated Zoom with Enable Animations off: the wheel zooms eased, but
|
||||
/// Zoom with Scroll Wheel + Animated Zoom with pan smoothing off: the wheel zooms eased, but
|
||||
/// a sideways wheel still pans without a glide (#5721), all of it in the frame it turns.
|
||||
#[test]
|
||||
fn animated_zoom_keeps_the_sideways_wheel_unsmoothed_with_animations_off() {
|
||||
@@ -397,6 +431,44 @@ fn animated_zoom_keeps_the_sideways_wheel_unsmoothed_with_animations_off() {
|
||||
assert!(pans[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it: {pans:?}");
|
||||
}
|
||||
|
||||
/// One frame of `events` read with pan smoothing off (the canvas, #9479) and Animated Zoom on.
|
||||
fn unsmoothed_frame(events: Vec<Event>, zoom_with_wheel: bool) -> Option<Wheel> {
|
||||
let ctx = Context::default();
|
||||
configure(&ctx);
|
||||
let raw = RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() };
|
||||
let mut wheel = None;
|
||||
let mut out = ctx.run_ui(raw, |ui| wheel = read_with(ui.ctx(), zoom_with_wheel, true, true, Id::unique("test-mixed"), true, false, true));
|
||||
out.textures_delta.clear();
|
||||
wheel
|
||||
}
|
||||
|
||||
/// Unsmoothed, the canvas pans by the wheel events of the gesture in progress only (the latest
|
||||
/// event's modifiers pick it, as for zooming): a ⌥ notch (a zoom) or a ⇧ notch (a snap zoom)
|
||||
/// arriving in the same frame as the panning notch must not pan the canvas too.
|
||||
#[test]
|
||||
fn unsmoothed_pan_takes_only_the_wheel_events_of_the_gesture_in_progress() {
|
||||
let down = Vec2::new(0.0, -1.0);
|
||||
// ⌥ zooms, then a plain notch pans: one notch, not two.
|
||||
let pan = unsmoothed_frame(vec![wheel(down, Modifiers::ALT), wheel(down, Modifiers::NONE)], false);
|
||||
assert_eq!(pan, Some(Wheel::Pan(Vec2::new(0.0, -40.0))), "only the plain notch pans");
|
||||
// ⇧ + wheel pans sideways: a plain notch before it in the frame is not part of that.
|
||||
let pan = unsmoothed_frame(vec![wheel(down, Modifiers::NONE), wheel(down, Modifiers::SHIFT)], false);
|
||||
assert_eq!(pan, Some(Wheel::Pan(Vec2::new(-40.0, 0.0))), "only the ⇧ notch pans, sideways");
|
||||
// Zoom with Scroll Wheel: ⌥ + wheel pans; the plain notch before it zooms and doesn't pan.
|
||||
let pan = unsmoothed_frame(vec![wheel(down, Modifiers::NONE), wheel(down, Modifiers::ALT)], true);
|
||||
assert_eq!(pan, Some(Wheel::Pan(Vec2::new(0.0, -40.0))), "only the ⌥ notch pans");
|
||||
// ...and with the plain wheel zooming, a ⇧ snap notch earlier in the frame doesn't pan sideways.
|
||||
let zoom = unsmoothed_frame(vec![wheel(Vec2::new(0.0, 1.0), Modifiers::SHIFT), wheel(down, Modifiers::NONE)], true);
|
||||
assert!(matches!(zoom, Some(Wheel::Zoom(f)) if f < 1.0), "the plain notch zooms, nothing pans: {zoom:?}");
|
||||
// ⌘/Ctrl + wheel is part of the plain gesture: it pans sideways alongside a plain notch.
|
||||
let pan = unsmoothed_frame(vec![wheel(down, CTRL), wheel(down, Modifiers::NONE)], false);
|
||||
assert_eq!(pan, Some(Wheel::Pan(Vec2::new(-40.0, -40.0))), "⌘/Ctrl + wheel and a plain notch both pan");
|
||||
// A held ⌥ the wheel event itself misses (#8049) still makes it the ⌥ gesture's.
|
||||
let alt_key = |pressed: bool| Event::Key { key: Key::AltLeft, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE };
|
||||
let pan = unsmoothed_frame(vec![wheel(down, Modifiers::NONE), alt_key(true), wheel(down, Modifiers::NONE), alt_key(false)], true);
|
||||
assert_eq!(pan, Some(Wheel::Pan(Vec2::new(0.0, -40.0))), "only the notch under the held ⌥ pans");
|
||||
}
|
||||
|
||||
/// A diagonal point step with ⌥ is measured as egui measures it, folded onto one axis: (5, 5)
|
||||
/// is a 10-point step, which egui smooths, so Animated Zoom eases it.
|
||||
#[test]
|
||||
|
||||
@@ -439,7 +439,15 @@ fn drop_taken_text(ctx: &Context) {
|
||||
ctx.data_mut(|d| d.remove_temp::<(char, u64)>(taken_key_id()));
|
||||
return;
|
||||
}
|
||||
let same = |t: &str| t.chars().eq(c.to_lowercase()) || t.chars().eq(c.to_uppercase());
|
||||
let same = |t: &str| {
|
||||
if c == 'I' {
|
||||
// The consumed logical I key may emit either Turkic letter on the active keyboard,
|
||||
// whatever the interface language (an English UI on a Turkish keyboard emits `ı`).
|
||||
matches!(t, "I" | "i" | "İ" | "ı")
|
||||
} else {
|
||||
t.chars().eq(c.to_lowercase()) || t.chars().eq(c.to_uppercase())
|
||||
}
|
||||
};
|
||||
let found = ctx.input_mut(|i| {
|
||||
let at = i.events.iter().position(|e| matches!(e, egui::Event::Text(t) if same(t)));
|
||||
at.map(|at| i.events.remove(at)).is_some()
|
||||
@@ -558,6 +566,37 @@ fn on_pasteboard(app: &crate::PhotocraftApp, ctx: &Context, pos: egui::Pos2) ->
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Whether `text` survives `drop_taken_text` after the menu took the logical key `key`.
|
||||
fn text_survives(key: char, text: &str) -> bool {
|
||||
let ctx = Context::default();
|
||||
ctx.begin_pass(egui::RawInput { events: vec![egui::Event::Text(text.into())], ..Default::default() });
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
ctx.data_mut(|d| d.insert_temp(taken_key_id(), (key, pass)));
|
||||
drop_taken_text(&ctx);
|
||||
let survives = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Text(_))));
|
||||
ctx.end_pass().textures_delta.clear();
|
||||
survives
|
||||
}
|
||||
|
||||
/// A menu mnemonic consumes the text emitted by the same logical key on Turkic keyboards. The
|
||||
/// keyboard layout is not the interface language: an English UI on a Turkish keyboard too.
|
||||
#[test]
|
||||
fn menu_i_key_does_not_leak_dotless_text_into_zoom_in_any_ui_language() {
|
||||
for code in ["az", "tr", "en", "de"] {
|
||||
let lang = crate::i18n::Lang::from_code(code).unwrap();
|
||||
crate::i18n::with_language(lang, || {
|
||||
for text in ["I", "i", "İ", "ı"] {
|
||||
assert!(!text_survives('I', text), "{code}: {text} leaked after the I key");
|
||||
}
|
||||
// Only the I key folds the Turkic letters; another key's text is not taken.
|
||||
for text in ["İ", "ı", "j"] {
|
||||
assert!(text_survives('K', text), "{code}: {text} was taken for the K key");
|
||||
}
|
||||
assert!(!text_survives('K', "k"), "{code}: k leaked after the K key");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_reads_one_separator_and_the_number_before_a_second_one() {
|
||||
let number = |t: &str| Entry::Number(t.into());
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
//! - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows
|
||||
//! - `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (`button: "secondary"` opens the tool's canvas context menu (the pasteboard colour menu outside the image) or Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase)
|
||||
//! - `ui.click {x, y, button?, count?}` / `ui.move {x, y}`: synthetic pointer input in screen points
|
||||
//! (`count` at most [`MAX_CLICKS`])
|
||||
//! (`count` at most [`MAX_CLICKS`], `x` and `y` within ±[`MAX_SCREEN_POINT`])
|
||||
//! - `ui.key {key, command?, shift?, alt?, ctrl?}` / `ui.type {text}`: synthetic keyboard input
|
||||
//! - The synthetic input methods reject unknown fields, wrong types, unknown enum values and
|
||||
//! out-of-range numbers before acting, naming the parameter (#2449)
|
||||
@@ -51,7 +51,7 @@ use dispatch::dispatch;
|
||||
pub use inspect::{inspect, save_screenshot, save_screenshot_rgba};
|
||||
#[cfg(test)]
|
||||
use params::screen_point;
|
||||
pub use params::{MAX_CLICKS, UI_SET_FIELDS};
|
||||
pub use params::{MAX_CLICKS, MAX_SCREEN_POINT, UI_SET_FIELDS};
|
||||
use params::{err, ok};
|
||||
|
||||
pub type ControlResponse = Value;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user