diff --git a/AGENTS.md b/AGENTS.md index dbe7e172a9..172bc7bd70 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -70,6 +70,7 @@ 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 diff --git a/Cargo.lock b/Cargo.lock index ba0e6baea0..5c96f56119 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4638,10 +4638,11 @@ dependencies = [ [[package]] name = "photocraft" -version = "0.12.0" +version = "0.14.0" dependencies = [ "arboard", "async-io", + "chrono", "core-graphics2", "dispatch2", "eframe", @@ -4683,7 +4684,7 @@ dependencies = [ [[package]] name = "photocraft-affinity" -version = "0.12.0" +version = "0.14.0" dependencies = [ "crc32fast", "flate2", @@ -4693,7 +4694,7 @@ dependencies = [ [[package]] name = "photocraft-algo" -version = "0.12.0" +version = "0.14.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4706,7 +4707,7 @@ dependencies = [ [[package]] name = "photocraft-automation" -version = "0.12.0" +version = "0.14.0" dependencies = [ "base64 0.22.1", "cap-std", @@ -4729,7 +4730,7 @@ dependencies = [ [[package]] name = "photocraft-cli" -version = "0.12.0" +version = "0.14.0" dependencies = [ "photocraft-automation", "photocraft-codecs", @@ -4744,7 +4745,7 @@ dependencies = [ [[package]] name = "photocraft-cms" -version = "0.12.0" +version = "0.14.0" dependencies = [ "moxcms", "rayon", @@ -4752,7 +4753,7 @@ dependencies = [ [[package]] name = "photocraft-codecs" -version = "0.12.0" +version = "0.14.0" dependencies = [ "exr", "flate2", @@ -4773,7 +4774,7 @@ dependencies = [ [[package]] name = "photocraft-color" -version = "0.12.0" +version = "0.14.0" dependencies = [ "photocraft-cms", "serde", @@ -4781,7 +4782,7 @@ dependencies = [ [[package]] name = "photocraft-compose" -version = "0.12.0" +version = "0.14.0" dependencies = [ "criterion", "photocraft-color", @@ -4796,7 +4797,7 @@ dependencies = [ [[package]] name = "photocraft-doc" -version = "0.12.0" +version = "0.14.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4807,9 +4808,10 @@ dependencies = [ [[package]] name = "photocraft-engine" -version = "0.12.0" +version = "0.14.0" dependencies = [ "blake3", + "chrono", "craft-print", "exr", "flate2", @@ -4845,7 +4847,7 @@ dependencies = [ [[package]] name = "photocraft-format" -version = "0.12.0" +version = "0.14.0" dependencies = [ "blake3", "crc32fast", @@ -4868,14 +4870,14 @@ dependencies = [ [[package]] name = "photocraft-geom" -version = "0.12.0" +version = "0.14.0" dependencies = [ "serde", ] [[package]] name = "photocraft-gpu" -version = "0.12.0" +version = "0.14.0" dependencies = [ "half", "log", @@ -4893,14 +4895,14 @@ dependencies = [ [[package]] name = "photocraft-heif" -version = "0.12.0" +version = "0.14.0" dependencies = [ "heic-rs", ] [[package]] name = "photocraft-io" -version = "0.12.0" +version = "0.14.0" dependencies = [ "blake3", "craft-docpath", @@ -4930,18 +4932,18 @@ dependencies = [ [[package]] name = "photocraft-ipp" -version = "0.12.0" +version = "0.14.0" [[package]] name = "photocraft-ops" -version = "0.12.0" +version = "0.14.0" dependencies = [ "photocraft-doc", ] [[package]] name = "photocraft-paint" -version = "0.12.0" +version = "0.14.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4952,7 +4954,7 @@ dependencies = [ [[package]] name = "photocraft-plugins" -version = "0.12.0" +version = "0.14.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4967,7 +4969,7 @@ dependencies = [ [[package]] name = "photocraft-psd" -version = "0.12.0" +version = "0.14.0" dependencies = [ "flate2", "photocraft-psd", @@ -4978,7 +4980,7 @@ dependencies = [ [[package]] name = "photocraft-raster" -version = "0.12.0" +version = "0.14.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4989,7 +4991,7 @@ dependencies = [ [[package]] name = "photocraft-raw" -version = "0.12.0" +version = "0.14.0" dependencies = [ "flate2", "image", @@ -5004,7 +5006,7 @@ dependencies = [ [[package]] name = "photocraft-tablet" -version = "0.12.0" +version = "0.14.0" dependencies = [ "block2 0.6.2", "objc2 0.6.4", @@ -5016,7 +5018,7 @@ dependencies = [ [[package]] name = "photocraft-testkit" -version = "0.12.0" +version = "0.14.0" dependencies = [ "memory-stats", "serde_json", @@ -5024,7 +5026,7 @@ dependencies = [ [[package]] name = "photocraft-text" -version = "0.12.0" +version = "0.14.0" dependencies = [ "flate2", "parley", @@ -5039,7 +5041,7 @@ dependencies = [ [[package]] name = "photocraft-ui-egui" -version = "0.12.0" +version = "0.14.0" dependencies = [ "base64 0.22.1", "craft-print", @@ -5082,7 +5084,7 @@ dependencies = [ [[package]] name = "photocraft-vector" -version = "0.12.0" +version = "0.14.0" dependencies = [ "photocraft-color", "photocraft-doc", @@ -5093,7 +5095,7 @@ dependencies = [ [[package]] name = "photocraft-web" -version = "0.12.0" +version = "0.14.0" dependencies = [ "eframe", "egui", @@ -5115,7 +5117,7 @@ dependencies = [ [[package]] name = "photocraft-web-boot" -version = "0.12.0" +version = "0.14.0" dependencies = [ "flate2", "js-sys", @@ -8711,8 +8713,9 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.12.0" +version = "0.14.0" dependencies = [ + "chrono", "serde", "serde_json", "toml", diff --git a/Cargo.toml b/Cargo.toml index c3fdd1e10c..1215d84570 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"] [workspace.package] -version = "0.12.0" +version = "0.14.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -59,6 +59,8 @@ egui = { version = "0.36", default-features = false } egui_kittest = "0.36" rfd = "0.17" log = "0.4" +# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). +chrono = { version = "0.4.45", default-features = false, features = ["std"] } rayon = "1" criterion = { version = "0.5", default-features = false } getrandom = "0.3" diff --git a/README.md b/README.md index 4285f69513..74a5c78f36 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off PhotoCraft's PSD support is a standalone crate written from Adobe's public specification and tested against a corpus of real-world files. -- **Faithful round trips:** opening and re-saving a document renders the same for 307 of the 309 files in the psd-tools test set and 169 of 170 in our mixed ag-psd/psd-tools set (`crates/io/tests/corpus.rs`; fetch the psd-tools set with `cargo xtask corpus --psd-tools`), and anything we don't model yet (raw blocks, descriptors, extras) is carried over instead of being dropped. A re-saved file is not byte-identical to its source: PhotoCraft rewrites image resources, layer records and the composite. Only the standalone `photocraft-psd` crate, parsing and writing a file without the document model, reproduces every parseable corpus file byte for byte (`crates/psd/tests/corpus.rs`). +- **Faithful round trips:** opening and re-saving a document renders the same for 307 of the 309 files in the psd-tools test set and 169 of 170 in our mixed ag-psd/psd-tools set (`crates/io/tests/it/corpus.rs`; fetch the psd-tools set with `cargo xtask corpus --psd-tools`), and anything we don't model yet (raw blocks, descriptors, extras) is carried over instead of being dropped. A re-saved file is not byte-identical to its source: PhotoCraft rewrites image resources, layer records and the composite. Only the standalone `photocraft-psd` crate, parsing and writing a file without the document model, reproduces every parseable corpus file byte for byte (`crates/psd/tests/it/corpus.rs`). - **Pixels that match:** a composite oracle compares our render with Photoshop's own merged image, covering gradient interpolation (Classic, Perceptual and Linear), layer effects, shape strokes, clipping and fill opacity. - **Large documents:** PSB, 16 and 32-bit files, and CMYK and Lab documents open natively. diff --git a/ROADMAP.md b/ROADMAP.md index 1d1174c504..829ff75af8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -137,7 +137,7 @@ Detail and the next releases: [docs/roadmap.md](docs/roadmap.md). | Date | Change | Summary | |---|---|---| | 2026-10-17 | minor | Object Finder retains large enclosed foregrounds (#6548) | -| 2026-10-13 | minor | Focus item 1 quoted the oracle floor as 133 of 256; it is 145 of 258 (`crates/io/tests/corpus.rs`, gaps.md G1). Open issues 579 → 953 (2026-10-13) | +| 2026-10-13 | minor | Focus item 1 quoted the oracle floor as 133 of 256; it is 145 of 258 (`crates/io/tests/it/corpus.rs`, gaps.md G1). Open issues 579 → 953 (2026-10-13) | | 2026-10-15 | minor | Russian catalog covers every dynamic UI label the other catalogs translate | | 2026-10-11 | minor | Toolbox count 56 of 68 (12 missing) with the Convert Point tool (#3204) | | 2026-10-10 | minor | Readiness by audience with hours per tier | diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/it/cli.rs similarity index 100% rename from apps/photocraft-cli/tests/cli.rs rename to apps/photocraft-cli/tests/it/cli.rs diff --git a/apps/photocraft-cli/tests/it/main.rs b/apps/photocraft-cli/tests/it/main.rs new file mode 100644 index 0000000000..581c983b3c --- /dev/null +++ b/apps/photocraft-cli/tests/it/main.rs @@ -0,0 +1,4 @@ +//! The crate's integration tests, linked into one test binary. + +mod cli; +mod orientation; diff --git a/apps/photocraft-cli/tests/orientation.rs b/apps/photocraft-cli/tests/it/orientation.rs similarity index 100% rename from apps/photocraft-cli/tests/orientation.rs rename to apps/photocraft-cli/tests/it/orientation.rs diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml index 61c43ae9da..4ba562db68 100644 --- a/apps/photocraft/Cargo.toml +++ b/apps/photocraft/Cargo.toml @@ -33,6 +33,7 @@ eframe = { workspace = true, features = ["wgpu", "accesskit", "wayland", "x11", egui = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +chrono = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rfd = { workspace = true } diff --git a/apps/photocraft/src/logging.rs b/apps/photocraft/src/logging.rs index 5c8f0697dd..6a0cc8f052 100644 --- a/apps/photocraft/src/logging.rs +++ b/apps/photocraft/src/logging.rs @@ -91,27 +91,36 @@ fn matches(name: &str, target: &str) -> bool { } /// `2026-10-08T07:59:17.728Z` (UTC, milliseconds). A clock before 1970 reads as the epoch. +/// A clock far past chrono's year range still converts (the calendar repeats every 400 years), so +/// logging never panics and never silently resets to the epoch for a convertible instant. pub fn timestamp(t: SystemTime) -> String { let since = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default(); - let secs = since.as_secs(); - let (days, rem) = (secs / 86_400, secs % 86_400); - let (y, m, d) = civil_from_days(days); - format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3600, rem % 3600 / 60, rem % 60, since.subsec_millis()) + // Pre-1970 is clamped to the epoch by `unwrap_or_default` above. `as_secs` is `u64`; a value + // past `i64::MAX` seconds saturates rather than falling back to the epoch. + let secs = i64::try_from(since.as_secs()).unwrap_or(i64::MAX); + let (y, t) = utc_parts(secs, since.subsec_nanos()); + // `{:04}` rather than `%Y`, which writes a `+` before years past 9999. + format!("{y:04}-{}", t.format("%m-%dT%H:%M:%S%.3fZ")) } -/// Days since 1970-01-01 to a proleptic Gregorian (year, month, day) (Howard Hinnant's -/// `civil_from_days`, unsigned because `timestamp` clamps at the epoch). -fn civil_from_days(days: u64) -> (u64, u64, u64) { - let z = days + 719_468; - let era = z / 146_097; - let doe = z % 146_097; - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = yoe + era * 400 + u64::from(m <= 2); - (y, m, d) +/// Unix seconds (+ nanos) → (proleptic Gregorian year, the same wall-clock instant moved into +/// chrono's range by whole 400-year cycles). The calendar repeats every 400 years (146_097 days), +/// so month, day and time of day come from chrono and only the year is carried, which keeps every +/// `i64` exact. Replaces the old hand-rolled `civil_from_days`; chrono is the only calendar logic. +fn utc_parts(secs: i64, nanos: u32) -> (i64, chrono::NaiveDateTime) { + use chrono::Datelike; + let (days, sod) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); + let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097)); + // `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400. + let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt); + let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, nanos.min(999_999_999))); + match (date, time) { + (Some(d), Some(t)) => { + let y = i128::from(d.year()) + i128::from(cycles) * 400; + (i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX }), d.and_time(t)) + } + _ => (1970, chrono::NaiveDateTime::default()), // unreachable + } } fn numbered(dir: &Path, n: usize) -> PathBuf { @@ -416,6 +425,20 @@ mod tests { assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z"); // Before the epoch (a clock set wrong) clamps instead of panicking. assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z"); + // Past chrono's year range still converts via the 400-year cycle (the old code did too, + // through `civil_from_days`): never a silent reset to the epoch. Platform-safe: Windows' + // SystemTime can't hold this instant, so it is only checked where it exists. + // `u64::MAX / 2` seconds == `i64::MAX` seconds → year 292277026596 (old output). + if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) { + assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z"); + } + // Years past 9999 keep the plain zero-padded year (no `+`). + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z"); + // 10_000_000_000_000 s is far beyond chrono's range; old output is year 318857. + // Windows' SystemTime holds only up to about year 30828, so this is checked where it fits. + if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) { + assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z"); + } } #[test] diff --git a/apps/photocraft/tests/command_line_usage.rs b/apps/photocraft/tests/it/command_line_usage.rs similarity index 100% rename from apps/photocraft/tests/command_line_usage.rs rename to apps/photocraft/tests/it/command_line_usage.rs diff --git a/apps/photocraft/tests/control_exit_code.rs b/apps/photocraft/tests/it/control_exit_code.rs similarity index 100% rename from apps/photocraft/tests/control_exit_code.rs rename to apps/photocraft/tests/it/control_exit_code.rs diff --git a/apps/photocraft/tests/it/main.rs b/apps/photocraft/tests/it/main.rs new file mode 100644 index 0000000000..b5ece12621 --- /dev/null +++ b/apps/photocraft/tests/it/main.rs @@ -0,0 +1,5 @@ +//! The crate's integration tests, linked into one test binary. + +mod command_line_usage; +mod control_exit_code; +mod startup_without_display; diff --git a/apps/photocraft/tests/startup_without_display.rs b/apps/photocraft/tests/it/startup_without_display.rs similarity index 100% rename from apps/photocraft/tests/startup_without_display.rs rename to apps/photocraft/tests/it/startup_without_display.rs diff --git a/crates/affinity/README.md b/crates/affinity/README.md index 535c3736c6..1be7fd954e 100644 --- a/crates/affinity/README.md +++ b/crates/affinity/README.md @@ -108,11 +108,11 @@ The same reader is shared, as an independent copy, with VectorCraft's `vectorcra * Unit tests on synthetic containers built by the `synth` feature (stored, zlib and zstd entries, checksums, budgets, cycles, hostile streams, every truncation) and property tests of random - mutations, here and in `photocraft-io`'s `tests/affinity.rs`. + mutations, here and in `photocraft-io`'s `tests/it/affinity.rs`. * `cargo xtask corpus --affinity` fetches 21 public CC0/MIT documents, including the four Affinity 3 `.af` files of [samuel-etver/vector-art](https://github.com/samuel-etver/vector-art) - (CC0), at pinned commits, each checked against `xtask/affinity-corpus.sha256`. `tests/real_files.rs` - parses them; `photocraft-io`'s `tests/affinity_corpus.rs` imports and flattens each one and + (CC0), at pinned commits, each checked against `xtask/affinity-corpus.sha256`. `tests/it/real_files.rs` + parses them; `photocraft-io`'s `tests/it/affinity_corpus.rs` imports and flattens each one and compares it with the thumbnail Affinity saved in it (mean difference 0–4.6 of 255, with a ceiling per file). * `fuzz/` has `cargo-fuzz` targets for the whole reader (`preview`), the object stream (`stream`) diff --git a/crates/affinity/src/tests.rs b/crates/affinity/src/tests.rs index 2c68a064a3..a5517653de 100644 --- a/crates/affinity/src/tests.rs +++ b/crates/affinity/src/tests.rs @@ -1,4 +1,4 @@ -//! Unit tests on synthetic inputs; `tests/real_files.rs` covers public Affinity documents. +//! Unit tests on synthetic inputs; `tests/it/real_files.rs` covers public Affinity documents. mod preview { use crate::container::header; diff --git a/crates/affinity/tests/compound_limits.rs b/crates/affinity/tests/it/compound_limits.rs similarity index 97% rename from crates/affinity/tests/compound_limits.rs rename to crates/affinity/tests/it/compound_limits.rs index 76f2e6e4a1..6801f7f6d6 100644 --- a/crates/affinity/tests/compound_limits.rs +++ b/crates/affinity/tests/it/compound_limits.rs @@ -48,8 +48,10 @@ fn isolated(name: &str, check: impl FnOnce()) { check(); return; } + // The harness names a test by its module path below the crate root. + let test = module_path!().split_once("::").map_or(name.to_string(), |(_, m)| format!("{m}::{name}")); let mut child = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", name, "--nocapture"]) + .args(["--exact", &test, "--nocapture"]) .env("PHOTOCRAFT_COMPOUND_CASE", name) .spawn() .unwrap(); diff --git a/crates/affinity/tests/it/main.rs b/crates/affinity/tests/it/main.rs new file mode 100644 index 0000000000..5d0a5740b8 --- /dev/null +++ b/crates/affinity/tests/it/main.rs @@ -0,0 +1,4 @@ +//! The crate's integration tests, linked into one test binary. + +mod compound_limits; +mod real_files; diff --git a/crates/affinity/tests/real_files.rs b/crates/affinity/tests/it/real_files.rs similarity index 100% rename from crates/affinity/tests/real_files.rs rename to crates/affinity/tests/it/real_files.rs diff --git a/crates/algo/tests/liquify_source_footprint.rs b/crates/algo/tests/it/liquify_source_footprint.rs similarity index 100% rename from crates/algo/tests/liquify_source_footprint.rs rename to crates/algo/tests/it/liquify_source_footprint.rs diff --git a/crates/algo/tests/it/main.rs b/crates/algo/tests/it/main.rs new file mode 100644 index 0000000000..107626cfc2 --- /dev/null +++ b/crates/algo/tests/it/main.rs @@ -0,0 +1,5 @@ +//! The crate's integration tests, linked into one test binary. + +mod liquify_source_footprint; +mod retouch_blur_exact; +mod warp_clipped; diff --git a/crates/algo/tests/retouch_blur_exact.rs b/crates/algo/tests/it/retouch_blur_exact.rs similarity index 100% rename from crates/algo/tests/retouch_blur_exact.rs rename to crates/algo/tests/it/retouch_blur_exact.rs diff --git a/crates/algo/tests/warp_clipped.rs b/crates/algo/tests/it/warp_clipped.rs similarity index 100% rename from crates/algo/tests/warp_clipped.rs rename to crates/algo/tests/it/warp_clipped.rs diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 1e3e83e1bf..bed78c0f65 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -261,7 +261,10 @@ impl Headless { files::save(&doc, &target, format, opts, Some(writer))? } Filesystem::Workspace(workspace) => { - let (bytes, warnings) = files::save_bytes(&doc, target_text, format, opts)?; + // Only the target is granted: a linked smart object's stored path is document + // data, so PSD export writes that layer as pixels instead of embedding the file. + let opts = ExportOptions { read_linked_files: false, ..opts.clone() }; + let (bytes, warnings) = files::save_bytes(&doc, target_text, format, &opts)?; workspace.write(target_text, &bytes)?; warnings } diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index c0369c917d..a0923a6744 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -836,6 +836,142 @@ mod tests { std::fs::remove_dir_all(base).unwrap(); } + #[test] + fn doc_export_data_sets_judges_pixel_replacement_paths_like_apply() { + let base = std::env::temp_dir().join(format!("pc-doc-data-set-pixels-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let red = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, [255, 0, 0].repeat(16)).unwrap(); + let photo = base.join("photo.png"); + std::fs::write(&photo, photocraft_codecs::encode(&red, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "card"})).unwrap(); + let layer = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {}})).unwrap()["layer"].clone(); + h.handle( + "engine.execute", + json!({"command": "image.variables.define", "params": {"defs": [{"name": "photo", "layer": layer, "type": "pixelReplacement"}]}}), + ) + .unwrap(); + // Storing the path is allowed; reading it is what the gate judges. + h.handle( + "engine.execute", + json!({"command": "image.variables.dataSets", "params": {"dataSets": [ + {"name": "swap", "values": [{"variable": "photo", "kind": "pixels", "value": photo.to_string_lossy()}]}, + ]}}), + ) + .unwrap(); + let applied = h.handle("engine.execute", json!({"command": "image.applyDataSet", "params": {"name": "swap"}})).unwrap_err().to_string(); + assert!(applied.contains("ambient filesystem paths"), "{applied}"); + let sets = root.join("sets"); + let exported = h.handle("doc.exportDataSets", json!({"dir": sets.to_string_lossy(), "format": "png"})).unwrap_err().to_string(); + assert!(exported.contains("ambient filesystem paths"), "{exported}"); + assert_eq!(std::fs::read_dir(&sets).map_or(0, Iterator::count), 0, "nothing of the refused batch is written"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); + } + + #[test] + fn workspace_psd_saves_embed_no_file_a_linked_smart_object_names() { + use photocraft_engine::doc::{LayerContent, SmartSource}; + + const MARKER: &[u8] = b"PHOTOCRAFT-LINKED-0001"; + let has_marker = |bytes: &[u8]| bytes.windows(MARKER.len()).any(|w| w == MARKER); + let base = std::env::temp_dir().join(format!("pc-psd-linked-embed-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let outside = base.join("outside.txt"); + std::fs::write(&outside, MARKER).unwrap(); + // A document whose smart object names a file outside the roots as its source. + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let state = session.active_mut().unwrap(); + let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; + smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; + std::fs::write(root.join("in.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); + // A trusted export embeds the linked file, as before. + assert!(has_marker(&photocraft_io::export(&state.doc, "psd", &Default::default()).unwrap().bytes)); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.open", json!({"path": "in.pcraft"})).unwrap(); + let saved = h.handle("doc.save", json!({"path": "out.psd"})).unwrap(); + let warnings = saved["warnings"].to_string(); + assert!(warnings.contains("written as pixels"), "{warnings}"); + assert!(!has_marker(&std::fs::read(root.join("out.psd")).unwrap()), "the linked file outside the roots is not embedded"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); + } + + #[test] + fn allowed_filters_do_not_rerender_a_smart_object_from_its_linked_file() { + use photocraft_engine::doc::{LayerContent, SmartSource}; + + let base = std::env::temp_dir().join(format!("pc-linked-rerender-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let red = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgb, [255, 0, 0].repeat(64)).unwrap(); + let outside = base.join("red.png"); + std::fs::write(&outside, photocraft_codecs::encode(&red, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); + // A document whose white smart object names a file outside the roots as its source. + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let state = session.active_mut().unwrap(); + let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; + smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; + std::fs::write(root.join("p.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.open", json!({"path": "p.pcraft"})).unwrap(); + h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 0.5}})).unwrap(); + let doc = &h.session.active().unwrap().doc; + let LayerContent::Smart(smart) = &doc.layers[0].content else { panic!("smart object") }; + assert_eq!(smart.smart_filters.len(), 1, "the filter is still recorded"); + assert_eq!(smart.cache.as_ref().unwrap().rgba(4, 4), [1.0, 1.0, 1.0, 1.0], "the linked file outside the roots is not read"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); + } + + #[test] + fn workspace_layer_exports_keep_linked_smart_objects_as_pixels() { + use photocraft_engine::doc::{LayerContent, SmartSource}; + + const MARKER: &[u8] = b"PHOTOCRAFT-LINKED-0002"; + let has_marker = |bytes: &[u8]| bytes.windows(MARKER.len()).any(|w| w == MARKER); + let base = std::env::temp_dir().join(format!("pc-export-layers-linked-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let outside = base.join("outside.txt"); + std::fs::write(&outside, MARKER).unwrap(); + // A document whose smart object names a file outside the roots as its source. + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let state = session.active_mut().unwrap(); + let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; + smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; + std::fs::write(root.join("in.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.open", json!({"path": "in.pcraft"})).unwrap(); + let out = root.join("layers"); + for format in ["psd", "psb"] { + let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": format})).unwrap(); + assert_eq!(exported["count"], 1, "{exported}"); + } + let files: Vec<_> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().path()).collect(); + assert_eq!(files.len(), 2, "{files:?}"); + for file in files { + assert!(!has_marker(&std::fs::read(&file).unwrap()), "{} embeds no file outside the roots", file.display()); + } + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); + } + #[test] fn trusted_local_render_keeps_full_size_behavior() { let mut h = Headless::trusted_local(); diff --git a/crates/automation/tests/agent_tasks.rs b/crates/automation/tests/it/agent_tasks.rs similarity index 100% rename from crates/automation/tests/agent_tasks.rs rename to crates/automation/tests/it/agent_tasks.rs diff --git a/crates/automation/tests/agent_tasks_extended.rs b/crates/automation/tests/it/agent_tasks_extended.rs similarity index 100% rename from crates/automation/tests/agent_tasks_extended.rs rename to crates/automation/tests/it/agent_tasks_extended.rs diff --git a/crates/automation/tests/agent_tasks_more.rs b/crates/automation/tests/it/agent_tasks_more.rs similarity index 100% rename from crates/automation/tests/agent_tasks_more.rs rename to crates/automation/tests/it/agent_tasks_more.rs diff --git a/crates/automation/tests/bridge.rs b/crates/automation/tests/it/bridge.rs similarity index 100% rename from crates/automation/tests/bridge.rs rename to crates/automation/tests/it/bridge.rs diff --git a/crates/automation/tests/inactive_save.rs b/crates/automation/tests/it/inactive_save.rs similarity index 100% rename from crates/automation/tests/inactive_save.rs rename to crates/automation/tests/it/inactive_save.rs diff --git a/crates/automation/tests/krita.rs b/crates/automation/tests/it/krita.rs similarity index 100% rename from crates/automation/tests/krita.rs rename to crates/automation/tests/it/krita.rs diff --git a/crates/automation/tests/layered_save_dirty.rs b/crates/automation/tests/it/layered_save_dirty.rs similarity index 100% rename from crates/automation/tests/layered_save_dirty.rs rename to crates/automation/tests/it/layered_save_dirty.rs diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs new file mode 100644 index 0000000000..f701bd705b --- /dev/null +++ b/crates/automation/tests/it/main.rs @@ -0,0 +1,16 @@ +//! The crate's integration tests, linked into one test binary. + +mod agent_tasks; +mod agent_tasks_extended; +mod agent_tasks_more; +mod bridge; +mod inactive_save; +mod krita; +mod layered_save_dirty; +mod mcp; +mod mcp_wire; +mod missing_font_warnings; +mod native_save_name; +mod openraster; +mod raw_defaults; +mod smart_filter_authorization; diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/it/mcp.rs similarity index 100% rename from crates/automation/tests/mcp.rs rename to crates/automation/tests/it/mcp.rs diff --git a/crates/automation/tests/mcp_wire.rs b/crates/automation/tests/it/mcp_wire.rs similarity index 100% rename from crates/automation/tests/mcp_wire.rs rename to crates/automation/tests/it/mcp_wire.rs diff --git a/crates/automation/tests/missing_font_warnings.rs b/crates/automation/tests/it/missing_font_warnings.rs similarity index 100% rename from crates/automation/tests/missing_font_warnings.rs rename to crates/automation/tests/it/missing_font_warnings.rs diff --git a/crates/automation/tests/native_save_name.rs b/crates/automation/tests/it/native_save_name.rs similarity index 100% rename from crates/automation/tests/native_save_name.rs rename to crates/automation/tests/it/native_save_name.rs diff --git a/crates/automation/tests/openraster.rs b/crates/automation/tests/it/openraster.rs similarity index 100% rename from crates/automation/tests/openraster.rs rename to crates/automation/tests/it/openraster.rs diff --git a/crates/automation/tests/raw_defaults.rs b/crates/automation/tests/it/raw_defaults.rs similarity index 100% rename from crates/automation/tests/raw_defaults.rs rename to crates/automation/tests/it/raw_defaults.rs diff --git a/crates/automation/tests/smart_filter_authorization.rs b/crates/automation/tests/it/smart_filter_authorization.rs similarity index 100% rename from crates/automation/tests/smart_filter_authorization.rs rename to crates/automation/tests/it/smart_filter_authorization.rs diff --git a/crates/cms/README.md b/crates/cms/README.md index 70b4ab3c9c..9109f48ed2 100644 --- a/crates/cms/README.md +++ b/crates/cms/README.md @@ -75,7 +75,7 @@ sampled gamut boundary. `profiles/photocraft-coated-cmyk.icc` (237 KB, AToB 11 21³ lut16) is that output, dedicated to the public domain (CC0-1.0). Regenerate with ```sh -PHOTOCRAFT_REGEN_PROFILES=1 cargo test -p photocraft-cms --release --test regen +PHOTOCRAFT_REGEN_PROFILES=1 cargo test -p photocraft-cms --release --test it -- regen:: ``` It is a plausible coated-offset profile, not a measured characterisation: use your printer's diff --git a/crates/cms/tests/bench.rs b/crates/cms/tests/it/bench.rs similarity index 95% rename from crates/cms/tests/bench.rs rename to crates/cms/tests/it/bench.rs index e0b9628a53..06789ff350 100644 --- a/crates/cms/tests/bench.rs +++ b/crates/cms/tests/it/bench.rs @@ -1,4 +1,4 @@ -//! Throughput check: `cargo test -p photocraft-cms --release --test bench -- --ignored --nocapture`. +//! Throughput check: `cargo test -p photocraft-cms --release --test it -- bench:: --ignored --nocapture`. use photocraft_cms::{Builtin, Intent, Transform}; diff --git a/crates/cms/tests/cms.rs b/crates/cms/tests/it/cms.rs similarity index 100% rename from crates/cms/tests/cms.rs rename to crates/cms/tests/it/cms.rs diff --git a/crates/cms/tests/gpu_matrix_shaper.rs b/crates/cms/tests/it/gpu_matrix_shaper.rs similarity index 100% rename from crates/cms/tests/gpu_matrix_shaper.rs rename to crates/cms/tests/it/gpu_matrix_shaper.rs diff --git a/crates/cms/tests/it/main.rs b/crates/cms/tests/it/main.rs new file mode 100644 index 0000000000..127f08435b --- /dev/null +++ b/crates/cms/tests/it/main.rs @@ -0,0 +1,6 @@ +//! The crate's integration tests, linked into one test binary. + +mod bench; +mod cms; +mod gpu_matrix_shaper; +mod regen; diff --git a/crates/cms/tests/regen.rs b/crates/cms/tests/it/regen.rs similarity index 98% rename from crates/cms/tests/regen.rs rename to crates/cms/tests/it/regen.rs index 54db9b4e2e..05d4b696b3 100644 --- a/crates/cms/tests/regen.rs +++ b/crates/cms/tests/it/regen.rs @@ -1,7 +1,7 @@ //! Regenerates the shipped synthetic CMYK profile when `PHOTOCRAFT_REGEN_PROFILES=1`: //! //! ```sh -//! PHOTOCRAFT_REGEN_PROFILES=1 cargo test -p photocraft-cms --release --test regen +//! PHOTOCRAFT_REGEN_PROFILES=1 cargo test -p photocraft-cms --release --test it -- regen:: //! ``` //! //! Without the variable the test only checks that the generator's model still matches the diff --git a/crates/codecs/src/codecs/pcx.rs b/crates/codecs/src/codecs/pcx.rs index f89a781e9d..48dbf1169e 100644 --- a/crates/codecs/src/codecs/pcx.rs +++ b/crates/codecs/src/codecs/pcx.rs @@ -72,8 +72,31 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { return Err(bad("8-bit indexed PCX has no 256-colour palette")); } let image_end = if vga { b.len() - 769 } else { b.len() }; + // A 63-byte RLE packet takes 2 bytes; a trailing remainder of 1 byte below 0xC0 + // can be encoded as a 1-byte literal, while any larger remainder takes at least 2 bytes. + // Because RLE packets may span planes within a scanline (`row_len`), compute the + // minimum encoded bytes across the full scanline (`row_len`) and multiply by `h`. + // Reject inputs that cannot possibly contain all scanlines before allocating + // the decoded image buffer. + let min_packets = (row_len / 63) + .checked_mul(2) + .and_then(|n| { + n.checked_add(match row_len % 63 { + 0 => 0, + 1 => 1, + _ => 2, + }) + }) + .ok_or_else(|| bad("compressed row size overflow"))?; + let min_encoded = min_packets.checked_mul(h as usize).ok_or_else(|| bad("compressed image size overflow"))?; + let encoded_len = image_end.saturating_sub(HEADER); + if encoded_len < min_encoded { + return Err(bad("PCX pixel data is too short for the declared image")); + } let mut row = vec![0u8; row_len]; - let mut pixels = vec![0u8; total]; + let mut pixels = Vec::new(); + pixels.try_reserve_exact(total).map_err(|_| bad("PCX pixel buffer is too large"))?; + pixels.resize(total, 0); let mut p = HEADER; let width = w as usize; for y in 0..h as usize { diff --git a/crates/codecs/src/codecs/xpm.rs b/crates/codecs/src/codecs/xpm.rs index 82543d8867..c20f3c58e9 100644 --- a/crates/codecs/src/codecs/xpm.rs +++ b/crates/codecs/src/codecs/xpm.rs @@ -206,11 +206,16 @@ fn decode_lines(lines: &[Vec], limits: &Limits) -> Result } } let row_len = width.checked_mul(cpp).ok_or_else(|| bad("row byte count overflow"))?; - let mut pixels = vec![0u8; width.checked_mul(height).and_then(|n| n.checked_mul(4)).ok_or_else(|| bad("pixel size overflow"))?]; + // Validate all source rows before reserving the decoded RGBA image. A malformed + // short row must not be able to make a large header-sized allocation first. + if lines[1 + colours..required].iter().any(|line| line.len() != row_len) { + return Err(bad("XPM row has the wrong width")); + } + let total = width.checked_mul(height).and_then(|n| n.checked_mul(4)).ok_or_else(|| bad("pixel size overflow"))?; + let mut pixels = Vec::new(); + pixels.try_reserve_exact(total).map_err(|_| bad("XPM pixel buffer is too large"))?; + pixels.resize(total, 0); for (y, line) in lines[1 + colours..required].iter().enumerate() { - if line.len() != row_len { - return Err(bad("XPM row has the wrong width")); - } for x in 0..width { let key = &line[x * cpp..(x + 1) * cpp]; let rgba = palette.get(key).ok_or_else(|| bad("unknown palette key"))?; diff --git a/crates/codecs/tests/camera_raw.rs b/crates/codecs/tests/it/camera_raw.rs similarity index 100% rename from crates/codecs/tests/camera_raw.rs rename to crates/codecs/tests/it/camera_raw.rs diff --git a/crates/codecs/tests/common/mod.rs b/crates/codecs/tests/it/common/mod.rs similarity index 100% rename from crates/codecs/tests/common/mod.rs rename to crates/codecs/tests/it/common/mod.rs diff --git a/crates/codecs/tests/common/tiffgen.rs b/crates/codecs/tests/it/common/tiffgen.rs similarity index 100% rename from crates/codecs/tests/common/tiffgen.rs rename to crates/codecs/tests/it/common/tiffgen.rs diff --git a/crates/codecs/tests/dds.rs b/crates/codecs/tests/it/dds.rs similarity index 100% rename from crates/codecs/tests/dds.rs rename to crates/codecs/tests/it/dds.rs diff --git a/crates/codecs/tests/dds_write.rs b/crates/codecs/tests/it/dds_write.rs similarity index 99% rename from crates/codecs/tests/dds_write.rs rename to crates/codecs/tests/it/dds_write.rs index 119101e4fd..e51e21ceda 100644 --- a/crates/codecs/tests/dds_write.rs +++ b/crates/codecs/tests/it/dds_write.rs @@ -348,7 +348,7 @@ fn compression_names_round_trip() { /// Encode timings on a synthetic ~30 MP texture (6336×4752). Ignored by default; run in release: /// /// ```sh -/// cargo test --release -p photocraft-codecs --test dds_write -- --ignored --nocapture +/// cargo test --release -p photocraft-codecs --test it -- dds_write:: --ignored --nocapture /// ``` #[test] #[ignore] diff --git a/crates/codecs/tests/decode_warnings.rs b/crates/codecs/tests/it/decode_warnings.rs similarity index 99% rename from crates/codecs/tests/decode_warnings.rs rename to crates/codecs/tests/it/decode_warnings.rs index 5fc310104a..82bf75b57d 100644 --- a/crates/codecs/tests/decode_warnings.rs +++ b/crates/codecs/tests/it/decode_warnings.rs @@ -1,7 +1,7 @@ //! Decode warnings: a file that holds more than was decoded (#523: animations, multi-page //! TIFF) or less than it should (#518: truncated JPEG) says so; complete single images don't. -mod common; +use crate::common; use common::*; use photocraft_codecs::*; diff --git a/crates/codecs/tests/deep_exr.rs b/crates/codecs/tests/it/deep_exr.rs similarity index 100% rename from crates/codecs/tests/deep_exr.rs rename to crates/codecs/tests/it/deep_exr.rs diff --git a/crates/codecs/tests/detect_caps.rs b/crates/codecs/tests/it/detect_caps.rs similarity index 99% rename from crates/codecs/tests/detect_caps.rs rename to crates/codecs/tests/it/detect_caps.rs index 2f55d3cf58..8db608de12 100644 --- a/crates/codecs/tests/detect_caps.rs +++ b/crates/codecs/tests/it/detect_caps.rs @@ -1,7 +1,7 @@ //! Magic-number detection, extensions, and the capability table //! (including the symmetric read/write guarantee). -mod common; +use crate::common; use common::*; use photocraft_codecs::*; diff --git a/crates/codecs/tests/dpx.rs b/crates/codecs/tests/it/dpx.rs similarity index 100% rename from crates/codecs/tests/dpx.rs rename to crates/codecs/tests/it/dpx.rs diff --git a/crates/codecs/tests/exr_cryptomatte.rs b/crates/codecs/tests/it/exr_cryptomatte.rs similarity index 100% rename from crates/codecs/tests/exr_cryptomatte.rs rename to crates/codecs/tests/it/exr_cryptomatte.rs diff --git a/crates/codecs/tests/exr_multipart.rs b/crates/codecs/tests/it/exr_multipart.rs similarity index 100% rename from crates/codecs/tests/exr_multipart.rs rename to crates/codecs/tests/it/exr_multipart.rs diff --git a/crates/codecs/tests/fidelity.rs b/crates/codecs/tests/it/fidelity.rs similarity index 99% rename from crates/codecs/tests/fidelity.rs rename to crates/codecs/tests/it/fidelity.rs index 93b0236fdf..2c584a559a 100644 --- a/crates/codecs/tests/fidelity.rs +++ b/crates/codecs/tests/it/fidelity.rs @@ -1,6 +1,6 @@ //! `fidelity_warnings` cases, and consistency with what `encode` does. -mod common; +use crate::common; use FidelityWarning as W; use common::*; use photocraft_codecs::*; diff --git a/crates/codecs/tests/gif_frames.rs b/crates/codecs/tests/it/gif_frames.rs similarity index 100% rename from crates/codecs/tests/gif_frames.rs rename to crates/codecs/tests/it/gif_frames.rs diff --git a/crates/codecs/tests/heif.rs b/crates/codecs/tests/it/heif.rs similarity index 99% rename from crates/codecs/tests/heif.rs rename to crates/codecs/tests/it/heif.rs index 6471a5ece6..bc1a185ae1 100644 --- a/crates/codecs/tests/heif.rs +++ b/crates/codecs/tests/it/heif.rs @@ -8,7 +8,7 @@ #![cfg(all(feature = "corpus", feature = "heif"))] -mod common; +use crate::common; use common::*; use photocraft_codecs::*; use std::sync::LazyLock; diff --git a/crates/codecs/tests/limits.rs b/crates/codecs/tests/it/limits.rs similarity index 99% rename from crates/codecs/tests/limits.rs rename to crates/codecs/tests/it/limits.rs index 6969fea922..c1873771f6 100644 --- a/crates/codecs/tests/limits.rs +++ b/crates/codecs/tests/it/limits.rs @@ -1,6 +1,6 @@ //! Decompression-bomb guards. -mod common; +use crate::common; use common::*; use photocraft_codecs::*; diff --git a/crates/codecs/tests/it/main.rs b/crates/codecs/tests/it/main.rs new file mode 100644 index 0000000000..3e77f071f0 --- /dev/null +++ b/crates/codecs/tests/it/main.rs @@ -0,0 +1,35 @@ +//! The crate's integration tests, linked into one test binary. + +mod camera_raw; +mod common; +mod dds; +mod dds_write; +mod decode_warnings; +mod deep_exr; +mod detect_caps; +mod dpx; +mod exr_cryptomatte; +mod exr_multipart; +mod fidelity; +mod gif_frames; +mod heif; +mod limits; +mod malformed; +mod metadata; +mod orientation; +mod pcx; +mod png_jpeg; +mod pnm_headers; +mod resolution; +mod roundtrip; +mod source_settings; +mod tga; +mod tiff_bench; +mod tiff_exif; +mod tiff_lab; +mod tiff_pages; +mod tiff_photoshop; +mod tiff_regressions; +mod webp_frames; +mod webp_lossy; +mod xpm; diff --git a/crates/codecs/tests/malformed.rs b/crates/codecs/tests/it/malformed.rs similarity index 99% rename from crates/codecs/tests/malformed.rs rename to crates/codecs/tests/it/malformed.rs index b6da84b072..4bb9ee7cb1 100644 --- a/crates/codecs/tests/malformed.rs +++ b/crates/codecs/tests/it/malformed.rs @@ -1,6 +1,6 @@ //! Malformed input must produce errors, never panics or huge allocations. -mod common; +use crate::common; use common::*; use photocraft_codecs::*; use proptest::prelude::*; diff --git a/crates/codecs/tests/metadata.rs b/crates/codecs/tests/it/metadata.rs similarity index 99% rename from crates/codecs/tests/metadata.rs rename to crates/codecs/tests/it/metadata.rs index d8f4d80a9a..b33ae0a715 100644 --- a/crates/codecs/tests/metadata.rs +++ b/crates/codecs/tests/it/metadata.rs @@ -1,6 +1,6 @@ //! ICC / EXIF / XMP / DPI / text preservation, per format, per caps. -mod common; +use crate::common; use common::*; use photocraft_codecs::*; @@ -36,7 +36,7 @@ fn check_format(format: Format) { } if c.exif && format == Format::Tiff { // TIFF writes the block's directories as its own and rebuilds a block from them on - // reading (tests/tiff_exif.rs); IFD0's orientation here is the image's. + // reading (tests/it/tiff_exif.rs); IFD0's orientation here is the image's. assert!(!warnings.contains(&FidelityWarning::ExifDropped), "{format:?}"); } else if c.exif { assert_eq!(back.meta.exif, img.meta.exif, "{format:?} exif"); diff --git a/crates/codecs/tests/orientation.rs b/crates/codecs/tests/it/orientation.rs similarity index 99% rename from crates/codecs/tests/orientation.rs rename to crates/codecs/tests/it/orientation.rs index c1f176b87c..26eeae030c 100644 --- a/crates/codecs/tests/orientation.rs +++ b/crates/codecs/tests/it/orientation.rs @@ -1,7 +1,7 @@ //! EXIF / TIFF orientation (#285): files are opened upright, and every export //! writes Orientation = 1 so the upright pixels are never rotated twice. -mod common; +use crate::common; use common::*; use photocraft_codecs::*; use proptest::prelude::{any, prop_assert, prop_assert_eq, proptest}; @@ -372,7 +372,7 @@ fn every_layout_and_depth_orients_and_inverts() { } /// #285 performance budget: turning a 24 MP photo upright on open adds ≤ 50 ms -/// (release build: `cargo test --release -p photocraft-codecs --test orientation -- --ignored`). +/// (release build: `cargo test --release -p photocraft-codecs --test it -- orientation:: --ignored`). #[test] #[ignore = "timing; run in release"] fn rotating_24_mp_is_fast() { diff --git a/crates/codecs/tests/pcx.rs b/crates/codecs/tests/it/pcx.rs similarity index 85% rename from crates/codecs/tests/pcx.rs rename to crates/codecs/tests/it/pcx.rs index a5796473e6..792a41021c 100644 --- a/crates/codecs/tests/pcx.rs +++ b/crates/codecs/tests/it/pcx.rs @@ -87,6 +87,25 @@ fn rejects_truncated_and_overshooting_rle_without_panicking() { let mut b = header(8, 3, 2, 1, 2); b[66..68].copy_from_slice(&0u16.to_le_bytes()); assert_eq!(detect(&b), None, "invalid stride is not a PCX signature"); + + // A solid image with stride of the form 63k + 1 (64, 127) encodes as k full 63-byte runs + // plus a 1-byte literal (2k + 1 bytes per plane row), which is valid and must decode. + for width in [64u16, 127] { + let mut solid = header(8, 3, width, 1, width); + for _plane in 0..3 { + let mut rem = usize::from(width); + while rem >= 63 { + solid.extend_from_slice(&[0xff, 0x00]); // 63-byte run of 0x00 + rem -= 63; + } + if rem == 1 { + solid.push(0x00); // 1-byte literal 0x00 + } + } + let im = decode(&solid).unwrap(); + assert_eq!(im.dimensions(), (u32::from(width), 1)); + assert!(im.data().iter().all(|&v| v == 0)); + } } #[test] diff --git a/crates/codecs/tests/png_jpeg.rs b/crates/codecs/tests/it/png_jpeg.rs similarity index 99% rename from crates/codecs/tests/png_jpeg.rs rename to crates/codecs/tests/it/png_jpeg.rs index bd704e9a1a..0b8b42a7b7 100644 --- a/crates/codecs/tests/png_jpeg.rs +++ b/crates/codecs/tests/it/png_jpeg.rs @@ -1,7 +1,7 @@ //! Format-specific behaviour: Adam7 PNG, JPEG colour models, oracle //! cross-checks against the `image` crate, and the optional PngSuite corpus. -mod common; +use crate::common; use common::*; use photocraft_codecs::*; diff --git a/crates/codecs/tests/pnm_headers.rs b/crates/codecs/tests/it/pnm_headers.rs similarity index 100% rename from crates/codecs/tests/pnm_headers.rs rename to crates/codecs/tests/it/pnm_headers.rs diff --git a/crates/codecs/tests/resolution.rs b/crates/codecs/tests/it/resolution.rs similarity index 100% rename from crates/codecs/tests/resolution.rs rename to crates/codecs/tests/it/resolution.rs diff --git a/crates/codecs/tests/roundtrip.rs b/crates/codecs/tests/it/roundtrip.rs similarity index 99% rename from crates/codecs/tests/roundtrip.rs rename to crates/codecs/tests/it/roundtrip.rs index 9ba9423509..acbd16c5db 100644 --- a/crates/codecs/tests/roundtrip.rs +++ b/crates/codecs/tests/it/roundtrip.rs @@ -2,7 +2,7 @@ //! Lossless formats must reproduce the (planned) conversion of the input //! exactly; lossy formats must stay above a PSNR threshold. -mod common; +use crate::common; use common::*; use photocraft_codecs::*; diff --git a/crates/codecs/tests/source_settings.rs b/crates/codecs/tests/it/source_settings.rs similarity index 99% rename from crates/codecs/tests/source_settings.rs rename to crates/codecs/tests/it/source_settings.rs index 9da82dbe79..0389e2fa8e 100644 --- a/crates/codecs/tests/source_settings.rs +++ b/crates/codecs/tests/it/source_settings.rs @@ -1,7 +1,7 @@ //! Reading back the settings a lossy file was saved with: a JPEG's quality from its //! quantisation tables, a WebP's lossy or lossless encoding (and its quality). -mod common; +use crate::common; use common::*; use photocraft_codecs::*; diff --git a/crates/codecs/tests/tga.rs b/crates/codecs/tests/it/tga.rs similarity index 100% rename from crates/codecs/tests/tga.rs rename to crates/codecs/tests/it/tga.rs diff --git a/crates/codecs/tests/tiff_bench.rs b/crates/codecs/tests/it/tiff_bench.rs similarity index 97% rename from crates/codecs/tests/tiff_bench.rs rename to crates/codecs/tests/it/tiff_bench.rs index 357c10486e..e17f6466d4 100644 --- a/crates/codecs/tests/tiff_bench.rs +++ b/crates/codecs/tests/it/tiff_bench.rs @@ -2,10 +2,10 @@ //! release: //! //! ```sh -//! cargo test --release -p photocraft-codecs --test tiff_bench -- --ignored --nocapture +//! cargo test --release -p photocraft-codecs --test it -- tiff_bench:: --ignored --nocapture //! ``` -mod common; +use crate::common; use common::tiffgen::*; use photocraft_codecs::*; use std::time::Instant; diff --git a/crates/codecs/tests/tiff_exif.rs b/crates/codecs/tests/it/tiff_exif.rs similarity index 100% rename from crates/codecs/tests/tiff_exif.rs rename to crates/codecs/tests/it/tiff_exif.rs diff --git a/crates/codecs/tests/tiff_lab.rs b/crates/codecs/tests/it/tiff_lab.rs similarity index 100% rename from crates/codecs/tests/tiff_lab.rs rename to crates/codecs/tests/it/tiff_lab.rs diff --git a/crates/codecs/tests/tiff_pages.rs b/crates/codecs/tests/it/tiff_pages.rs similarity index 99% rename from crates/codecs/tests/tiff_pages.rs rename to crates/codecs/tests/it/tiff_pages.rs index 60885e527d..db432abe51 100644 --- a/crates/codecs/tests/tiff_pages.rs +++ b/crates/codecs/tests/it/tiff_pages.rs @@ -4,7 +4,7 @@ //! offsets past the end, absurd sizes) that must give `Ok` or a clean `Err`, never a panic. //! Every file here is hand-built by `common::tiffgen`. -mod common; +use crate::common; use common::Rng; use common::tiffgen::*; use photocraft_codecs::*; diff --git a/crates/codecs/tests/tiff_photoshop.rs b/crates/codecs/tests/it/tiff_photoshop.rs similarity index 99% rename from crates/codecs/tests/tiff_photoshop.rs rename to crates/codecs/tests/it/tiff_photoshop.rs index 400b72eb0c..238710b68c 100644 --- a/crates/codecs/tests/tiff_photoshop.rs +++ b/crates/codecs/tests/it/tiff_photoshop.rs @@ -2,7 +2,7 @@ //! `Metadata` as opaque bytes: written when present, read from either byte order and from //! BigTIFF, and never a panic or an allocation on malformed input. -mod common; +use crate::common; use common::*; use photocraft_codecs::*; diff --git a/crates/codecs/tests/tiff_regressions.rs b/crates/codecs/tests/it/tiff_regressions.rs similarity index 99% rename from crates/codecs/tests/tiff_regressions.rs rename to crates/codecs/tests/it/tiff_regressions.rs index d823f33f4a..8fcb1e570c 100644 --- a/crates/codecs/tests/tiff_regressions.rs +++ b/crates/codecs/tests/it/tiff_regressions.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use common::tiffgen::*; use photocraft_codecs::{Image, decode, exif_orientation, upright_exif}; diff --git a/crates/codecs/tests/webp_frames.rs b/crates/codecs/tests/it/webp_frames.rs similarity index 100% rename from crates/codecs/tests/webp_frames.rs rename to crates/codecs/tests/it/webp_frames.rs diff --git a/crates/codecs/tests/webp_lossy.rs b/crates/codecs/tests/it/webp_lossy.rs similarity index 99% rename from crates/codecs/tests/webp_lossy.rs rename to crates/codecs/tests/it/webp_lossy.rs index f0ff2cbbb4..079b9134fd 100644 --- a/crates/codecs/tests/webp_lossy.rs +++ b/crates/codecs/tests/it/webp_lossy.rs @@ -3,7 +3,7 @@ //! smaller than lossless on photographic content; alpha and metadata travel in the container; //! odd sizes and the limits behave. -mod common; +use crate::common; use common::*; use photocraft_codecs::*; diff --git a/crates/codecs/tests/xpm.rs b/crates/codecs/tests/it/xpm.rs similarity index 100% rename from crates/codecs/tests/xpm.rs rename to crates/codecs/tests/it/xpm.rs diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 6b710eab93..ec5b4ac075 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -42,6 +42,7 @@ roxmltree = "0.20" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] tempfile = "3" +chrono = { workspace = true } # `file_cmds::same_file` on Windows: the volume serial number and file index, so a hard link to a # file is that file (std's `MetadataExt::file_index` is unstable). diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/analysis_cmds.rs index 92b630aa44..8932295d52 100644 --- a/crates/engine/src/analysis_cmds.rs +++ b/crates/engine/src/analysis_cmds.rs @@ -231,18 +231,7 @@ pub fn now_iso() -> String { #[cfg(not(target_arch = "wasm32"))] { let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); - let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); - // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm). - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = yoe + era * 400 + i64::from(m <= 2); - format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60) + iso_from_unix(secs) } #[cfg(target_arch = "wasm32")] { @@ -250,6 +239,29 @@ pub fn now_iso() -> String { } } +/// `YYYY-MM-DDTHH:MM:SSZ` for Unix seconds `secs` (UTC, proleptic Gregorian). A time outside +/// chrono's year range still converts (the calendar repeats every 400 years, so the instant is +/// moved into range by whole cycles and only the year is carried, matching the old hand-rolled +/// code), never a silent reset to the epoch. chrono is the only calendar logic. +#[cfg(not(target_arch = "wasm32"))] +fn iso_from_unix(secs: i64) -> String { + use chrono::Datelike; + let (days, sod) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); + let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097)); + // `rest + 719_163` (1970-01-01 is CE day 719_163) is always a valid CE day, and `sod` < 86_400. + let date = i32::try_from(rest + 719_163).ok().and_then(chrono::NaiveDate::from_num_days_from_ce_opt); + let time = u32::try_from(sod).ok().and_then(|s| chrono::NaiveTime::from_num_seconds_from_midnight_opt(s, 0)); + match (date, time) { + (Some(d), Some(t)) => { + let y = i128::from(d.year()) + i128::from(cycles) * 400; + let y = i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX }); + // `{:04}` rather than `%Y`, which writes a `+` before years past 9999. + format!("{y:04}-{}", d.and_time(t).format("%m-%dT%H:%M:%SZ")) + } + _ => "1970-01-01T00:00:00Z".to_string(), // unreachable + } +} + fn round4(v: f64) -> f64 { (v * 10_000.0).round() / 10_000.0 } diff --git a/crates/engine/src/analysis_cmds/tests.rs b/crates/engine/src/analysis_cmds/tests.rs index f9138e8b65..c1184f2a4c 100644 --- a/crates/engine/src/analysis_cmds/tests.rs +++ b/crates/engine/src/analysis_cmds/tests.rs @@ -535,3 +535,20 @@ fn count_add_keeps_first_group_creation_and_targets_the_requested_group() { let r = s.execute("count.add", json!({"x": 6, "y": 7})).unwrap(); assert_eq!(r["groups"][1]["points"], json!([[6.0, 7.0]])); } + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn iso_from_unix_matches_the_old_cycle_conversion_including_beyond_chrono() { + use super::iso_from_unix; + assert_eq!(iso_from_unix(0), "1970-01-01T00:00:00Z"); + assert_eq!(iso_from_unix(951_782_400), "2000-02-29T00:00:00Z"); + assert_eq!(iso_from_unix(1_791_446_357), "2026-10-08T07:59:17Z"); + // Years past 9999 keep the plain zero-padded year (no `+`). + assert_eq!(iso_from_unix(253_402_300_800), "10000-01-01T00:00:00Z"); + // Beyond chrono's year range the old hand-rolled code still converted; pin that output + // (never the epoch) in both directions and at the i64 extremes. + assert_eq!(iso_from_unix(10_000_000_000_000), "318857-05-20T17:46:40Z"); + assert_eq!(iso_from_unix(-10_000_000_000_000), "-314918-08-13T06:13:20Z"); + assert_eq!(iso_from_unix(i64::MAX), "292277026596-12-04T15:30:07Z"); + assert_eq!(iso_from_unix(i64::MIN), "-292277022657-01-27T08:29:52Z"); +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 406bdbe499..ebc7c49640 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -510,6 +510,8 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> R psd_maximize_compatibility: save.psd_maximize_compatibility, // Linked files a PSD embeds are resolved against the document being worked on. document_path: crate::doc_path::current(), + // An untrusted session's stored paths are document data: embed none of them. + read_linked_files: !crate::jobs::authorization_installed(), ..Default::default() }; // No quality chosen: write the file the way it was opened (a JPEG at its own quality, a WebP @@ -1679,6 +1681,9 @@ pub fn export_layers_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[ let cmd = "file.export.layersToFiles"; let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true); + // Callers outside `Session::execute` (headless workspace exports) carry the session's gate + // into `encode`, so a PSD embeds no file a linked smart object names. + let _authorization = crate::jobs::render_authorization_scope(s.authorize); let save = SaveOpts::from_params(s, p, cmd)?; let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 57846617dd..4a1c304241 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -66,6 +66,11 @@ pub(crate) fn authorize_render_command(id: &str, params: &Value) -> Result<()> { } } +/// Whether the work on this thread is done for an untrusted session (a gate is installed). +pub(crate) fn authorization_installed() -> bool { + RENDER_AUTHORIZATION.with(std::cell::Cell::get).is_some() +} + /// Identifies one background job for the session's lifetime. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, serde::Deserialize)] pub struct JobId(pub u64); diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs index fdd69e4568..556ad5c55a 100644 --- a/crates/engine/src/smart_cmds.rs +++ b/crates/engine/src/smart_cmds.rs @@ -79,10 +79,16 @@ fn base_name(path: &str) -> String { /// A linked file's bytes; `None` when it is missing or its path is not followed /// ([`crate::doc_path::resolve`]). +/// +/// The path is document data, not a request parameter, so every read rechecks it with the gate +/// of the session the work is done for: a filter, transform or refresh re-renders from here, +/// not only the contents commands that judge it up front. A refused path is handled like a +/// missing file: the layer keeps its last rendering. fn read_file(path: &str) -> Option> { if path.is_empty() { return None; } + crate::jobs::authorize_render_command("layer.smartObjects.updateModifiedContent", &json!({"path": path})).ok()?; photocraft_format::read_file(&crate::doc_path::resolve(path).ok()?).ok() } diff --git a/crates/engine/src/variables_cmds.rs b/crates/engine/src/variables_cmds.rs index 0560a9d593..67aa1fe4f4 100644 --- a/crates/engine/src/variables_cmds.rs +++ b/crates/engine/src/variables_cmds.rs @@ -243,10 +243,9 @@ fn replace_pixels(doc: &mut Document, layer: LayerId, path: &str, method: PixelM Ok(()) } -fn apply_data_set(s: &mut Session, p: &Value) -> Result { - let (set, idx) = resolve_set(s, p, "image.applyDataSet")?; - let vars = s.active().ok_or(EngineError::NoDocument)?.doc.variables.clone(); - // Pixel Replacement reads image files, so an untrusted session's gate judges each path. +/// Pixel Replacement reads image files, so an untrusted session's gate judges each path a data +/// set would read: whether it is applied or exported, the path is document data. +fn authorize_pixel_paths(s: &Session, set: &DataSet) -> Result<()> { if let Some(auth) = s.authorize { for dv in &set.values { if let VarValue::Pixels(path) = &dv.value { @@ -254,6 +253,13 @@ fn apply_data_set(s: &mut Session, p: &Value) -> Result { } } } + Ok(()) +} + +fn apply_data_set(s: &mut Session, p: &Value) -> Result { + let (set, idx) = resolve_set(s, p, "image.applyDataSet")?; + let vars = s.active().ok_or(EngineError::NoDocument)?.doc.variables.clone(); + authorize_pixel_paths(s, &set)?; s.edit(&format!("Apply Data Set \"{}\"", set.name), |doc, _| apply_to_doc(doc, &vars, &set))?; set_vars(s, |v| v.active = Some(idx))?; Ok(json!({"applied": set.name, "index": idx})) @@ -409,6 +415,10 @@ pub fn export_data_sets_with(s: &Session, p: &Value, mut write: impl FnMut(&str, if sets.is_empty() { return Err(bad("file.export.dataSetsAsFiles", "no data sets to export")); } + // Judge every image path before anything is written, as Apply Data Set does. + for set in &sets { + authorize_pixel_paths(s, set)?; + } // Filename template: `{name}` (sanitised data-set name), `{index}` (1-based). Default `{name}`. let template = p.get("naming").and_then(Value::as_str).unwrap_or("{name}"); let doc_stem = original.name.rsplit_once('.').map_or(original.name.as_str(), |(a, _)| a).to_string(); @@ -432,7 +442,8 @@ pub fn export_data_sets_with(s: &Session, p: &Value, mut write: impl FnMut(&str, for (set, name) in sets.iter().zip(&names) { let mut doc = (*original).clone(); apply_to_doc(&mut doc, &vars, set)?; - let opts = photocraft_io::ExportOptions::default(); + // An untrusted session's PSD export embeds no file a linked smart object names. + let opts = photocraft_io::ExportOptions { read_linked_files: s.authorize.is_none(), ..Default::default() }; let bytes = photocraft_io::export(&doc, format, &opts).map(|r| r.bytes).map_err(|e| EngineError::Other(format!("export `{}`: {e}", set.name)))?; write(name, &bytes)?; written.push(name.clone()); diff --git a/crates/engine/tests/affinity.rs b/crates/engine/tests/it/affinity.rs similarity index 100% rename from crates/engine/tests/affinity.rs rename to crates/engine/tests/it/affinity.rs diff --git a/crates/engine/tests/artboard_export_names.rs b/crates/engine/tests/it/artboard_export_names.rs similarity index 100% rename from crates/engine/tests/artboard_export_names.rs rename to crates/engine/tests/it/artboard_export_names.rs diff --git a/crates/engine/tests/atn_crystallize_cell_size.rs b/crates/engine/tests/it/atn_crystallize_cell_size.rs similarity index 100% rename from crates/engine/tests/atn_crystallize_cell_size.rs rename to crates/engine/tests/it/atn_crystallize_cell_size.rs diff --git a/crates/engine/tests/atn_ripple_amount.rs b/crates/engine/tests/it/atn_ripple_amount.rs similarity index 100% rename from crates/engine/tests/atn_ripple_amount.rs rename to crates/engine/tests/it/atn_ripple_amount.rs diff --git a/crates/engine/tests/atn_stroke_width.rs b/crates/engine/tests/it/atn_stroke_width.rs similarity index 100% rename from crates/engine/tests/atn_stroke_width.rs rename to crates/engine/tests/it/atn_stroke_width.rs diff --git a/crates/engine/tests/background_and_mask_depth.rs b/crates/engine/tests/it/background_and_mask_depth.rs similarity index 100% rename from crates/engine/tests/background_and_mask_depth.rs rename to crates/engine/tests/it/background_and_mask_depth.rs diff --git a/crates/engine/tests/background_layer_consistency.rs b/crates/engine/tests/it/background_layer_consistency.rs similarity index 100% rename from crates/engine/tests/background_layer_consistency.rs rename to crates/engine/tests/it/background_layer_consistency.rs diff --git a/crates/engine/tests/brush_smoothing.rs b/crates/engine/tests/it/brush_smoothing.rs similarity index 100% rename from crates/engine/tests/brush_smoothing.rs rename to crates/engine/tests/it/brush_smoothing.rs diff --git a/crates/engine/tests/camera_raw_exposure_clamp.rs b/crates/engine/tests/it/camera_raw_exposure_clamp.rs similarity index 100% rename from crates/engine/tests/camera_raw_exposure_clamp.rs rename to crates/engine/tests/it/camera_raw_exposure_clamp.rs diff --git a/crates/engine/tests/camera_raw_noise_clamp.rs b/crates/engine/tests/it/camera_raw_noise_clamp.rs similarity index 100% rename from crates/engine/tests/camera_raw_noise_clamp.rs rename to crates/engine/tests/it/camera_raw_noise_clamp.rs diff --git a/crates/engine/tests/clipping_semantics.rs b/crates/engine/tests/it/clipping_semantics.rs similarity index 100% rename from crates/engine/tests/clipping_semantics.rs rename to crates/engine/tests/it/clipping_semantics.rs diff --git a/crates/engine/tests/close_document.rs b/crates/engine/tests/it/close_document.rs similarity index 100% rename from crates/engine/tests/close_document.rs rename to crates/engine/tests/it/close_document.rs diff --git a/crates/engine/tests/command_lookup.rs b/crates/engine/tests/it/command_lookup.rs similarity index 100% rename from crates/engine/tests/command_lookup.rs rename to crates/engine/tests/it/command_lookup.rs diff --git a/crates/engine/tests/convert_keeps_references.rs b/crates/engine/tests/it/convert_keeps_references.rs similarity index 100% rename from crates/engine/tests/convert_keeps_references.rs rename to crates/engine/tests/it/convert_keeps_references.rs diff --git a/crates/engine/tests/corpus_atn.rs b/crates/engine/tests/it/corpus_atn.rs similarity index 100% rename from crates/engine/tests/corpus_atn.rs rename to crates/engine/tests/it/corpus_atn.rs diff --git a/crates/engine/tests/crop_content_aware.rs b/crates/engine/tests/it/crop_content_aware.rs similarity index 100% rename from crates/engine/tests/crop_content_aware.rs rename to crates/engine/tests/it/crop_content_aware.rs diff --git a/crates/engine/tests/current_affinity_artboards.rs b/crates/engine/tests/it/current_affinity_artboards.rs similarity index 97% rename from crates/engine/tests/current_affinity_artboards.rs rename to crates/engine/tests/it/current_affinity_artboards.rs index e3b27e856b..8348b4065f 100644 --- a/crates/engine/tests/current_affinity_artboards.rs +++ b/crates/engine/tests/it/current_affinity_artboards.rs @@ -1,7 +1,7 @@ //! Artboards recognized from current .af properties move with their children and undo together. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -#[path = "../../io/tests/support/current_affinity.rs"] +#[path = "../../../io/tests/support/current_affinity.rs"] mod fixture; use fixture::{Marker, document}; diff --git a/crates/engine/tests/duplicate_layer_comps.rs b/crates/engine/tests/it/duplicate_layer_comps.rs similarity index 100% rename from crates/engine/tests/duplicate_layer_comps.rs rename to crates/engine/tests/it/duplicate_layer_comps.rs diff --git a/crates/engine/tests/duplicate_slices.rs b/crates/engine/tests/it/duplicate_slices.rs similarity index 100% rename from crates/engine/tests/duplicate_slices.rs rename to crates/engine/tests/it/duplicate_slices.rs diff --git a/crates/engine/tests/duplicate_variables.rs b/crates/engine/tests/it/duplicate_variables.rs similarity index 100% rename from crates/engine/tests/duplicate_variables.rs rename to crates/engine/tests/it/duplicate_variables.rs diff --git a/crates/engine/tests/empty_selection_combine.rs b/crates/engine/tests/it/empty_selection_combine.rs similarity index 100% rename from crates/engine/tests/empty_selection_combine.rs rename to crates/engine/tests/it/empty_selection_combine.rs diff --git a/crates/engine/tests/eraser_locked.rs b/crates/engine/tests/it/eraser_locked.rs similarity index 100% rename from crates/engine/tests/eraser_locked.rs rename to crates/engine/tests/it/eraser_locked.rs diff --git a/crates/engine/tests/explicit_layer_target.rs b/crates/engine/tests/it/explicit_layer_target.rs similarity index 100% rename from crates/engine/tests/explicit_layer_target.rs rename to crates/engine/tests/it/explicit_layer_target.rs diff --git a/crates/engine/tests/export_shape_strokes.rs b/crates/engine/tests/it/export_shape_strokes.rs similarity index 100% rename from crates/engine/tests/export_shape_strokes.rs rename to crates/engine/tests/it/export_shape_strokes.rs diff --git a/crates/engine/tests/fill_lock_transparency.rs b/crates/engine/tests/it/fill_lock_transparency.rs similarity index 100% rename from crates/engine/tests/fill_lock_transparency.rs rename to crates/engine/tests/it/fill_lock_transparency.rs diff --git a/crates/engine/tests/filter_locked.rs b/crates/engine/tests/it/filter_locked.rs similarity index 100% rename from crates/engine/tests/filter_locked.rs rename to crates/engine/tests/it/filter_locked.rs diff --git a/crates/engine/tests/finite_command_params.rs b/crates/engine/tests/it/finite_command_params.rs similarity index 100% rename from crates/engine/tests/finite_command_params.rs rename to crates/engine/tests/it/finite_command_params.rs diff --git a/crates/engine/tests/flatten_background.rs b/crates/engine/tests/it/flatten_background.rs similarity index 100% rename from crates/engine/tests/flatten_background.rs rename to crates/engine/tests/it/flatten_background.rs diff --git a/crates/engine/tests/gallery_colours.rs b/crates/engine/tests/it/gallery_colours.rs similarity index 100% rename from crates/engine/tests/gallery_colours.rs rename to crates/engine/tests/it/gallery_colours.rs diff --git a/crates/engine/tests/gauss_small_sigma.rs b/crates/engine/tests/it/gauss_small_sigma.rs similarity index 100% rename from crates/engine/tests/gauss_small_sigma.rs rename to crates/engine/tests/it/gauss_small_sigma.rs diff --git a/crates/engine/tests/gradient_overlay_strokes.rs b/crates/engine/tests/it/gradient_overlay_strokes.rs similarity index 100% rename from crates/engine/tests/gradient_overlay_strokes.rs rename to crates/engine/tests/it/gradient_overlay_strokes.rs diff --git a/crates/engine/tests/guide_layout_limit.rs b/crates/engine/tests/it/guide_layout_limit.rs similarity index 100% rename from crates/engine/tests/guide_layout_limit.rs rename to crates/engine/tests/it/guide_layout_limit.rs diff --git a/crates/engine/tests/guide_layout_preview.rs b/crates/engine/tests/it/guide_layout_preview.rs similarity index 100% rename from crates/engine/tests/guide_layout_preview.rs rename to crates/engine/tests/it/guide_layout_preview.rs diff --git a/crates/engine/tests/hdr_gamma_direction.rs b/crates/engine/tests/it/hdr_gamma_direction.rs similarity index 100% rename from crates/engine/tests/hdr_gamma_direction.rs rename to crates/engine/tests/it/hdr_gamma_direction.rs diff --git a/crates/engine/tests/huge_doc_flatten.rs b/crates/engine/tests/it/huge_doc_flatten.rs similarity index 100% rename from crates/engine/tests/huge_doc_flatten.rs rename to crates/engine/tests/it/huge_doc_flatten.rs diff --git a/crates/engine/tests/jpeg_exif_resolution.rs b/crates/engine/tests/it/jpeg_exif_resolution.rs similarity index 100% rename from crates/engine/tests/jpeg_exif_resolution.rs rename to crates/engine/tests/it/jpeg_exif_resolution.rs diff --git a/crates/engine/tests/keyboard_shortcut_bulk.rs b/crates/engine/tests/it/keyboard_shortcut_bulk.rs similarity index 100% rename from crates/engine/tests/keyboard_shortcut_bulk.rs rename to crates/engine/tests/it/keyboard_shortcut_bulk.rs diff --git a/crates/engine/tests/kra.rs b/crates/engine/tests/it/kra.rs similarity index 96% rename from crates/engine/tests/kra.rs rename to crates/engine/tests/it/kra.rs index 8bdf10531c..783c5fb28f 100644 --- a/crates/engine/tests/kra.rs +++ b/crates/engine/tests/it/kra.rs @@ -1,7 +1,7 @@ //! Krita documents opened through the session: read-only source, 16-bit layers, editable //! layers with history, and saving as OpenRaster or native. The files come from //! `tools/krita-oracles/generate.py` in https://github.com/storytold/photocraft-corpus. Run with -//! `KRITA_TEST_DIR= cargo test -p photocraft-engine --test kra -- --ignored --nocapture`. +//! `KRITA_TEST_DIR= cargo test -p photocraft-engine --test it -- kra:: --ignored --nocapture`. use photocraft_engine::Session; use serde_json::json; @@ -24,7 +24,7 @@ fn krita_documents_open_read_only_and_stay_editable() { assert!(session.execute("file.save", json!({})).is_err()); // Krita's merged image is the composite (the corpus files carry no ICC profile, so both - // sides are sRGB); crates/io/tests/krita_corpus.rs compares every file. + // sides are sRGB); crates/io/tests/it/krita_corpus.rs compares every file. let ours = photocraft_compose::flatten(&session.active().unwrap().doc); let zip_bytes = std::fs::read(&path).unwrap(); let zip = photocraft_format::zip::ZipReader::new(&zip_bytes).unwrap(); diff --git a/crates/engine/tests/kys_import.rs b/crates/engine/tests/it/kys_import.rs similarity index 100% rename from crates/engine/tests/kys_import.rs rename to crates/engine/tests/it/kys_import.rs diff --git a/crates/engine/tests/layer_delete_last.rs b/crates/engine/tests/it/layer_delete_last.rs similarity index 100% rename from crates/engine/tests/layer_delete_last.rs rename to crates/engine/tests/it/layer_delete_last.rs diff --git a/crates/engine/tests/layer_mask_depth.rs b/crates/engine/tests/it/layer_mask_depth.rs similarity index 100% rename from crates/engine/tests/layer_mask_depth.rs rename to crates/engine/tests/it/layer_mask_depth.rs diff --git a/crates/engine/tests/layer_props_several.rs b/crates/engine/tests/it/layer_props_several.rs similarity index 100% rename from crates/engine/tests/layer_props_several.rs rename to crates/engine/tests/it/layer_props_several.rs diff --git a/crates/engine/tests/layer_range_panel_order.rs b/crates/engine/tests/it/layer_range_panel_order.rs similarity index 100% rename from crates/engine/tests/layer_range_panel_order.rs rename to crates/engine/tests/it/layer_range_panel_order.rs diff --git a/crates/engine/tests/live_line_transform.rs b/crates/engine/tests/it/live_line_transform.rs similarity index 100% rename from crates/engine/tests/live_line_transform.rs rename to crates/engine/tests/it/live_line_transform.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs new file mode 100644 index 0000000000..cd44a7a946 --- /dev/null +++ b/crates/engine/tests/it/main.rs @@ -0,0 +1,80 @@ +//! The crate's integration tests, linked into one test binary. + +mod affinity; +mod artboard_export_names; +mod atn_crystallize_cell_size; +mod atn_ripple_amount; +mod atn_stroke_width; +mod background_and_mask_depth; +mod background_layer_consistency; +mod brush_smoothing; +mod camera_raw_exposure_clamp; +mod camera_raw_noise_clamp; +mod clipping_semantics; +mod close_document; +mod command_lookup; +mod convert_keeps_references; +mod corpus_atn; +mod crop_content_aware; +mod current_affinity_artboards; +mod duplicate_layer_comps; +mod duplicate_slices; +mod duplicate_variables; +mod empty_selection_combine; +mod eraser_locked; +mod explicit_layer_target; +mod export_shape_strokes; +mod fill_lock_transparency; +mod filter_locked; +mod finite_command_params; +mod flatten_background; +mod gallery_colours; +mod gauss_small_sigma; +mod gradient_overlay_strokes; +mod guide_layout_limit; +mod guide_layout_preview; +mod hdr_gamma_direction; +mod huge_doc_flatten; +mod jpeg_exif_resolution; +mod keyboard_shortcut_bulk; +mod kra; +mod kys_import; +mod layer_delete_last; +mod layer_mask_depth; +mod layer_props_several; +mod layer_range_panel_order; +mod live_line_transform; +mod merge_transparent_bounds; +mod missing_layer_error; +mod nonfinite_style; +mod open_identity; +mod path_blur_speed_clamp; +mod path_transform_target; +mod pdn; +mod photoshop_oracles; +mod pixel_lock_edits; +mod precheck; +mod prefs_usage; +mod rasterize_psd_reopen; +mod rasterize_selected_layers; +mod rendering_preferences; +mod save_keeps_encoding; +mod selection_layer_commands; +mod shortcut_sets; +mod shortcuts_headless; +mod smart_clipboard_sources; +mod smart_duplicates; +mod smart_filter_canvas_geometry; +mod smart_object_tones; +mod smart_psd; +mod style_and_align; +mod svg_smart_object; +mod transform_budget_unclamped; +mod type_format_targets; +mod type_postscript_font; +mod undo_keeps_active_layer; +mod unicode_colors; +mod unsupported_smart_filters; +mod wand_transparent_copy; +mod working_rgb_profile; +mod xmp_charref; diff --git a/crates/engine/tests/merge_transparent_bounds.rs b/crates/engine/tests/it/merge_transparent_bounds.rs similarity index 100% rename from crates/engine/tests/merge_transparent_bounds.rs rename to crates/engine/tests/it/merge_transparent_bounds.rs diff --git a/crates/engine/tests/missing_layer_error.rs b/crates/engine/tests/it/missing_layer_error.rs similarity index 100% rename from crates/engine/tests/missing_layer_error.rs rename to crates/engine/tests/it/missing_layer_error.rs diff --git a/crates/engine/tests/nonfinite_style.rs b/crates/engine/tests/it/nonfinite_style.rs similarity index 100% rename from crates/engine/tests/nonfinite_style.rs rename to crates/engine/tests/it/nonfinite_style.rs diff --git a/crates/engine/tests/open_identity.rs b/crates/engine/tests/it/open_identity.rs similarity index 100% rename from crates/engine/tests/open_identity.rs rename to crates/engine/tests/it/open_identity.rs diff --git a/crates/engine/tests/path_blur_speed_clamp.rs b/crates/engine/tests/it/path_blur_speed_clamp.rs similarity index 100% rename from crates/engine/tests/path_blur_speed_clamp.rs rename to crates/engine/tests/it/path_blur_speed_clamp.rs diff --git a/crates/engine/tests/path_transform_target.rs b/crates/engine/tests/it/path_transform_target.rs similarity index 100% rename from crates/engine/tests/path_transform_target.rs rename to crates/engine/tests/it/path_transform_target.rs diff --git a/crates/engine/tests/pdn.rs b/crates/engine/tests/it/pdn.rs similarity index 100% rename from crates/engine/tests/pdn.rs rename to crates/engine/tests/it/pdn.rs diff --git a/crates/engine/tests/photoshop_oracles.rs b/crates/engine/tests/it/photoshop_oracles.rs similarity index 98% rename from crates/engine/tests/photoshop_oracles.rs rename to crates/engine/tests/it/photoshop_oracles.rs index b1f0a133a1..88e63b67fc 100644 --- a/crates/engine/tests/photoshop_oracles.rs +++ b/crates/engine/tests/it/photoshop_oracles.rs @@ -3,7 +3,7 @@ //! `cargo xtask corpus --all`. Feature `corpus` (run with `cargo xtask test-corpus`); a missing //! corpus fails. //! -//! The io corpus test (`crates/io/tests/corpus.rs`) flattens imported documents, which composite +//! The io corpus test (`crates/io/tests/it/corpus.rs`) flattens imported documents, which composite //! Photoshop's own cached pixels for smart objects and type layers. This test throws those caches //! away: every smart object is re-rendered from its embedded source through our smart-filter //! stack, and every type layer is re-laid-out and re-rasterised by our text engine; the flatten is diff --git a/crates/engine/tests/pixel_lock_edits.rs b/crates/engine/tests/it/pixel_lock_edits.rs similarity index 100% rename from crates/engine/tests/pixel_lock_edits.rs rename to crates/engine/tests/it/pixel_lock_edits.rs diff --git a/crates/engine/tests/precheck.rs b/crates/engine/tests/it/precheck.rs similarity index 100% rename from crates/engine/tests/precheck.rs rename to crates/engine/tests/it/precheck.rs diff --git a/crates/engine/tests/prefs_usage.rs b/crates/engine/tests/it/prefs_usage.rs similarity index 100% rename from crates/engine/tests/prefs_usage.rs rename to crates/engine/tests/it/prefs_usage.rs diff --git a/crates/engine/tests/rasterize_psd_reopen.rs b/crates/engine/tests/it/rasterize_psd_reopen.rs similarity index 100% rename from crates/engine/tests/rasterize_psd_reopen.rs rename to crates/engine/tests/it/rasterize_psd_reopen.rs diff --git a/crates/engine/tests/rasterize_selected_layers.rs b/crates/engine/tests/it/rasterize_selected_layers.rs similarity index 100% rename from crates/engine/tests/rasterize_selected_layers.rs rename to crates/engine/tests/it/rasterize_selected_layers.rs diff --git a/crates/engine/tests/rendering_preferences.rs b/crates/engine/tests/it/rendering_preferences.rs similarity index 100% rename from crates/engine/tests/rendering_preferences.rs rename to crates/engine/tests/it/rendering_preferences.rs diff --git a/crates/engine/tests/save_keeps_encoding.rs b/crates/engine/tests/it/save_keeps_encoding.rs similarity index 100% rename from crates/engine/tests/save_keeps_encoding.rs rename to crates/engine/tests/it/save_keeps_encoding.rs diff --git a/crates/engine/tests/selection_layer_commands.rs b/crates/engine/tests/it/selection_layer_commands.rs similarity index 100% rename from crates/engine/tests/selection_layer_commands.rs rename to crates/engine/tests/it/selection_layer_commands.rs diff --git a/crates/engine/tests/shortcut_sets.rs b/crates/engine/tests/it/shortcut_sets.rs similarity index 100% rename from crates/engine/tests/shortcut_sets.rs rename to crates/engine/tests/it/shortcut_sets.rs diff --git a/crates/engine/tests/shortcuts_headless.rs b/crates/engine/tests/it/shortcuts_headless.rs similarity index 100% rename from crates/engine/tests/shortcuts_headless.rs rename to crates/engine/tests/it/shortcuts_headless.rs diff --git a/crates/engine/tests/smart_clipboard_sources.rs b/crates/engine/tests/it/smart_clipboard_sources.rs similarity index 100% rename from crates/engine/tests/smart_clipboard_sources.rs rename to crates/engine/tests/it/smart_clipboard_sources.rs diff --git a/crates/engine/tests/smart_duplicates.rs b/crates/engine/tests/it/smart_duplicates.rs similarity index 100% rename from crates/engine/tests/smart_duplicates.rs rename to crates/engine/tests/it/smart_duplicates.rs diff --git a/crates/engine/tests/smart_filter_canvas_geometry.rs b/crates/engine/tests/it/smart_filter_canvas_geometry.rs similarity index 100% rename from crates/engine/tests/smart_filter_canvas_geometry.rs rename to crates/engine/tests/it/smart_filter_canvas_geometry.rs diff --git a/crates/engine/tests/smart_object_tones.rs b/crates/engine/tests/it/smart_object_tones.rs similarity index 100% rename from crates/engine/tests/smart_object_tones.rs rename to crates/engine/tests/it/smart_object_tones.rs diff --git a/crates/engine/tests/smart_psd.rs b/crates/engine/tests/it/smart_psd.rs similarity index 99% rename from crates/engine/tests/smart_psd.rs rename to crates/engine/tests/it/smart_psd.rs index 5bba21f122..4aeda1519b 100644 --- a/crates/engine/tests/smart_psd.rs +++ b/crates/engine/tests/it/smart_psd.rs @@ -331,7 +331,7 @@ fn photoshop_samples() { } /// PSD export of a 24 MP smart object versus the same layer as pixels (release: -/// `cargo test --release -p photocraft-engine --test smart_psd -- --ignored --nocapture perf`). +/// `cargo test --release -p photocraft-engine --test it -- --ignored --nocapture smart_psd::perf`). #[test] #[ignore = "benchmark"] fn perf_24mp_smart_object_export() { diff --git a/crates/engine/tests/style_and_align.rs b/crates/engine/tests/it/style_and_align.rs similarity index 100% rename from crates/engine/tests/style_and_align.rs rename to crates/engine/tests/it/style_and_align.rs diff --git a/crates/engine/tests/svg_smart_object.rs b/crates/engine/tests/it/svg_smart_object.rs similarity index 100% rename from crates/engine/tests/svg_smart_object.rs rename to crates/engine/tests/it/svg_smart_object.rs diff --git a/crates/engine/tests/transform_budget_unclamped.rs b/crates/engine/tests/it/transform_budget_unclamped.rs similarity index 100% rename from crates/engine/tests/transform_budget_unclamped.rs rename to crates/engine/tests/it/transform_budget_unclamped.rs diff --git a/crates/engine/tests/type_format_targets.rs b/crates/engine/tests/it/type_format_targets.rs similarity index 100% rename from crates/engine/tests/type_format_targets.rs rename to crates/engine/tests/it/type_format_targets.rs diff --git a/crates/engine/tests/type_postscript_font.rs b/crates/engine/tests/it/type_postscript_font.rs similarity index 100% rename from crates/engine/tests/type_postscript_font.rs rename to crates/engine/tests/it/type_postscript_font.rs diff --git a/crates/engine/tests/undo_keeps_active_layer.rs b/crates/engine/tests/it/undo_keeps_active_layer.rs similarity index 100% rename from crates/engine/tests/undo_keeps_active_layer.rs rename to crates/engine/tests/it/undo_keeps_active_layer.rs diff --git a/crates/engine/tests/unicode_colors.rs b/crates/engine/tests/it/unicode_colors.rs similarity index 100% rename from crates/engine/tests/unicode_colors.rs rename to crates/engine/tests/it/unicode_colors.rs diff --git a/crates/engine/tests/unsupported_smart_filters.rs b/crates/engine/tests/it/unsupported_smart_filters.rs similarity index 100% rename from crates/engine/tests/unsupported_smart_filters.rs rename to crates/engine/tests/it/unsupported_smart_filters.rs diff --git a/crates/engine/tests/wand_transparent_copy.rs b/crates/engine/tests/it/wand_transparent_copy.rs similarity index 100% rename from crates/engine/tests/wand_transparent_copy.rs rename to crates/engine/tests/it/wand_transparent_copy.rs diff --git a/crates/engine/tests/working_rgb_profile.rs b/crates/engine/tests/it/working_rgb_profile.rs similarity index 100% rename from crates/engine/tests/working_rgb_profile.rs rename to crates/engine/tests/it/working_rgb_profile.rs diff --git a/crates/engine/tests/xmp_charref.rs b/crates/engine/tests/it/xmp_charref.rs similarity index 100% rename from crates/engine/tests/xmp_charref.rs rename to crates/engine/tests/it/xmp_charref.rs diff --git a/crates/format/src/atomic/tests.rs b/crates/format/src/atomic/tests.rs index 853a11293d..d48cf7d9a6 100644 --- a/crates/format/src/atomic/tests.rs +++ b/crates/format/src/atomic/tests.rs @@ -328,6 +328,19 @@ fn keeps_the_original_file_mode() { assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600); } +#[cfg(unix)] +#[test] +fn new_file_follows_the_process_umask() { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("umask"); + let probe = d.0.join("probe.psd"); + std::fs::File::create(&probe).unwrap(); + let expected = std::fs::metadata(&probe).unwrap().permissions().mode() & 0o777; + let p = d.0.join("fresh.psd"); + atomic_write(&p, b"new").unwrap(); + assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, expected); +} + #[cfg(unix)] #[test] fn writes_through_a_symlink() { diff --git a/crates/format/src/autosave.rs b/crates/format/src/autosave.rs index fa3c9a4085..cb09e27cb8 100644 --- a/crates/format/src/autosave.rs +++ b/crates/format/src/autosave.rs @@ -20,7 +20,6 @@ use std::time::{SystemTime, UNIX_EPOCH}; use photocraft_doc::Document; use serde::{Deserialize, Serialize}; -use crate::store::write_atomic; use crate::{FormatError, PcraftWriter, Result, SaveOptions, SaveStats}; /// Sidecar describing an autosave. @@ -168,7 +167,7 @@ fn worker(rx: Receiver, bundle: PathBuf, sidecar: PathBuf, last: Arc, bundle: PathBuf, sidecar: PathBuf, last: Arc Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + struct PrivateFs; + impl crate::atomic::AtomicFs for PrivateFs { + fn write_new(&self, tmp: &Path, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write; + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(tmp)?; + f.write_all(bytes)?; + crate::atomic::sync_file(&f) + } + fn rename(&self, from: &Path, to: &Path) -> std::io::Result<()> { + crate::atomic::RealFs.rename(from, to) + } + fn remove(&self, path: &Path) -> std::io::Result<()> { + crate::atomic::RealFs.remove(path) + } + fn sync_dir(&self, dir: &Path) -> std::io::Result<()> { + crate::atomic::RealFs.sync_dir(dir) + } + fn copy_metadata(&self, from: &Path, to: &Path) -> std::io::Result<()> { + crate::atomic::RealFs.copy_metadata(from, to) + } + } + crate::atomic::atomic_write_with(&PrivateFs, crate::atomic::RenameRetry::platform(), path, bytes)?; + Ok(()) + } + #[cfg(not(unix))] + { + crate::store::write_atomic(path, bytes) + } +} + +fn read_sidecar_bounded(path: &Path, max: usize) -> Option> { + use std::io::Read; + #[cfg(unix)] + let mut file = { + use rustix::fs::{Mode, OFlags, open}; + let fd = open(path, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty()).ok()?; + let file = std::fs::File::from(fd); + if !file.metadata().ok()?.is_file() { + return None; + } + let _ = rustix::fs::fcntl_setfl(&file, OFlags::empty()); + file + }; + #[cfg(not(unix))] + let mut file = { + if !std::fs::symlink_metadata(path).ok()?.file_type().is_file() { + return None; + } + let file = std::fs::File::open(path).ok()?; + if !file.metadata().ok()?.is_file() { + return None; + } + file + }; + let mut bytes = Vec::new(); + (&mut file).take((max as u64).saturating_add(1)).read_to_end(&mut bytes).ok()?; + if bytes.len() > max { + return None; + } + Some(bytes) +} + /// Recoverable documents in `recovery_dir`, newest first. A sidecar must be named after its own /// (sanitized) key, so a stray or hand-edited one can never point outside the directory. pub fn list_recovery(recovery_dir: &Path) -> Vec { @@ -189,8 +254,9 @@ pub fn list_recovery(recovery_dir: &Path) -> Vec { }; for e in rd.flatten() { let p = e.path(); - if p.extension().is_some_and(|x| x == "json") - && let Ok(bytes) = std::fs::read(&p) + if e.file_type().is_ok_and(|ft| ft.is_file()) + && p.extension().is_some_and(|x| x == "json") + && let Some(bytes) = read_sidecar_bounded(&p, 1 << 20) && let Ok(info) = serde_json::from_slice::(&bytes) && sanitize(&info.key) == info.key && p.file_stem().is_some_and(|stem| *stem == *info.key) @@ -402,6 +468,9 @@ fn untouched_for(path: &Path, min_age: std::time::Duration, missing_ok: bool) -> } fn remove_entry(dir: &Path, key: &str) -> Result<()> { + if sanitize(key) != key { + return Err(FormatError::corrupt("recovery entry key contains path components")); + } let bundle = dir.join(format!("{key}.pcraft")); if bundle.exists() { std::fs::remove_dir_all(bundle)?; diff --git a/crates/format/src/read.rs b/crates/format/src/read.rs index 4ebfcbbfa6..8c72a20406 100644 --- a/crates/format/src/read.rs +++ b/crates/format/src/read.rs @@ -23,8 +23,28 @@ pub fn read_file(path: &Path) -> io::Result> { /// [`read_file`] with a chosen read size (tests use small ones to exercise the loop). pub fn read_file_with(path: &Path, chunk: usize) -> io::Result> { - let mut f = std::fs::File::open(path)?; - let len = f.metadata().map(|m| m.len()).unwrap_or(0); + #[cfg(unix)] + let (mut f, metadata) = { + use rustix::fs::{Mode, OFlags, open}; + let fd = open(path, OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty()).map_err(io::Error::from)?; + let f = std::fs::File::from(fd); + let metadata = f.metadata()?; + if !metadata.is_file() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "path is not a regular file")); + } + rustix::fs::fcntl_setfl(&f, OFlags::empty()).map_err(io::Error::from)?; + (f, metadata) + }; + #[cfg(not(unix))] + let (mut f, metadata) = { + let f = std::fs::File::open(path)?; + let metadata = f.metadata()?; + if !metadata.is_file() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "path is not a regular file")); + } + (f, metadata) + }; + let len = metadata.len(); read_all_with(&mut f, len, chunk) } diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index 03a85cbc83..18e6a9b432 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -598,7 +598,14 @@ fn write_bundle_file(root: &Path, path: &Path, data: &[u8], fs: &dyn crate::atom let mut temporary = None; for _ in 0..8 { let candidate = parent.join(crate::atomic::temp_name(&name.to_string_lossy())); - match std::fs::OpenOptions::new().write(true).create_new(true).open(&candidate) { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + match opts.open(&candidate) { Ok(file) => { temporary = Some((candidate, file)); break; diff --git a/crates/format/tests/analysis.rs b/crates/format/tests/it/analysis.rs similarity index 100% rename from crates/format/tests/analysis.rs rename to crates/format/tests/it/analysis.rs diff --git a/crates/format/tests/autosave.rs b/crates/format/tests/it/autosave.rs similarity index 99% rename from crates/format/tests/autosave.rs rename to crates/format/tests/it/autosave.rs index a1954682a1..24d61d50d3 100644 --- a/crates/format/tests/autosave.rs +++ b/crates/format/tests/it/autosave.rs @@ -1,6 +1,6 @@ //! Background autosave and crash recovery. -mod common; +use crate::common; use std::sync::Arc; use common::*; diff --git a/crates/format/tests/common/mod.rs b/crates/format/tests/it/common/mod.rs similarity index 100% rename from crates/format/tests/common/mod.rs rename to crates/format/tests/it/common/mod.rs diff --git a/crates/format/tests/corruption.rs b/crates/format/tests/it/corruption.rs similarity index 99% rename from crates/format/tests/corruption.rs rename to crates/format/tests/it/corruption.rs index 727b37cb70..fd2d0602f6 100644 --- a/crates/format/tests/corruption.rs +++ b/crates/format/tests/it/corruption.rs @@ -1,6 +1,6 @@ //! Damaged or hostile bundles must fail cleanly, never panic. -mod common; +use crate::common; use common::*; use photocraft_color::{ColorMode, SampleType}; use photocraft_format::*; diff --git a/crates/format/tests/directory_symlinks.rs b/crates/format/tests/it/directory_symlinks.rs similarity index 99% rename from crates/format/tests/directory_symlinks.rs rename to crates/format/tests/it/directory_symlinks.rs index edeebbdc3d..0a8d7d2462 100644 --- a/crates/format/tests/directory_symlinks.rs +++ b/crates/format/tests/it/directory_symlinks.rs @@ -1,6 +1,6 @@ //! Directory cleanup only owns content-addressed objects; unrelated files survive. -mod common; +use crate::common; use common::temp_dir; use photocraft_color::{ColorMode, SampleType}; diff --git a/crates/format/tests/float_roundtrip.rs b/crates/format/tests/it/float_roundtrip.rs similarity index 100% rename from crates/format/tests/float_roundtrip.rs rename to crates/format/tests/it/float_roundtrip.rs diff --git a/crates/format/tests/layer_labels.rs b/crates/format/tests/it/layer_labels.rs similarity index 100% rename from crates/format/tests/layer_labels.rs rename to crates/format/tests/it/layer_labels.rs diff --git a/crates/format/tests/it/main.rs b/crates/format/tests/it/main.rs new file mode 100644 index 0000000000..6c822f4282 --- /dev/null +++ b/crates/format/tests/it/main.rs @@ -0,0 +1,11 @@ +//! The crate's integration tests, linked into one test binary. + +mod analysis; +mod autosave; +mod common; +mod corruption; +mod directory_symlinks; +mod float_roundtrip; +mod layer_labels; +mod roundtrip; +mod smart_contents; diff --git a/crates/format/tests/roundtrip.rs b/crates/format/tests/it/roundtrip.rs similarity index 99% rename from crates/format/tests/roundtrip.rs rename to crates/format/tests/it/roundtrip.rs index b123214a58..72de346c32 100644 --- a/crates/format/tests/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -1,6 +1,6 @@ //! doc → .pcraft → doc equality, incremental saves, ids, previews. -mod common; +use crate::common; use common::*; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::text::{CharStyle, ParagraphStyle, TextRun}; diff --git a/crates/format/tests/smart_contents.rs b/crates/format/tests/it/smart_contents.rs similarity index 100% rename from crates/format/tests/smart_contents.rs rename to crates/format/tests/it/smart_contents.rs diff --git a/crates/gpu/tests/device_loss.rs b/crates/gpu/tests/it/device_loss.rs similarity index 98% rename from crates/gpu/tests/device_loss.rs rename to crates/gpu/tests/it/device_loss.rs index 294961ee8d..666e434da4 100644 --- a/crates/gpu/tests/device_loss.rs +++ b/crates/gpu/tests/it/device_loss.rs @@ -8,8 +8,7 @@ use photocraft_geom::{Rect, Size}; use photocraft_gpu::{Compositor, DeviceHealth, Fault, render_to_vec}; use photocraft_raster::Surface; -/// Concurrent wgpu instances in one process segfault on some drivers (see `parity.rs`). -static GPU_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); +use crate::GPU_LOCK; fn device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> { let instance = wgpu::Instance::default(); diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs new file mode 100644 index 0000000000..f71972c5b9 --- /dev/null +++ b/crates/gpu/tests/it/main.rs @@ -0,0 +1,11 @@ +//! The crate's integration tests, linked into one test binary. + +/// Concurrent wgpu instances in one process segfault on some drivers (RADV), so every test that +/// creates a device takes this lock and holds it until the device is dropped. +static GPU_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +mod device_loss; +mod parity; +mod timing; +mod uniform_limits; +mod vector_mask; diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/it/parity.rs similarity index 99% rename from crates/gpu/tests/parity.rs rename to crates/gpu/tests/it/parity.rs index 400c5a03b7..464ad1f1a2 100644 --- a/crates/gpu/tests/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -12,9 +12,7 @@ use photocraft_gpu::{Compositor, render_to_vec}; /// lands on that side at the Hue/Saturation pixel in `adjustment_layers`). const TOL: f32 = 1.0 / 255.0 + 4.0 * f32::EPSILON; -/// Concurrent wgpu instances in one process segfault on some drivers (RADV), so the GPU tests -/// take this lock and hold it until their device is dropped. -static GPU_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); +use crate::GPU_LOCK; struct Gpu { device: wgpu::Device, diff --git a/crates/gpu/tests/timing.rs b/crates/gpu/tests/it/timing.rs similarity index 96% rename from crates/gpu/tests/timing.rs rename to crates/gpu/tests/it/timing.rs index 24c2057253..9761a1d90d 100644 --- a/crates/gpu/tests/timing.rs +++ b/crates/gpu/tests/it/timing.rs @@ -111,6 +111,7 @@ fn measure(device: &wgpu::Device, queue: &wgpu::Queue, comp: &mut Compositor, do #[test] fn gpu_time_tracks_execution_not_submission() { + let _lock = crate::GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let Some((device, queue, mut comp)) = gpu() else { return }; let size = Size::new(3000, 2000); let doc = document(size); @@ -164,6 +165,7 @@ fn gpu_time_tracks_execution_not_submission() { #[test] fn an_unmeasured_compositor_reports_nothing() { + let _lock = crate::GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let Some((device, queue, _)) = gpu() else { return }; let mut comp = Compositor::new(&device); assert!(!comp.measures_gpu_time(), "timing is off until it is asked for"); @@ -175,6 +177,7 @@ fn an_unmeasured_compositor_reports_nothing() { #[test] fn a_refresh_that_submits_several_times_is_one_measurement() { + let _lock = crate::GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let Some((device, queue, mut comp)) = gpu() else { return }; // A budget far below the document's layer pages makes the refresh evict as it goes, which is // what makes it submit in batches: the measurement must span all of them, not just the last. @@ -208,6 +211,7 @@ fn a_refresh_that_submits_several_times_is_one_measurement() { #[test] fn refreshes_faster_than_the_readback_stay_valid() { + let _lock = crate::GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let Some((device, queue, mut comp)) = gpu() else { return }; // Refreshes arriving before the last measurement has been read back must simply go // unmeasured. Mapping the readback buffer again while its first map is still pending is a @@ -232,6 +236,7 @@ fn refreshes_faster_than_the_readback_stay_valid() { /// wrote no timestamps itself — and the compositor would silently never measure again. #[test] fn a_failed_refresh_that_recorded_nothing_keeps_the_timer_alive() { + let _lock = crate::GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let Some((device, queue, _)) = gpu() else { return }; let mut timer = timing::GpuTimer::new(&device, &queue).expect("the device has timestamp queries"); diff --git a/crates/gpu/tests/uniform_limits.rs b/crates/gpu/tests/it/uniform_limits.rs similarity index 99% rename from crates/gpu/tests/uniform_limits.rs rename to crates/gpu/tests/it/uniform_limits.rs index 994dbd7508..90dfa57aed 100644 --- a/crates/gpu/tests/uniform_limits.rs +++ b/crates/gpu/tests/it/uniform_limits.rs @@ -5,7 +5,7 @@ use photocraft_doc::{Document, Fill, Layer, LayerContent}; use photocraft_geom::Size; use photocraft_gpu::{Compositor, DeviceHealth, plan, render_to_vec}; -static GPU_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); +use crate::GPU_LOCK; fn fills(count: usize) -> Document { fills_size(count, Size::new(1, 1)) diff --git a/crates/gpu/tests/vector_mask.rs b/crates/gpu/tests/it/vector_mask.rs similarity index 98% rename from crates/gpu/tests/vector_mask.rs rename to crates/gpu/tests/it/vector_mask.rs index 43d3d081e3..d0d7e7a012 100644 --- a/crates/gpu/tests/vector_mask.rs +++ b/crates/gpu/tests/it/vector_mask.rs @@ -47,6 +47,7 @@ fn painted(name: &str, fmt: PixelFormat, rgba: [f32; 4]) -> Layer { #[test] fn vector_masks_match_the_cpu() { + let _lock = crate::GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let Some(mut g) = gpu() else { return }; for depth in [SampleType::U8, SampleType::U16] { for (inverted, density) in [(false, 1.0), (true, 1.0), (false, 0.6)] { diff --git a/crates/heif/README.md b/crates/heif/README.md index 8915129443..9d859e8401 100644 --- a/crates/heif/README.md +++ b/crates/heif/README.md @@ -30,5 +30,5 @@ inside it (fuzzing found two in 0.1.1) becomes `Error::Malformed`. The crate depends on no other PhotoCraft crate and knows nothing of `photocraft-codecs`' types; `codecs` → `heif` is the one allowed dependency between standalone crates (`cargo xtask layers`). -Tests on real files live in `photocraft-codecs` (`tests/heif.rs`, features `corpus,heif`, files +Tests on real files live in `photocraft-codecs` (`tests/it/heif.rs`, features `corpus,heif`, files fetched by `cargo xtask corpus --heif`). diff --git a/crates/io/examples/big_psb_check.rs b/crates/io/examples/big_psb_check.rs index 3d0f407583..3b1c21034b 100644 --- a/crates/io/examples/big_psb_check.rs +++ b/crates/io/examples/big_psb_check.rs @@ -2,7 +2,7 @@ //! //! `cargo run --release -p photocraft-io --example big_psb_check -- ...` //! -//! The opt-in tests in `tests/large_files.rs` generate and check the same files. +//! The opt-in tests in `tests/it/large_files.rs` generate and check the same files. use photocraft_psd::fixtures::sample; diff --git a/crates/io/examples/oracle_diff.rs b/crates/io/examples/oracle_diff.rs index a7f295d463..fddef567a9 100644 --- a/crates/io/examples/oracle_diff.rs +++ b/crates/io/examples/oracle_diff.rs @@ -437,7 +437,7 @@ fn main() { } } -/// The corpus oracle table (as `tests/corpus.rs`), files in parallel, without a test build. +/// The corpus oracle table (as `tests/it/corpus.rs`), files in parallel, without a test build. fn corpus_summary(root: &std::path::Path) { fn collect(dir: &std::path::Path, out: &mut Vec) { let Ok(rd) = std::fs::read_dir(dir) else { return }; diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index a0fc3e87e2..2289670dbb 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -232,6 +232,9 @@ pub struct ExportOptions { pub document_path: Option, /// Reuse one cache per open document for native saves; other formats ignore it. pub pcraft_cache: Option, + /// PSD/PSB and layered TIFF: read and embed the files linked smart objects name (see + /// [`PsdExportOptions::read_linked_files`]). On by default; automation turns it off. + pub read_linked_files: bool, } impl Default for ExportOptions { @@ -246,6 +249,7 @@ impl Default for ExportOptions { psd_maximize_compatibility: true, document_path: None, pcraft_cache: None, + read_linked_files: true, } } } @@ -526,6 +530,7 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & force_psb: opts.force_psb || ext == "psb", maximize_compatibility: opts.psd_maximize_compatibility, document_path: opts.document_path.clone(), + read_linked_files: opts.read_linked_files, ..Default::default() }; let (mut file, mut warnings) = with_span(ctl, 0.0, PSD_MODEL_DONE, |ctl| psd_export::document_to_psd_interruptible(doc, &o, ctl)); diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 90a5d86ce9..fd07adde50 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -50,6 +50,10 @@ pub struct PsdExportOptions { /// The path of the document's own file: linked smart objects are resolved against it /// ([`crate::doc_path::resolve`]) before they are read and embedded. pub document_path: Option, + /// Read and embed the files linked smart objects name. On by default; automation turns it + /// off, since a stored path is document data rather than a granted file: such a layer is + /// then written as pixels, with a warning. + pub read_linked_files: bool, } impl Default for PsdExportOptions { @@ -61,6 +65,7 @@ impl Default for PsdExportOptions { merged_compression: Compression::Rle, maximize_compatibility: true, document_path: None, + read_linked_files: true, } } } @@ -71,6 +76,8 @@ struct Ex { dpi: f32, /// The document's own file, which linked smart objects are resolved against. document: Option, + /// Whether linked files may be read and embedded ([`PsdExportOptions::read_linked_files`]). + read_linked_files: bool, /// Character/paragraph styles written into every type layer's engine data. text_styles: photocraft_doc::TextStyles, mask_fmt: PixelFormat, @@ -977,6 +984,9 @@ impl Ex { SmartSource::Linked { path } => { #[cfg(not(target_arch = "wasm32"))] { + if !self.read_linked_files { + return Err(format!("the linked file {path} is not read for this export")); + } let file = crate::doc_path::resolve(path, self.document.as_deref()).map_err(|e| format!("the linked file {path} is not opened: {e}"))?; let bytes = std::fs::read(file).map_err(|e| format!("the linked file {path} can't be read: {e}"))?; let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_string(); @@ -1049,7 +1059,7 @@ impl Ex { let doc = photocraft_format::load_from_bytes(bytes).map_err(|e| format!("its contents can't be read: {e}"))?; let (file, warnings) = document_to_psd_nested( &doc, - &PsdExportOptions { force_psb: true, document_path: self.document.clone(), ..Default::default() }, + &PsdExportOptions { force_psb: true, document_path: self.document.clone(), read_linked_files: self.read_linked_files, ..Default::default() }, self.smart.depth + 1, &Interrupt::NONE, ); @@ -1595,6 +1605,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c fmt, dpi: doc.resolution_dpi, document: opts.document_path.clone(), + read_linked_files: opts.read_linked_files, text_styles: doc.text_styles.clone(), text_index: Default::default(), mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false), diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index ac1bd27ffa..6bc256d4e0 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -28,6 +28,48 @@ use crate::{ImportResult, IoError}; pub const MAX_SIDE: u32 = 16_384; /// A rasterised fallback layer or a smart-object render never exceeds this many pixels. const MAX_RASTER_PIXELS: u64 = 24_000_000; +/// Largest decoded byte size (RGBA8) accepted for an embedded raster image before resvg decodes +/// it. resvg/tiny-skia allocate the full intrinsic image before any destination-size scaling, +/// so a highly compressed PNG or WebP could otherwise trigger gigabyte-scale allocation and +/// decompression that the destination pixmap's size check never sees. +const MAX_EMBEDDED_IMAGE_BYTES: u64 = MAX_RASTER_PIXELS * 4; + +/// The IHDR width/height of a PNG, read directly from its header (no decoding): the signature +/// (8 bytes), the IHDR chunk's length and type (8 bytes), then big-endian width and height. +fn png_dimensions(data: &[u8]) -> Option<(u32, u32)> { + let sig = data.get(0..8)?; + if sig != [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A] { + return None; + } + if data.get(12..16)? != b"IHDR" { + return None; + } + let w = u32::from_be_bytes(data.get(16..20)?.try_into().ok()?); + let h = u32::from_be_bytes(data.get(20..24)?.try_into().ok()?); + Some((w, h)) +} + +/// Intrinsic dimensions of a raster image resvg can embed, from its header alone, for formats +/// where decoding allocates the full image before any destination scaling (PNG, WebP). +/// Returns `Some(Some((w, h)))` when the format is PNG/WebP and its header parses cleanly, +/// `Some(None)` when the format is PNG/WebP (by MIME or magic bytes under `"text/plain"`) +/// and its header is malformed, or `None` for other formats. +fn embedded_image_dimensions(mime: &str, data: &[u8]) -> Option> { + match mime { + "image/png" => Some(png_dimensions(data)), + "image/webp" => Some(photocraft_codecs::probe_size(data).ok()), + "text/plain" => { + if data.starts_with(&[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]) { + Some(png_dimensions(data)) + } else if data.get(0..4) == Some(b"RIFF") && data.get(8..12) == Some(b"WEBP") { + Some(photocraft_codecs::probe_size(data).ok()) + } else { + None + } + } + _ => None, + } +} /// Aggregate memory for retained fallback surfaces in the document's pixel format. const MAX_PIXEL_BYTES: u64 = 1 << 30; /// Estimated peak during raster conversion (retained surfaces + RGBA8 pixmap + f32 staging + tiles). @@ -139,9 +181,36 @@ fn system_generic_family(_generic: &str) -> Option { /// `~/.ssh/...`) into the document. Embedded SVG images get no `` resolution at all /// (`usvg` already blanks it for sub-SVGs). fn options(fontdb: Arc) -> usvg::Options<'static> { + let default_resolver = usvg::ImageHrefResolver::default_data_resolver(); + let resolve_data: usvg::ImageHrefDataResolverFn<'static> = Box::new(move |mime, data, opts| { + // Reject embedded images whose decoded RGBA storage would exceed the budget before + // resvg (which allocates the full intrinsic image before any destination scaling) ever + // sees them. Formats without a cheap header probe fall through unchanged; their decode + // path is bounded elsewhere or accepted as-is, matching the previous behavior. + if let Some(probed) = embedded_image_dimensions(mime, &data) { + let (w, h) = probed?; + let decoded = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4); + if decoded > MAX_EMBEDDED_IMAGE_BYTES { + return None; + } + } + // An embedded `image/svg+xml` value can itself be gzip-compressed (SVGZ-in-data-URL). + // The default resolver's sub-SVG loader checks for the gzip magic and decompresses + // again with no byte limit of its own. Apply our bounded inflate first: if the data is + // gzip-compressed, hand the default resolver the already-decompressed (and + // size-checked) bytes, which no longer start with the gzip magic, so it parses them + // directly instead of decompressing a second time. + if (mime == "image/svg+xml" || mime == "text/plain") && data.starts_with(&[0x1f, 0x8b]) { + return match inflate(&data) { + Ok(xml) if !xml.starts_with(&[0x1f, 0x8b]) => default_resolver("image/svg+xml", std::sync::Arc::new(xml.into_owned()), opts), + _ => None, + }; + } + default_resolver(mime, data, opts) + }); usvg::Options { resources_dir: None, - image_href_resolver: usvg::ImageHrefResolver { resolve_data: usvg::ImageHrefResolver::default_data_resolver(), resolve_string: Box::new(|_, _| None) }, + image_href_resolver: usvg::ImageHrefResolver { resolve_data, resolve_string: Box::new(|_, _| None) }, fontdb, ..usvg::Options::default() } @@ -174,7 +243,11 @@ fn parse_with(bytes: &[u8], fonts: fn() -> Arc) -> Resul let fontdb = if has_text { fonts() } else { Arc::new(usvg::fontdb::Database::new()) }; let fontless_text = has_text && fontdb.faces().next().is_none(); let opt = options(fontdb); - let tree = usvg::Tree::from_data(&xml, &opt).map_err(|e| IoError::Svg(e.to_string()))?; + // Parse the already-bounded-and-decoded text with from_str, not from_data: from_data + // re-checks the gzip magic and would decompress a second time without our size limit if + // the inflated content happened to start with a nested gzip stream. + let text = std::str::from_utf8(&xml).map_err(|_| IoError::Svg("the SVG is not valid UTF-8".into()))?; + let tree = usvg::Tree::from_str(text, &opt).map_err(|e| IoError::Svg(e.to_string()))?; Ok(Parsed { tree, fontless_text }) } @@ -1058,4 +1131,46 @@ mod tests { assert_eq!((cv.size.width, cv.size.height), (MAX_SIDE, MAX_SIDE / 2)); assert_eq!(w.len(), 1); } + + #[test] + fn resolve_data_rejects_oversized_and_malformed_embedded_png_and_webp() { + let opt = options(Arc::new(usvg::fontdb::Database::new())); + let resolve = &opt.image_href_resolver.resolve_data; + let img = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![255; 12]).unwrap(); + let valid_png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + assert!(resolve("image/png", Arc::new(valid_png.clone()), &opt).is_some()); + assert!(resolve("text/plain", Arc::new(valid_png.clone()), &opt).is_some()); + + let mut huge_png = valid_png; + huge_png[16..20].copy_from_slice(&40_000u32.to_be_bytes()); + huge_png[20..24].copy_from_slice(&40_000u32.to_be_bytes()); + assert!(resolve("image/png", Arc::new(huge_png.clone()), &opt).is_none(), "oversized PNG rejected before decode"); + assert!(resolve("text/plain", Arc::new(huge_png), &opt).is_none(), "oversized mime-less PNG rejected before decode"); + + // Malformed WebP header under image/webp or text/plain must be rejected at the probe step. + let bad_webp = b"RIFF\x10\x00\x00\x00WEBPVP8 ".to_vec(); + assert!(resolve("image/webp", Arc::new(bad_webp.clone()), &opt).is_none()); + assert!(resolve("text/plain", Arc::new(bad_webp), &opt).is_none()); + } + + #[test] + fn resolve_data_rejects_nested_gzip_and_handles_text_plain_svgz() { + use std::io::Write; + fn gz(bytes: &[u8]) -> Vec { + let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + e.write_all(bytes).unwrap(); + e.finish().unwrap() + } + let opt = options(Arc::new(usvg::fontdb::Database::new())); + let resolve = &opt.image_href_resolver.resolve_data; + let svg = b""; + let once = gz(svg); + assert!(resolve("image/svg+xml", Arc::new(once.clone()), &opt).is_some()); + assert!(resolve("text/plain", Arc::new(once.clone()), &opt).is_some()); + + // Doubly gzip-compressed payload must be rejected rather than decompressed a second time by usvg. + let twice = gz(&once); + assert!(resolve("image/svg+xml", Arc::new(twice.clone()), &opt).is_none()); + assert!(resolve("text/plain", Arc::new(twice), &opt).is_none()); + } } diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 6caf335768..d6c0a845b3 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -216,6 +216,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr merged_compression: Compression::Raw, maximize_compatibility: true, document_path: opts.document_path.clone(), + read_linked_files: opts.read_linked_files, }; // TIFF has no palette, bitmap or duotone layout: the PSD model of an Indexed Color, Bitmap // or Duotone document is made in its pixel format (RGB or Grayscale), which the PSD exporter diff --git a/crates/io/tests/adjust_blend_roundtrip.rs b/crates/io/tests/it/adjust_blend_roundtrip.rs similarity index 99% rename from crates/io/tests/adjust_blend_roundtrip.rs rename to crates/io/tests/it/adjust_blend_roundtrip.rs index 4e8b727af2..67085abee3 100644 --- a/crates/io/tests/adjust_blend_roundtrip.rs +++ b/crates/io/tests/it/adjust_blend_roundtrip.rs @@ -4,7 +4,7 @@ //! document flattens to the same composite (within 1/255) in every case, so nothing a user made //! in PhotoCraft silently disappears or changes when Photoshop opens the file. -mod common; +use crate::common; use std::sync::Arc; diff --git a/crates/io/tests/adjust_warnings.rs b/crates/io/tests/it/adjust_warnings.rs similarity index 100% rename from crates/io/tests/adjust_warnings.rs rename to crates/io/tests/it/adjust_warnings.rs diff --git a/crates/io/tests/affinity.rs b/crates/io/tests/it/affinity.rs similarity index 100% rename from crates/io/tests/affinity.rs rename to crates/io/tests/it/affinity.rs diff --git a/crates/io/tests/affinity_artboards.rs b/crates/io/tests/it/affinity_artboards.rs similarity index 98% rename from crates/io/tests/affinity_artboards.rs rename to crates/io/tests/it/affinity_artboards.rs index 67e3739043..26a9a3c7e5 100644 --- a/crates/io/tests/affinity_artboards.rs +++ b/crates/io/tests/it/affinity_artboards.rs @@ -1,7 +1,7 @@ //! Current .af artboards stay separate, editable and clipped through native/PSD saves. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -#[path = "support/current_affinity.rs"] +#[path = "../support/current_affinity.rs"] mod fixture; use fixture::{Marker, document}; diff --git a/crates/io/tests/affinity_corpus.rs b/crates/io/tests/it/affinity_corpus.rs similarity index 100% rename from crates/io/tests/affinity_corpus.rs rename to crates/io/tests/it/affinity_corpus.rs diff --git a/crates/io/tests/annotations.rs b/crates/io/tests/it/annotations.rs similarity index 100% rename from crates/io/tests/annotations.rs rename to crates/io/tests/it/annotations.rs diff --git a/crates/io/tests/artboard_guide_order.rs b/crates/io/tests/it/artboard_guide_order.rs similarity index 100% rename from crates/io/tests/artboard_guide_order.rs rename to crates/io/tests/it/artboard_guide_order.rs diff --git a/crates/io/tests/banded.rs b/crates/io/tests/it/banded.rs similarity index 100% rename from crates/io/tests/banded.rs rename to crates/io/tests/it/banded.rs diff --git a/crates/io/tests/cancel.rs b/crates/io/tests/it/cancel.rs similarity index 100% rename from crates/io/tests/cancel.rs rename to crates/io/tests/it/cancel.rs diff --git a/crates/io/tests/channels.rs b/crates/io/tests/it/channels.rs similarity index 100% rename from crates/io/tests/channels.rs rename to crates/io/tests/it/channels.rs diff --git a/crates/io/tests/cmyk_composite_export.rs b/crates/io/tests/it/cmyk_composite_export.rs similarity index 100% rename from crates/io/tests/cmyk_composite_export.rs rename to crates/io/tests/it/cmyk_composite_export.rs diff --git a/crates/io/tests/color.rs b/crates/io/tests/it/color.rs similarity index 99% rename from crates/io/tests/color.rs rename to crates/io/tests/it/color.rs index c5d4479904..b553097ae4 100644 --- a/crates/io/tests/color.rs +++ b/crates/io/tests/it/color.rs @@ -1,7 +1,7 @@ //! ICC profiles through import/export: byte-exact PSD round trips with real profiles, PNG/JPEG //! embedding and extraction, colour-managed CMYK → RGB for formats without CMYK. -mod common; +use crate::common; use std::sync::Arc; diff --git a/crates/io/tests/common/mod.rs b/crates/io/tests/it/common/mod.rs similarity index 100% rename from crates/io/tests/common/mod.rs rename to crates/io/tests/it/common/mod.rs diff --git a/crates/io/tests/composite.rs b/crates/io/tests/it/composite.rs similarity index 99% rename from crates/io/tests/composite.rs rename to crates/io/tests/it/composite.rs index fbb9e5ab3d..cef80e6a08 100644 --- a/crates/io/tests/composite.rs +++ b/crates/io/tests/it/composite.rs @@ -1,7 +1,7 @@ //! Composite oracle: the merged image stored in a PSD must match our //! compositor's rendering of the imported document. -mod common; +use crate::common; use common::*; use photocraft_color::{BlendMode, ColorMode, SampleType}; diff --git a/crates/io/tests/comps_artboards.rs b/crates/io/tests/it/comps_artboards.rs similarity index 100% rename from crates/io/tests/comps_artboards.rs rename to crates/io/tests/it/comps_artboards.rs diff --git a/crates/io/tests/corpus.rs b/crates/io/tests/it/corpus.rs similarity index 99% rename from crates/io/tests/corpus.rs rename to crates/io/tests/it/corpus.rs index 831529d115..b7695d451a 100644 --- a/crates/io/tests/corpus.rs +++ b/crates/io/tests/it/corpus.rs @@ -44,7 +44,7 @@ //! asserts import + flatten return (Ok or Err) without panicking. #![cfg(feature = "corpus")] -mod common; +use crate::common; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::path::{Path, PathBuf}; diff --git a/crates/io/tests/corpus_regressions.rs b/crates/io/tests/it/corpus_regressions.rs similarity index 99% rename from crates/io/tests/corpus_regressions.rs rename to crates/io/tests/it/corpus_regressions.rs index b335642cc9..26266c9f07 100644 --- a/crates/io/tests/corpus_regressions.rs +++ b/crates/io/tests/it/corpus_regressions.rs @@ -1,5 +1,5 @@ //! Synthetic reproductions of failures found by the psd-tools corpus -//! (`cargo xtask corpus --psd-tools`; see `tests/corpus.rs`). The corpus +//! (`cargo xtask corpus --psd-tools`; see `tests/it/corpus.rs`). The corpus //! files themselves are never committed: each test rebuilds the relevant //! structure from our own documents. diff --git a/crates/io/tests/effects_multi.rs b/crates/io/tests/it/effects_multi.rs similarity index 100% rename from crates/io/tests/effects_multi.rs rename to crates/io/tests/it/effects_multi.rs diff --git a/crates/io/tests/exif_resolution.rs b/crates/io/tests/it/exif_resolution.rs similarity index 100% rename from crates/io/tests/exif_resolution.rs rename to crates/io/tests/it/exif_resolution.rs diff --git a/crates/io/tests/export_progress.rs b/crates/io/tests/it/export_progress.rs similarity index 100% rename from crates/io/tests/export_progress.rs rename to crates/io/tests/it/export_progress.rs diff --git a/crates/io/tests/exr_part_profile.rs b/crates/io/tests/it/exr_part_profile.rs similarity index 100% rename from crates/io/tests/exr_part_profile.rs rename to crates/io/tests/it/exr_part_profile.rs diff --git a/crates/io/tests/flat.rs b/crates/io/tests/it/flat.rs similarity index 99% rename from crates/io/tests/flat.rs rename to crates/io/tests/it/flat.rs index 98833d45d5..353e2bbb7a 100644 --- a/crates/io/tests/flat.rs +++ b/crates/io/tests/it/flat.rs @@ -1,6 +1,6 @@ //! Flat formats through photocraft-codecs, and export warnings. -mod common; +use crate::common; use common::*; use photocraft_color::{ColorMode, SampleType}; diff --git a/crates/io/tests/gif_frames.rs b/crates/io/tests/it/gif_frames.rs similarity index 100% rename from crates/io/tests/gif_frames.rs rename to crates/io/tests/it/gif_frames.rs diff --git a/crates/io/tests/guides_v2.rs b/crates/io/tests/it/guides_v2.rs similarity index 100% rename from crates/io/tests/guides_v2.rs rename to crates/io/tests/it/guides_v2.rs diff --git a/crates/io/tests/heif.rs b/crates/io/tests/it/heif.rs similarity index 100% rename from crates/io/tests/heif.rs rename to crates/io/tests/it/heif.rs diff --git a/crates/io/tests/heif_unsupported.rs b/crates/io/tests/it/heif_unsupported.rs similarity index 100% rename from crates/io/tests/heif_unsupported.rs rename to crates/io/tests/it/heif_unsupported.rs diff --git a/crates/io/tests/krita_corpus.rs b/crates/io/tests/it/krita_corpus.rs similarity index 97% rename from crates/io/tests/krita_corpus.rs rename to crates/io/tests/it/krita_corpus.rs index b0b3a01d63..ab2c56c143 100644 --- a/crates/io/tests/krita_corpus.rs +++ b/crates/io/tests/it/krita_corpus.rs @@ -2,7 +2,7 @@ //! Krita's own rendering of the layer stack (`mergedimage.png`). The files are generated by //! `tools/krita-oracles/generate.py` in https://github.com/storytold/photocraft-corpus and are //! not bundled. Run with -//! `KRITA_TEST_DIR= cargo test -p photocraft-io --test krita_corpus -- --ignored --nocapture`. +//! `KRITA_TEST_DIR= cargo test -p photocraft-io --test it -- krita_corpus:: --ignored --nocapture`. use std::path::{Path, PathBuf}; diff --git a/crates/io/tests/lab16.rs b/crates/io/tests/it/lab16.rs similarity index 100% rename from crates/io/tests/lab16.rs rename to crates/io/tests/it/lab16.rs diff --git a/crates/io/tests/large_files.rs b/crates/io/tests/it/large_files.rs similarity index 98% rename from crates/io/tests/large_files.rs rename to crates/io/tests/it/large_files.rs index f492dd2d65..b0a2669480 100644 --- a/crates/io/tests/large_files.rs +++ b/crates/io/tests/it/large_files.rs @@ -5,7 +5,7 @@ //! //! The two layered documents run in memory; the streamed files are written to //! `$PHOTOCRAFT_FIXTURE_DIR` (default: the system temp dir), removed afterwards, and are opt-in: -//! `cargo test --release -p photocraft-io --test large_files -- --ignored`. +//! `cargo test --release -p photocraft-io --test it -- large_files:: --ignored`. use std::path::PathBuf; diff --git a/crates/io/tests/large_psb.rs b/crates/io/tests/it/large_psb.rs similarity index 96% rename from crates/io/tests/large_psb.rs rename to crates/io/tests/it/large_psb.rs index bcde955bd0..da9f6ca9a1 100644 --- a/crates/io/tests/large_psb.rs +++ b/crates/io/tests/it/large_psb.rs @@ -25,7 +25,7 @@ fn undecodable_channel_leaves_the_layer_empty() { /// A flattened 29000² RGB PSB: its merged image decodes to 2.52 GB, past the old 2 GiB cap, which /// opened it as a document with no layers. Needs about 12 GB of memory, so it is opt-in: -/// `cargo test --release -p photocraft-io --test large_psb -- --ignored`. +/// `cargo test --release -p photocraft-io --test it -- large_psb:: --ignored`. #[test] #[ignore = "allocates ~12 GB; run in release"] fn flattened_psb_with_a_merged_image_over_2_gib_opens() { diff --git a/crates/io/tests/layer_labels.rs b/crates/io/tests/it/layer_labels.rs similarity index 100% rename from crates/io/tests/layer_labels.rs rename to crates/io/tests/it/layer_labels.rs diff --git a/crates/io/tests/layer_xmp.rs b/crates/io/tests/it/layer_xmp.rs similarity index 100% rename from crates/io/tests/layer_xmp.rs rename to crates/io/tests/it/layer_xmp.rs diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs new file mode 100644 index 0000000000..662d37c307 --- /dev/null +++ b/crates/io/tests/it/main.rs @@ -0,0 +1,76 @@ +//! The crate's integration tests, linked into one test binary. + +mod adjust_blend_roundtrip; +mod adjust_warnings; +mod affinity; +mod affinity_artboards; +mod affinity_corpus; +mod annotations; +mod artboard_guide_order; +mod banded; +mod cancel; +mod channels; +mod cmyk_composite_export; +mod color; +mod common; +mod composite; +mod comps_artboards; +mod corpus; +mod corpus_regressions; +mod effects_multi; +mod exif_resolution; +mod export_progress; +mod exr_part_profile; +mod flat; +mod gif_frames; +mod guides_v2; +mod heif; +mod heif_unsupported; +mod krita_corpus; +mod lab16; +mod large_files; +mod large_psb; +mod layer_labels; +mod layer_xmp; +mod modes; +mod multichannel; +mod orientation; +mod pattern_fill_psd; +mod pcraft_manifest_name; +mod pdn_corpus; +mod png_text_metadata; +mod psd16_merged_transparency; +mod psd32_export; +mod psd_background; +mod psd_block_alignment; +mod psd_block_layout; +mod psd_damaged_merged; +mod psd_empty_channels; +mod psd_font_identity; +mod psd_kerning; +mod psd_layer_block_length; +mod psd_maximize_compatibility; +mod psd_noise_fill_roundtrip; +mod psd_roundtrip_bytes; +mod psd_structure; +mod psd_style_sheets; +mod psd_thumbnail; +mod psd_type_bounds; +mod psd_type_photoshop_bytes; +mod psd_unknown_adjustment; +mod psd_vertical_type; +mod raw; +mod resolution_axes; +mod roundtrip; +mod smart_contents_identity; +mod smart_corpus; +mod svg; +mod text_corpus; +mod text_styles; +mod tiff_corpus; +mod tiff_layers; +mod tiff_pages; +mod tiff_type_geometry; +mod vector; +mod xcf; +mod xmp_export; diff --git a/crates/io/tests/modes.rs b/crates/io/tests/it/modes.rs similarity index 100% rename from crates/io/tests/modes.rs rename to crates/io/tests/it/modes.rs diff --git a/crates/io/tests/multichannel.rs b/crates/io/tests/it/multichannel.rs similarity index 100% rename from crates/io/tests/multichannel.rs rename to crates/io/tests/it/multichannel.rs diff --git a/crates/io/tests/orientation.rs b/crates/io/tests/it/orientation.rs similarity index 100% rename from crates/io/tests/orientation.rs rename to crates/io/tests/it/orientation.rs diff --git a/crates/io/tests/pattern_fill_psd.rs b/crates/io/tests/it/pattern_fill_psd.rs similarity index 100% rename from crates/io/tests/pattern_fill_psd.rs rename to crates/io/tests/it/pattern_fill_psd.rs diff --git a/crates/io/tests/pcraft_manifest_name.rs b/crates/io/tests/it/pcraft_manifest_name.rs similarity index 98% rename from crates/io/tests/pcraft_manifest_name.rs rename to crates/io/tests/it/pcraft_manifest_name.rs index 285fa02203..fffb88fa8b 100644 --- a/crates/io/tests/pcraft_manifest_name.rs +++ b/crates/io/tests/it/pcraft_manifest_name.rs @@ -1,7 +1,7 @@ //! A `.pcraft` bundle's manifest reports the file it is in (#3312): writing a document to a new //! name must not leave the previous one inside, on every path that produces `.pcraft` bytes. -mod common; +use crate::common; use common::*; use photocraft_color::{ColorMode, SampleType}; diff --git a/crates/io/tests/pdn_corpus.rs b/crates/io/tests/it/pdn_corpus.rs similarity index 98% rename from crates/io/tests/pdn_corpus.rs rename to crates/io/tests/it/pdn_corpus.rs index 1e67b3d22b..c85b87f3ee 100644 --- a/crates/io/tests/pdn_corpus.rs +++ b/crates/io/tests/it/pdn_corpus.rs @@ -1,5 +1,5 @@ //! Local PDN oracles are not bundled. Set PDN_TEST_DIR to a directory containing PDNs and their -//! exported PNGs, then run `cargo test -p photocraft-io --test pdn_corpus -- --ignored --nocapture`. +//! exported PNGs, then run `cargo test -p photocraft-io --test it -- pdn_corpus:: --ignored --nocapture`. use std::path::{Path, PathBuf}; diff --git a/crates/io/tests/png_text_metadata.rs b/crates/io/tests/it/png_text_metadata.rs similarity index 100% rename from crates/io/tests/png_text_metadata.rs rename to crates/io/tests/it/png_text_metadata.rs diff --git a/crates/io/tests/psd16_merged_transparency.rs b/crates/io/tests/it/psd16_merged_transparency.rs similarity index 99% rename from crates/io/tests/psd16_merged_transparency.rs rename to crates/io/tests/it/psd16_merged_transparency.rs index 02d6c0e6b3..82b054e873 100644 --- a/crates/io/tests/psd16_merged_transparency.rs +++ b/crates/io/tests/it/psd16_merged_transparency.rs @@ -5,7 +5,7 @@ //! Photoshop's 16-bit PSB in the report has four channels, a positive layer count in `Lr16`, no //! `Mt16` block, and one alpha channel name, "Transparency". Re-saving it wrote five channels. -mod common; +use crate::common; use common::raster; use photocraft_color::{ColorMode, SampleType}; diff --git a/crates/io/tests/psd32_export.rs b/crates/io/tests/it/psd32_export.rs similarity index 99% rename from crates/io/tests/psd32_export.rs rename to crates/io/tests/it/psd32_export.rs index b4707fadb0..f9a297a7f6 100644 --- a/crates/io/tests/psd32_export.rs +++ b/crates/io/tests/it/psd32_export.rs @@ -6,7 +6,7 @@ //! resources, layer info in an `Lr32` global block with an empty classic layer info, channel //! compression codes valid for 32-bit data, and a raw big-endian float merged image. -mod common; +use crate::common; use common::Features; use photocraft_color::{ColorMode, SampleType}; diff --git a/crates/io/tests/psd_background.rs b/crates/io/tests/it/psd_background.rs similarity index 100% rename from crates/io/tests/psd_background.rs rename to crates/io/tests/it/psd_background.rs diff --git a/crates/io/tests/psd_block_alignment.rs b/crates/io/tests/it/psd_block_alignment.rs similarity index 100% rename from crates/io/tests/psd_block_alignment.rs rename to crates/io/tests/it/psd_block_alignment.rs diff --git a/crates/io/tests/psd_block_layout.rs b/crates/io/tests/it/psd_block_layout.rs similarity index 99% rename from crates/io/tests/psd_block_layout.rs rename to crates/io/tests/it/psd_block_layout.rs index bb858633b5..d081bfbc43 100644 --- a/crates/io/tests/psd_block_layout.rs +++ b/crates/io/tests/it/psd_block_layout.rs @@ -3,7 +3,7 @@ //! to even, a layer info body not padded to 4 and, in PSB, `cinf`/`lnkE` read and written //! with 4-byte lengths; psd-tools rejected or misaligned all of them. -mod common; +use crate::common; use photocraft_io::*; use photocraft_psd::descriptor::{Descriptor, VersionedDescriptor}; diff --git a/crates/io/tests/psd_damaged_merged.rs b/crates/io/tests/it/psd_damaged_merged.rs similarity index 100% rename from crates/io/tests/psd_damaged_merged.rs rename to crates/io/tests/it/psd_damaged_merged.rs diff --git a/crates/io/tests/psd_empty_channels.rs b/crates/io/tests/it/psd_empty_channels.rs similarity index 99% rename from crates/io/tests/psd_empty_channels.rs rename to crates/io/tests/it/psd_empty_channels.rs index 285f03cfcd..610bb145cc 100644 --- a/crates/io/tests/psd_empty_channels.rs +++ b/crates/io/tests/it/psd_empty_channels.rs @@ -1,4 +1,4 @@ -mod common; +use crate::common; use common::Features; use photocraft_color::{ColorMode, SampleType}; use photocraft_io::{ExportOptions, export}; diff --git a/crates/io/tests/psd_font_identity.rs b/crates/io/tests/it/psd_font_identity.rs similarity index 100% rename from crates/io/tests/psd_font_identity.rs rename to crates/io/tests/it/psd_font_identity.rs diff --git a/crates/io/tests/psd_kerning.rs b/crates/io/tests/it/psd_kerning.rs similarity index 100% rename from crates/io/tests/psd_kerning.rs rename to crates/io/tests/it/psd_kerning.rs diff --git a/crates/io/tests/psd_layer_block_length.rs b/crates/io/tests/it/psd_layer_block_length.rs similarity index 99% rename from crates/io/tests/psd_layer_block_length.rs rename to crates/io/tests/it/psd_layer_block_length.rs index acb4a6b15c..71f8e2552d 100644 --- a/crates/io/tests/psd_layer_block_length.rs +++ b/crates/io/tests/it/psd_layer_block_length.rs @@ -4,7 +4,7 @@ //! Photoshop writes these blocks this way. Readers that check the block length exactly (Unity's //! PSD Importer, "Incorrect length for InfoLayers") reject a block whose length counts the padding. -mod common; +use crate::common; use common::Features; use photocraft_color::{ColorMode, SampleType}; diff --git a/crates/io/tests/psd_maximize_compatibility.rs b/crates/io/tests/it/psd_maximize_compatibility.rs similarity index 100% rename from crates/io/tests/psd_maximize_compatibility.rs rename to crates/io/tests/it/psd_maximize_compatibility.rs diff --git a/crates/io/tests/psd_noise_fill_roundtrip.rs b/crates/io/tests/it/psd_noise_fill_roundtrip.rs similarity index 100% rename from crates/io/tests/psd_noise_fill_roundtrip.rs rename to crates/io/tests/it/psd_noise_fill_roundtrip.rs diff --git a/crates/io/tests/psd_roundtrip_bytes.rs b/crates/io/tests/it/psd_roundtrip_bytes.rs similarity index 100% rename from crates/io/tests/psd_roundtrip_bytes.rs rename to crates/io/tests/it/psd_roundtrip_bytes.rs diff --git a/crates/io/tests/psd_structure.rs b/crates/io/tests/it/psd_structure.rs similarity index 100% rename from crates/io/tests/psd_structure.rs rename to crates/io/tests/it/psd_structure.rs diff --git a/crates/io/tests/psd_style_sheets.rs b/crates/io/tests/it/psd_style_sheets.rs similarity index 100% rename from crates/io/tests/psd_style_sheets.rs rename to crates/io/tests/it/psd_style_sheets.rs diff --git a/crates/io/tests/psd_thumbnail.rs b/crates/io/tests/it/psd_thumbnail.rs similarity index 100% rename from crates/io/tests/psd_thumbnail.rs rename to crates/io/tests/it/psd_thumbnail.rs diff --git a/crates/io/tests/psd_type_bounds.rs b/crates/io/tests/it/psd_type_bounds.rs similarity index 99% rename from crates/io/tests/psd_type_bounds.rs rename to crates/io/tests/it/psd_type_bounds.rs index a80bc9b7ab..b87d4f4a3a 100644 --- a/crates/io/tests/psd_type_bounds.rs +++ b/crates/io/tests/it/psd_type_bounds.rs @@ -10,7 +10,7 @@ //! //! Fonts: the bundled Inter (deterministic), so our render is the "Photoshop" render here. -mod common; +use crate::common; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::text::TextShape; diff --git a/crates/io/tests/psd_type_photoshop_bytes.rs b/crates/io/tests/it/psd_type_photoshop_bytes.rs similarity index 100% rename from crates/io/tests/psd_type_photoshop_bytes.rs rename to crates/io/tests/it/psd_type_photoshop_bytes.rs diff --git a/crates/io/tests/psd_unknown_adjustment.rs b/crates/io/tests/it/psd_unknown_adjustment.rs similarity index 100% rename from crates/io/tests/psd_unknown_adjustment.rs rename to crates/io/tests/it/psd_unknown_adjustment.rs diff --git a/crates/io/tests/psd_vertical_type.rs b/crates/io/tests/it/psd_vertical_type.rs similarity index 100% rename from crates/io/tests/psd_vertical_type.rs rename to crates/io/tests/it/psd_vertical_type.rs diff --git a/crates/io/tests/raw.rs b/crates/io/tests/it/raw.rs similarity index 100% rename from crates/io/tests/raw.rs rename to crates/io/tests/it/raw.rs diff --git a/crates/io/tests/resolution_axes.rs b/crates/io/tests/it/resolution_axes.rs similarity index 99% rename from crates/io/tests/resolution_axes.rs rename to crates/io/tests/it/resolution_axes.rs index f7f8cbf006..fb2bd209e2 100644 --- a/crates/io/tests/resolution_axes.rs +++ b/crates/io/tests/it/resolution_axes.rs @@ -1,7 +1,7 @@ //! A file whose horizontal and vertical resolutions differ opens at the horizontal one, and the //! import says the vertical one is not kept (#1018). Equal axes, the common case, open silently. -mod common; +use crate::common; use common::*; use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, Metadata, SampleType as CSample}; diff --git a/crates/io/tests/roundtrip.rs b/crates/io/tests/it/roundtrip.rs similarity index 99% rename from crates/io/tests/roundtrip.rs rename to crates/io/tests/it/roundtrip.rs index dcb7bce62a..1031b5504a 100644 --- a/crates/io/tests/roundtrip.rs +++ b/crates/io/tests/it/roundtrip.rs @@ -1,6 +1,6 @@ //! Document → PSD → Document round trips. -mod common; +use crate::common; use common::*; use photocraft_color::{ColorMode, SampleType}; diff --git a/crates/io/tests/smart_contents_identity.rs b/crates/io/tests/it/smart_contents_identity.rs similarity index 100% rename from crates/io/tests/smart_contents_identity.rs rename to crates/io/tests/it/smart_contents_identity.rs diff --git a/crates/io/tests/smart_corpus.rs b/crates/io/tests/it/smart_corpus.rs similarity index 99% rename from crates/io/tests/smart_corpus.rs rename to crates/io/tests/it/smart_corpus.rs index 494a43071c..f258c01103 100644 --- a/crates/io/tests/smart_corpus.rs +++ b/crates/io/tests/it/smart_corpus.rs @@ -10,7 +10,7 @@ //! ones dropped). #![cfg(feature = "corpus")] -mod common; +use crate::common; use std::path::{Path, PathBuf}; use std::sync::Arc; diff --git a/crates/io/tests/svg.rs b/crates/io/tests/it/svg.rs similarity index 81% rename from crates/io/tests/svg.rs rename to crates/io/tests/it/svg.rs index d1baf418fa..c71bb0ae4f 100644 --- a/crates/io/tests/svg.rs +++ b/crates/io/tests/it/svg.rs @@ -190,6 +190,31 @@ fn png_data_url() -> String { out } +/// A small valid PNG whose IHDR claims `w`x`h`, far larger than its actual (tiny) image data. +/// The header alone must be enough to reject it before any decode is attempted. +fn png_data_url_with_claimed_size(w: u32, h: u32) -> String { + let img = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255]).unwrap(); + let mut bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + // IHDR starts right after the 8-byte signature and 8-byte chunk length/type: width at 16, + // height at 20 (big-endian u32 each). + bytes[16..20].copy_from_slice(&w.to_be_bytes()); + bytes[20..24].copy_from_slice(&h.to_be_bytes()); + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::from("data:image/png;base64,"); + for chunk in bytes.chunks(3) { + let n = chunk.len(); + let v = (u32::from(chunk[0]) << 16) | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) | u32::from(*chunk.get(2).unwrap_or(&0)); + for i in 0..4 { + if i <= n { + out.push(T[((v >> (18 - 6 * i)) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + #[test] fn embedded_raster_images_become_pixel_layers() { let r = open(&format!( @@ -204,6 +229,18 @@ fn embedded_raster_images_become_pixel_layers() { assert!(close(px(d, 16, 16), [1.0, 1.0, 1.0, 1.0]), "{:?}", px(d, 16, 16)); } +#[test] +fn embedded_png_with_a_huge_claimed_size_is_not_decoded() { + // The IHDR claims 40000x40000 (6.4 GB RGBA decoded) but the display size is tiny; the + // header-only check must reject it before resvg ever decodes the actual (2x2) image data. + let r = open(&format!( + "", + png_data_url_with_claimed_size(40_000, 40_000) + )); + // Rejected at the resolver: no image layer is produced (resvg treats it as a missing image). + assert!(r.document.layers.is_empty() || !matches!(r.document.layers[0].content, LayerContent::Raster(_)), "{:?}", r.document.layers); +} + #[test] fn text_becomes_outline_shapes_or_warns_without_a_font() { let r = open(&format!( @@ -245,6 +282,52 @@ fn gzip(bytes: &[u8]) -> Vec { e.finish().unwrap() } +/// A `data:` URL of `bytes` under `mime`, base64-encoded. +fn base64_data_url(mime: &str, bytes: &[u8]) -> String { + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = format!("data:{mime};base64,"); + for chunk in bytes.chunks(3) { + let n = chunk.len(); + let v = (u32::from(chunk[0]) << 16) | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) | u32::from(*chunk.get(2).unwrap_or(&0)); + for i in 0..4 { + if i <= n { + out.push(T[((v >> (18 - 6 * i)) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + +#[test] +fn gzip_compressed_embedded_svg_decompresses_once_with_a_size_cap() { + // A small gzip-compressed SVG embedded via data URL (SVGZ-in-data-URL) must still import. + let inner = format!(""); + let url = base64_data_url("image/svg+xml", &gzip(inner.as_bytes())); + let r = open(&format!("")); + assert!( + r.document.layers.iter().any(|l| matches!(l.content, LayerContent::Raster(_))), + "valid embedded gzip SVG must decode into a raster layer: {:?}", + r.document.layers + ); + + // A gzip-compressed embedded SVG whose decompressed size exceeds the cap must be rejected + // by our bounded inflate, not silently decompressed again without a limit by usvg. + let mut bomb = format!("").into_bytes(); + bomb.resize(usize::try_from(svg::MAX_INFLATED_BYTES).unwrap() + 1024, b' '); + bomb.extend_from_slice(b""); + let gz = gzip(&bomb); + assert!(gz.len() < 2 << 20, "{} bytes compressed", gz.len()); + let url = base64_data_url("image/svg+xml", &gz); + let start = std::time::Instant::now(); + let r = open(&format!("")); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "took {:?}", start.elapsed()); + // The embedded bomb is rejected; the outer drawing may still open (e.g. with a missing + // image), but must not have decoded the bomb into a raster layer. + assert!(r.document.layers.iter().all(|l| !matches!(l.content, LayerContent::Raster(_))), "{:?}", r.document.layers); +} + /// 8 000 nested groups (70 KB) overflowed the XML parser's recursion on a 2 MB thread stack, an /// abort nothing can catch. It is an error now, found before the parser runs; the thread here /// has a small stack so a regression aborts the test instead of passing by luck. diff --git a/crates/io/tests/text_corpus.rs b/crates/io/tests/it/text_corpus.rs similarity index 100% rename from crates/io/tests/text_corpus.rs rename to crates/io/tests/it/text_corpus.rs diff --git a/crates/io/tests/text_styles.rs b/crates/io/tests/it/text_styles.rs similarity index 100% rename from crates/io/tests/text_styles.rs rename to crates/io/tests/it/text_styles.rs diff --git a/crates/io/tests/tiff_corpus.rs b/crates/io/tests/it/tiff_corpus.rs similarity index 100% rename from crates/io/tests/tiff_corpus.rs rename to crates/io/tests/it/tiff_corpus.rs diff --git a/crates/io/tests/tiff_layers.rs b/crates/io/tests/it/tiff_layers.rs similarity index 99% rename from crates/io/tests/tiff_layers.rs rename to crates/io/tests/it/tiff_layers.rs index 56e51bf9f9..382f45bc44 100644 --- a/crates/io/tests/tiff_layers.rs +++ b/crates/io/tests/it/tiff_layers.rs @@ -2,7 +2,7 @@ //! trips in every mode and depth, equivalence with the PSD path, the flat fall-backs, files //! written by an independent implementation (psdtags, both byte orders), and malformed input. -mod common; +use crate::common; use common::*; use photocraft_color::{ColorMode, SampleType}; diff --git a/crates/io/tests/tiff_pages.rs b/crates/io/tests/it/tiff_pages.rs similarity index 100% rename from crates/io/tests/tiff_pages.rs rename to crates/io/tests/it/tiff_pages.rs diff --git a/crates/io/tests/tiff_type_geometry.rs b/crates/io/tests/it/tiff_type_geometry.rs similarity index 100% rename from crates/io/tests/tiff_type_geometry.rs rename to crates/io/tests/it/tiff_type_geometry.rs diff --git a/crates/io/tests/vector.rs b/crates/io/tests/it/vector.rs similarity index 100% rename from crates/io/tests/vector.rs rename to crates/io/tests/it/vector.rs diff --git a/crates/io/tests/xcf.rs b/crates/io/tests/it/xcf.rs similarity index 100% rename from crates/io/tests/xcf.rs rename to crates/io/tests/it/xcf.rs diff --git a/crates/io/tests/xmp_export.rs b/crates/io/tests/it/xmp_export.rs similarity index 100% rename from crates/io/tests/xmp_export.rs rename to crates/io/tests/it/xmp_export.rs diff --git a/crates/psd/README.md b/crates/psd/README.md index b26a33dff6..421d706ab7 100644 --- a/crates/psd/README.md +++ b/crates/psd/README.md @@ -145,7 +145,7 @@ allocations for padded channels return an error on failure. * Builder → `rgba8` correctness. * Unknown blend modes and unknown blocks pass through unchanged. -`tests/corpus.rs` walks `corpus/psd/**/*.{psd,psb}` at the workspace root when that directory exists. For each file it asserts that parsing succeeds and the file round-trips byte for byte, and it prints a result per file. Without the directory it skips silently. +`tests/it/corpus.rs` walks `corpus/psd/**/*.{psd,psb}` at the workspace root when that directory exists. For each file it asserts that parsing succeeds and the file round-trips byte for byte, and it prints a result per file. Without the directory it skips silently. A `cargo-fuzz` skeleton lives in `fuzz/`. It is its own workspace and is excluded from photocraft's. Run it with `cargo +nightly fuzz run parse` (or `descriptor`) from `crates/psd`. diff --git a/crates/psd/fuzz/fuzz_targets/grd.rs b/crates/psd/fuzz/fuzz_targets/grd.rs index 2779a96846..16ab26a137 100644 --- a/crates/psd/fuzz/fuzz_targets/grd.rs +++ b/crates/psd/fuzz/fuzz_targets/grd.rs @@ -3,7 +3,7 @@ //! //! The cap assertions below are invariants, not fast checks: at libFuzzer default `-max_len` //! of 4096 no input can carry 10 001 gradients or 1001 stops, so they only fire on long runs with -//! a raised limit. The inputs that do reach those caps are in `crates/psd/tests/swatch_malformed.rs`. +//! a raised limit. The inputs that do reach those caps are in `crates/psd/tests/it/swatch_malformed.rs`. #![no_main] use libfuzzer_sys::fuzz_target; use photocraft_psd::grd::{self, GrdColor}; diff --git a/crates/psd/src/slices.rs b/crates/psd/src/slices.rs index 54bf4c8fcd..5d9cd50b39 100644 --- a/crates/psd/src/slices.rs +++ b/crates/psd/src/slices.rs @@ -10,6 +10,8 @@ //! version reads. Unknown fields are not kept here; callers that need a byte-exact round trip //! keep the raw resource while the slices are unchanged. +use std::collections::HashMap; + use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; use crate::error::{PsdError, Result}; use crate::io::{Reader, WriteExt}; @@ -274,13 +276,22 @@ impl SlicesResource { && let Ok(vd) = VersionedDescriptor::read(r) && let Some(Value::List(items)) = vd.descriptor.get("slices") { + // Index each slice ID to its first occurrence once, so matching trailing + // descriptors against slices is linear rather than quadratic. Both the slice + // count and the descriptor-ID list are file-controlled, so a plain + // `find()` per descriptor is O(n*m) and lets a crafted resource burn CPU. + // `or_insert` preserves the original first-match behavior for duplicate IDs. + let mut id_to_index: HashMap = HashMap::with_capacity(slices.len()); + for (i, s) in slices.iter().enumerate() { + id_to_index.entry(s.id).or_insert(i); + } for v in items { let Value::Descriptor(d) = v else { continue }; // An entry without a usable id belongs to no slice (not to slice 0). let Some(id) = d_u32(d, "sliceID") else { continue }; let extra = slice_from_descriptor(d); - if let Some(s) = slices.iter_mut().find(|s| s.id == id) { - s.outsets = extra.outsets; + if let Some(&i) = id_to_index.get(&id) { + slices[i].outsets = extra.outsets; } } } @@ -493,4 +504,28 @@ mod tests { assert!(SlicesResource::from_bytes(&huge).is_err()); assert!(SlicesResource::from_bytes(&9u32.to_be_bytes()).is_err()); } + + #[test] + fn trailing_descriptor_applies_outsets_to_first_matching_slice() { + // Two slices share id 1; the trailing descriptor must update the first one only, + // matching the pre-index behavior of `iter_mut().find()`. + let mut plain = SlicesResource { + version: 6, + bounds: [0, 0, 80, 100], + group_name: "site".into(), + slices: vec![ + SliceRecord { id: 1, origin: 0, kind: 1, rect: [0, 0, 10, 10], ..Default::default() }, + SliceRecord { id: 1, origin: 0, kind: 1, rect: [10, 10, 20, 20], ..Default::default() }, + ], + }; + for s in &mut plain.slices { + s.outsets = [0; 4]; + } + let mut bytes = plain.to_bytes(); + let extra = Descriptor::new("slice").with("sliceID", Value::Integer(1)).with("topOutset", Value::Integer(7)); + VersionedDescriptor::new(Descriptor::new("null").with("slices", Value::List(vec![Value::Descriptor(extra)]))).write(&mut bytes); + let back = SlicesResource::from_bytes(&bytes).unwrap(); + assert_eq!(back.slices[0].outsets, [7, 0, 0, 0], "first slice receives the outset"); + assert_eq!(back.slices[1].outsets, [0, 0, 0, 0], "later duplicate is untouched"); + } } diff --git a/crates/psd/tests/builder.rs b/crates/psd/tests/it/builder.rs similarity index 100% rename from crates/psd/tests/builder.rs rename to crates/psd/tests/it/builder.rs diff --git a/crates/psd/tests/corpus.rs b/crates/psd/tests/it/corpus.rs similarity index 100% rename from crates/psd/tests/corpus.rs rename to crates/psd/tests/it/corpus.rs diff --git a/crates/psd/tests/corpus_atn.rs b/crates/psd/tests/it/corpus_atn.rs similarity index 100% rename from crates/psd/tests/corpus_atn.rs rename to crates/psd/tests/it/corpus_atn.rs diff --git a/crates/psd/tests/layer_block_order.rs b/crates/psd/tests/it/layer_block_order.rs similarity index 100% rename from crates/psd/tests/layer_block_order.rs rename to crates/psd/tests/it/layer_block_order.rs diff --git a/crates/psd/tests/it/main.rs b/crates/psd/tests/it/main.rs new file mode 100644 index 0000000000..ee6879aa66 --- /dev/null +++ b/crates/psd/tests/it/main.rs @@ -0,0 +1,12 @@ +//! The crate's integration tests, linked into one test binary. + +mod builder; +mod corpus; +mod corpus_atn; +mod layer_block_order; +mod malformed; +mod merged_recovery; +mod proptests; +mod roundtrip; +mod swatch_malformed; +mod tree; diff --git a/crates/psd/tests/malformed.rs b/crates/psd/tests/it/malformed.rs similarity index 100% rename from crates/psd/tests/malformed.rs rename to crates/psd/tests/it/malformed.rs diff --git a/crates/psd/tests/merged_recovery.rs b/crates/psd/tests/it/merged_recovery.rs similarity index 100% rename from crates/psd/tests/merged_recovery.rs rename to crates/psd/tests/it/merged_recovery.rs diff --git a/crates/psd/tests/proptests.rs b/crates/psd/tests/it/proptests.rs similarity index 100% rename from crates/psd/tests/proptests.rs rename to crates/psd/tests/it/proptests.rs diff --git a/crates/psd/tests/roundtrip.rs b/crates/psd/tests/it/roundtrip.rs similarity index 100% rename from crates/psd/tests/roundtrip.rs rename to crates/psd/tests/it/roundtrip.rs diff --git a/crates/psd/tests/swatch_malformed.rs b/crates/psd/tests/it/swatch_malformed.rs similarity index 100% rename from crates/psd/tests/swatch_malformed.rs rename to crates/psd/tests/it/swatch_malformed.rs diff --git a/crates/psd/tests/tree.rs b/crates/psd/tests/it/tree.rs similarity index 100% rename from crates/psd/tests/tree.rs rename to crates/psd/tests/it/tree.rs diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index f0d9b63b78..49806e521c 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -476,30 +476,37 @@ impl Surface { /// Channel `c` at `(x0 + i·step, y)` for `i in 0..out.len()`, looking each tile up once per run /// (much faster than per-sample [`Surface::sample_channel`] for strided scans). + /// Steps below 1 read consecutive pixels; positions beyond `i32::MAX` read the default pixel. pub fn sample_row_strided(&self, y: i32, x0: i32, step: i32, c: usize, out: &mut [f32]) { - let step = step.max(1); + let step = i64::from(step.max(1)); let dp = read_sample(&self.default_pixel, self.format.sample, c); let n = self.format.channels(); let ty = y.div_euclid(TILE_SIZE); let ly = y.rem_euclid(TILE_SIZE) as usize; let mut i = 0; + let mut x = i64::from(x0); while i < out.len() { - let x = x0 + i as i32 * step; - let tx = x.div_euclid(TILE_SIZE); + if x > i64::from(i32::MAX) { + out[i..].fill(dp); + break; + } + let tx = x.div_euclid(i64::from(TILE_SIZE)); // Samples that fall in this tile. - let tile_end = (tx + 1) * TILE_SIZE; + let tile_end = (tx + 1) * i64::from(TILE_SIZE); let count = (((tile_end - x) + step - 1) / step).max(1) as usize; - let end = (i + count).min(out.len()); - match self.tiles.get(&TileCoord { tx, ty }) { + let count = count.min(out.len() - i); + let end = i + count; + match self.tiles.get(&TileCoord { tx: tx as i32, ty }) { None => out[i..end].fill(dp), Some(t) => { for (k, o) in out[i..end].iter_mut().enumerate() { - let lx = (x + k as i32 * step - tx * TILE_SIZE) as usize; + let lx = (x + k as i64 * step - tx * i64::from(TILE_SIZE)) as usize; *o = read_sample(&t.data, self.format.sample, (ly * TILE_SIZE as usize + lx) * n + c); } } } i = end; + x += count as i64 * step; } } @@ -1894,6 +1901,40 @@ mod tests { } } + #[test] + fn strided_row_sampling_handles_extreme_coordinates_and_steps() { + for sample in SampleType::ALL { + let mut s = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, sample, false), &[0.25]); + for (x, value) in [(i32::MIN, 0.1), (-1, 0.3), (0, 0.4), (i32::MAX - 1, 0.6), (i32::MAX, 0.9)] { + s.write_pixel(x, 0, &[value]); + } + for y in [0, 256] { + for (x0, step, len) in [(i32::MAX, 1, 1), (i32::MIN, i32::MAX, 3), (0, i32::MAX, 2), (i32::MAX - 1, 1, 2), (i32::MAX, i32::MAX, 0)] { + let mut out = vec![0.0; len]; + s.sample_row_strided(y, x0, step, 0, &mut out); + for (i, &got) in out.iter().enumerate() { + let x = i32::try_from(i64::from(x0) + i as i64 * i64::from(step)).unwrap(); + assert_eq!(got, s.sample_channel(x, y, 0), "{sample:?} y={y} x0={x0} step={step} i={i}"); + } + } + } + } + } + + #[test] + fn strided_row_sampling_uses_default_past_coordinate_range() { + for sample in SampleType::ALL { + let mut s = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, sample, false), &[0.25]); + s.write_pixel(i32::MAX, 0, &[0.75]); + s.write_pixel(i32::MIN, 0, &[1.0]); + for step in [1, i32::MAX] { + let mut out = [0.0; 4]; + s.sample_row_strided(0, i32::MAX, step, 0, &mut out); + assert_eq!(out, [s.sample_channel(i32::MAX, 0, 0), s.default_pixel()[0], s.default_pixel()[0], s.default_pixel()[0]]); + } + } + } + #[test] fn strided_row_sampling_matches_sample_channel() { let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]); diff --git a/crates/raw/examples/inspect.rs b/crates/raw/examples/inspect.rs index ca7b136a90..4dd6e5709a 100644 --- a/crates/raw/examples/inspect.rs +++ b/crates/raw/examples/inspect.rs @@ -1,5 +1,5 @@ //! Prints the raw metadata of files: `cargo run -p photocraft-raw --example inspect -- a.cr2 b.nef` -//! (handy while adding corpus files; the oracle expectations in `tests/raw_corpus.rs` come from it). +//! (handy while adding corpus files; the oracle expectations in `tests/it/raw_corpus.rs` come from it). use std::env; fn main() { diff --git a/crates/raw/tests/cr3.rs b/crates/raw/tests/it/cr3.rs similarity index 100% rename from crates/raw/tests/cr3.rs rename to crates/raw/tests/it/cr3.rs diff --git a/crates/raw/tests/development_limits.rs b/crates/raw/tests/it/development_limits.rs similarity index 100% rename from crates/raw/tests/development_limits.rs rename to crates/raw/tests/it/development_limits.rs diff --git a/crates/raw/tests/dng.rs b/crates/raw/tests/it/dng.rs similarity index 100% rename from crates/raw/tests/dng.rs rename to crates/raw/tests/it/dng.rs diff --git a/crates/raw/tests/hostile.rs b/crates/raw/tests/it/hostile.rs similarity index 100% rename from crates/raw/tests/hostile.rs rename to crates/raw/tests/it/hostile.rs diff --git a/crates/raw/tests/it/main.rs b/crates/raw/tests/it/main.rs new file mode 100644 index 0000000000..27a1af788b --- /dev/null +++ b/crates/raw/tests/it/main.rs @@ -0,0 +1,12 @@ +//! The crate's integration tests, linked into one test binary. + +mod cr3; +mod development_limits; +mod dng; +mod hostile; +mod nef_packed; +mod nikon_d4_depth; +mod raf; +mod raw_corpus; +mod vendor_codecs; +mod vendors; diff --git a/crates/raw/tests/nef_packed.rs b/crates/raw/tests/it/nef_packed.rs similarity index 100% rename from crates/raw/tests/nef_packed.rs rename to crates/raw/tests/it/nef_packed.rs diff --git a/crates/raw/tests/nikon_d4_depth.rs b/crates/raw/tests/it/nikon_d4_depth.rs similarity index 100% rename from crates/raw/tests/nikon_d4_depth.rs rename to crates/raw/tests/it/nikon_d4_depth.rs diff --git a/crates/raw/tests/raf.rs b/crates/raw/tests/it/raf.rs similarity index 100% rename from crates/raw/tests/raf.rs rename to crates/raw/tests/it/raf.rs diff --git a/crates/raw/tests/raw_corpus.rs b/crates/raw/tests/it/raw_corpus.rs similarity index 100% rename from crates/raw/tests/raw_corpus.rs rename to crates/raw/tests/it/raw_corpus.rs diff --git a/crates/raw/tests/vendor_codecs.rs b/crates/raw/tests/it/vendor_codecs.rs similarity index 100% rename from crates/raw/tests/vendor_codecs.rs rename to crates/raw/tests/it/vendor_codecs.rs diff --git a/crates/raw/tests/vendors.rs b/crates/raw/tests/it/vendors.rs similarity index 100% rename from crates/raw/tests/vendors.rs rename to crates/raw/tests/it/vendors.rs diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rs index 3e946b0d72..b6925867d4 100644 --- a/crates/ui-egui/src/actions.rs +++ b/crates/ui-egui/src/actions.rs @@ -98,7 +98,7 @@ pub(crate) fn play(app: &mut PhotocraftApp, params: &Value) -> Result) -> Result { let (action, from) = match actions_cmds::playback_plan(&app.session, params) { @@ -129,41 +129,46 @@ fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option) failed = Some(json!({"step": i, "id": id, "error": format!("action playback exceeded the {}-step limit", actions_cmds::MAX_PLAYBACK_STEPS)})); break; } + // The gate judges the step before its dialog opens: a denied step neither runs nor + // pauses. + if let Some(auth) = app.session.authorize + && let Err(e) = auth(id, p) + { + failed = Some(json!({"step": i, "id": id, "error": e.to_string()})); + break; + } // The dialog toggle: show the step's dialog with its recorded values and continue // from the next step when it is confirmed (`resume`). Agents play headlessly. if action.dialogs.contains(&i) && !app.automation_input && (crate::filter_dialog::has_dialog(id) || crate::adjust_dialog::has_dialog(id)) { let label = label_of(id); let dialog = crate::dialogs::open_command_dialog(app, id, &label); + let token = app.paused_playbacks.pause(action.name.clone(), i + 1, app.session.authorize); if let Some(d) = app.ui.dialog_mut(dialog) { if let Some(o) = p.as_object() { - d.fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); + // `__` keys are the dialog's own markers (`params_of` drops them), not step values. + d.fields.extend(o.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone()))); } - d.fields.insert(RESUME.into(), json!({"action": action.name, "from": i + 1})); + d.fields.insert(RESUME.into(), json!(token)); } paused = Some(json!({"step": i, "id": id, "dialog": dialog})); break; } let target = app.session.active().map(|d| d.doc.id); - let result = (|| { - if let Some(auth) = app.session.authorize { - auth(id, p).map_err(|e| e.to_string())?; - } - if id == "actions.play" { - play(app, p) - } else if actions_cmds::shell_save_command(id) { - // Write synchronously, so the next step doesn't meet a document locked by a - // background save. - let background = std::mem::replace(&mut app.background_jobs, false); - let r = app.replay_save(id, p); - app.background_jobs = background; - r - } else if actions_cmds::shell_view_command(id) { - app.sync_views(); - app.run(id, p.clone()) - } else { - app.session.execute(id, p.clone()).map_err(|e| e.to_string()) - } - })(); + let result = if id == "actions.play" { + play(app, p) + } else if actions_cmds::shell_save_command(id) { + // Write synchronously, so the next step doesn't meet a document locked by a + // background save. + let background = std::mem::replace(&mut app.background_jobs, false); + let r = app.replay_save(id, p); + app.background_jobs = background; + r + } else if actions_cmds::shell_view_command(id) { + app.sync_views(); + app.run(id, p.clone()) + } else { + app.session.execute(id, p.clone()).map_err(|e| e.to_string()) + }; match result { Ok(value) => { if let Some(error) = actions_cmds::nested_failure(id, &value).or_else(|| actions_cmds::save_target_closed(&app.session, id, target)) { @@ -186,13 +191,14 @@ fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option) actions_cmds::finish_playback(&mut app.session, None, &action, from); match paused.as_ref().and_then(|p| p.get("dialog")).and_then(Value::as_u64).and_then(|d| app.ui.dialog_mut(d)) { // Paused for a dialog: the call goes on after it, so recording stays suspended. - Some(d) if failed.is_none() => match (owner, d.fields.get_mut(RESUME)) { - (Some(owner), Some(Value::Object(r))) => { - r.insert(RECORD.into(), owner); + Some(d) if failed.is_none() => { + let entry = d.fields.get(RESUME).and_then(Value::as_u64).and_then(|t| app.paused_playbacks.paused.get_mut(&t)); + match (owner, entry) { + (Some(owner), Some(p)) => p.record = Some(owner), + // No continuation to carry the recording: the call ends here. + (owner, _) => restore_recording(app, owner.as_ref()), } - // No continuation to carry the recording: the call ends here. - (owner, _) => restore_recording(app, owner.as_ref()), - }, + } _ => restore_recording(app, owner.as_ref()), } Ok(match (failed, paused) { @@ -478,16 +484,9 @@ pub fn insert_stop_confirm(app: &mut PhotocraftApp, fields: &serde_json::Map) { let Some(owner) = owner else { return }; @@ -511,9 +510,9 @@ fn restore_recording(app: &mut PhotocraftApp, owner: Option<&Value>) { } } -/// Whether a step dialog holds a suspended recording. +/// Whether a paused playback holds a suspended recording. fn suspended(app: &PhotocraftApp) -> bool { - app.ui.dialogs.iter().any(|d| d.fields.get(RESUME).and_then(|r| r.get(RECORD)).is_some()) + app.paused_playbacks.paused.values().any(|p| p.record.is_some()) } /// While a step dialog holds a suspended recording, refuse what would lose its call: a new @@ -529,13 +528,58 @@ pub(crate) fn suspended_guard(app: &PhotocraftApp, id: &str) -> Result<(), Strin /// A step dialog's command failed: the action ends there. pub fn abandoned(app: &mut PhotocraftApp, fields: &serde_json::Map) { - restore_recording(app, fields.get(RESUME).and_then(|r| r.get(RECORD))); + let record = fields.get(RESUME).and_then(|t| app.paused_playbacks.take(t)).and_then(|p| p.record); + restore_recording(app, record.as_ref()); +} + +/// The automation gate a session installs ([`photocraft_engine::Session::authorize`]). +type Gate = fn(&str, &Value) -> photocraft_engine::Result<()>; + +/// A playback paused at a step dialog: the action and step it continues from, and the gate it +/// was playing under (`None` for one a person started). +#[derive(Clone, Debug)] +pub(crate) struct PausedPlayback { + action: String, + from: usize, + gate: Option, + /// The recording the paused call suspended: `{index, into, action, from}` (`into` is the + /// name of the action being recorded). A step dialog only closes through + /// `dialogs::confirm` (OK, `↩`, automation) or `dialogs::cancel` (Cancel, Esc, the close + /// box, automation), which end the call through `resume`, `abandoned` or `stopped`, so the + /// recording comes back exactly once. + record: Option, +} + +/// The paused playbacks, by the token their dialog carries. The dialog's fields hold only the +/// token; what plays next, and under which gate, is kept here. +#[derive(Debug, Default)] +pub(crate) struct PausedPlaybacks { + last: u64, + paused: std::collections::HashMap, +} + +impl PausedPlaybacks { + fn pause(&mut self, action: String, from: usize, gate: Option) -> u64 { + self.last = self.last.wrapping_add(1); + self.paused.insert(self.last, PausedPlayback { action, from, gate, record: None }); + self.last + } + + fn take(&mut self, token: &Value) -> Option { + token.as_u64().and_then(|token| self.paused.remove(&token)) + } } /// A step dialog confirmed: continue the action after it (`dialogs::confirm` calls this). +/// +/// The remaining steps run under the gate the playback paused with, however the dialog was +/// confirmed: a control request, synthetic Enter or OK, or a click. pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map) -> Result<(), String> { - let Some(r) = fields.get(RESUME) else { return Ok(()) }; - let owner = r.get(RECORD).cloned(); + let Some(token) = fields.get(RESUME) else { return Ok(()) }; + let Some(paused) = app.paused_playbacks.take(token) else { + return Err("this dialog doesn't belong to a paused action".into()); + }; + let owner = paused.record.clone(); // The dialog's command may run as a background job; the next step needs its result. if let Some(doc) = app.session.active().map(|d| d.doc.id) && let Some(job) = app.session.job_on(doc) @@ -547,8 +591,12 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map) app.ui.status_error = true; return Err(e.to_string()); } - let params = json!({"action": r.get("action").cloned().unwrap_or(Value::Null), "from": r.get("from").cloned().unwrap_or(Value::Null)}); - match play_owned(app, ¶ms, owner) { + let params = json!({"action": paused.action, "from": paused.from}); + let saved = app.session.authorize; + app.session.authorize = paused.gate.or(saved); + let played = play_owned(app, ¶ms, owner); + app.session.authorize = saved; + match played { Ok(v) => { report_play(app, &v); Ok(()) @@ -1821,7 +1869,7 @@ mod tests { let id = v["paused"]["dialog"].as_u64().unwrap(); let d = app.ui.dialog_mut(id).unwrap(); assert_eq!(d.fields["radius"], 3, "the dialog opens on the recorded values"); - assert_eq!(d.fields[RESUME], json!({"action": "Blur", "from": 2})); + assert!(d.fields[RESUME].is_u64(), "the dialog carries only the pause's token: {}", d.fields[RESUME]); assert!(app.session.active().unwrap().doc.selection.is_none(), "nothing after the dialog ran yet"); report_play(&mut app, &v); assert!(app.ui.status.contains("dialog"), "{}", app.ui.status); @@ -1939,6 +1987,18 @@ mod tests { assert_eq!(app.session.actions.list[1].steps, child_call()); } + #[test] + fn an_abandoned_step_dialog_leaves_no_paused_playback() { + let mut app = recording_with_dialog_child(); + let id = pause_child(&mut app); + app.ui.dialog_mut(id).unwrap().fields.insert("radius".into(), json!("not a radius")); + assert!(crate::dialogs::confirm(&mut app, id).is_err(), "the dialog command fails"); + assert!(app.paused_playbacks.paused.is_empty(), "the failed dialog ends its pause"); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list[1].steps, child_call(), "the call is recorded once"); + app.run("actions.record", json!({"name": "Next"})).unwrap(); + } + #[test] fn a_failing_resumed_playback_ends_the_recorded_call_once() { let mut app = recording_with_dialog_child(); @@ -1982,6 +2042,178 @@ mod tests { assert_eq!(app.session.actions.list[1].steps, child_call()); } + #[test] + fn a_step_dialog_keeps_its_continuation_token() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for (name, steps) in [ + ("First", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1}))]), + ("Second", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1})), ("select.all".into(), json!({}))]), + ] { + let mut action = Action::new(name, steps); + action.dialogs.insert(0); + app.session.actions.list.push(action); + } + let first = play(&mut app, &json!({"action": "First"})).unwrap()["paused"]["dialog"].as_u64().unwrap(); + let second = play(&mut app, &json!({"action": "Second"})).unwrap()["paused"]["dialog"].as_u64().unwrap(); + let first_token = app.ui.dialog_mut(first).unwrap().fields[RESUME].clone(); + let second_token = app.ui.dialog_mut(second).unwrap().fields[RESUME].clone(); + for token in [second_token.clone(), Value::Null, json!("invalid"), json!({"action": "Second", "from": 1})] { + let (request, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"dialog": first, "field": RESUME, "value": token})); + let response = crate::control::handle(&mut app, &egui::Context::default(), &request); + assert!(matches!(response, crate::control::Outcome::Done(ref v) if v["error"].as_str().is_some_and(|e| e.contains("read-only")))); + assert_eq!(app.ui.dialog_mut(first).unwrap().fields[RESUME], first_token); + assert_eq!(app.ui.dialog_mut(second).unwrap().fields[RESUME], second_token); + assert_eq!(app.paused_playbacks.paused.len(), 2); + } + crate::dialogs::confirm(&mut app, first).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_none(), "First must not run Second's remaining step"); + crate::dialogs::confirm(&mut app, second).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_some()); + assert!(app.paused_playbacks.paused.is_empty()); + } + + fn recording_with_displace_child() -> PhotocraftApp { + let mut app = recording_with_dialog_child(); + app.background_jobs = false; + app.session.actions.list[0].steps[0] = ("filter.distort.displace".into(), json!({})); + app + } + + fn assert_displace_call_finished(app: &mut PhotocraftApp, suffix_count: usize) { + assert!(!app.file_dialog_open()); + assert!(app.ui.dialogs.is_empty()); + assert!(app.paused_playbacks.paused.is_empty()); + assert!(app.session.actions.recording.is_some()); + assert_eq!(suffixes(app), suffix_count); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list[1].steps, child_call(), "record the child call exactly once"); + app.run("actions.record", json!({"name": "Next"})).unwrap(); + } + + #[test] + fn a_displace_step_restores_recording_when_the_map_picker_fails_or_is_cancelled() { + use crate::file_dialog::FileDialogAnswer; + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("missing.png").to_string_lossy().into_owned(); + for answer in [ + None, + Some(FileDialogAnswer::Unavailable("no picker available".into())), + Some(FileDialogAnswer::Paths(Vec::new())), + Some(FileDialogAnswer::Contents("map.png".into(), Vec::new())), + Some(FileDialogAnswer::Paths(vec![missing])), + ] { + let mut app = recording_with_displace_child(); + let (show, _) = crate::file_dialog::fake(vec![answer]); + app.services.file_dialog = Some(show); + let id = pause_child(&mut app); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert!(app.file_dialog_open()); + assert!(app.session.actions.recording.is_none()); + app.poll_file_dialog(&egui::Context::default(), None); + assert_displace_call_finished(&mut app, 0); + } + } + + #[test] + fn a_displace_step_restores_recording_when_the_map_picker_cannot_start() { + let mut app = recording_with_displace_child(); + let id = pause_child(&mut app); + assert!(crate::dialogs::confirm(&mut app, id).is_err()); + assert_displace_call_finished(&mut app, 0); + } + + #[test] + fn a_displace_step_resumes_and_records_its_call_once_after_choosing_a_map() { + let mut app = recording_with_displace_child(); + let dir = tempfile::tempdir().unwrap(); + let map = dir.path().join("map.png"); + let bytes = photocraft_io::export(&app.session.active().unwrap().doc, "png", &Default::default()).unwrap().bytes; + std::fs::write(&map, bytes).unwrap(); + let (show, _) = crate::file_dialog::fake(vec![Some(crate::file_dialog::FileDialogAnswer::Paths(vec![map.to_string_lossy().into_owned()]))]); + app.services.file_dialog = Some(show); + let id = pause_child(&mut app); + crate::dialogs::confirm(&mut app, id).unwrap(); + app.poll_file_dialog(&egui::Context::default(), None); + assert_displace_call_finished(&mut app, 1); + } + + #[test] + fn a_step_dialog_takes_only_the_steps_values() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut a = Action::new("Blur", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 2, "__command": "select.all", "__label": "Other"}))]); + a.dialogs.insert(0); + app.session.actions.list.push(a); + let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); + let d = app.ui.dialog_mut(v["paused"]["dialog"].as_u64().unwrap()).unwrap(); + assert_eq!(d.fields["radius"], 2); + assert_eq!(d.fields["__command"], "filter.blur.gaussianBlur"); + assert_ne!(d.fields["__label"], "Other"); + } + + fn deny_blur(id: &str, _: &Value) -> photocraft_engine::Result<()> { + if id == "filter.blur.gaussianBlur" { Err(photocraft_engine::EngineError::Other("blur denied".into())) } else { Ok(()) } + } + + #[test] + fn a_step_the_gate_denies_opens_no_dialog() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut a = Action::new("Blur", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1}))]); + a.dialogs.insert(0); + app.session.actions.list.push(a); + app.session.authorize = Some(deny_blur); + let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); + app.session.authorize = None; + assert!(v["failed"]["error"].as_str().is_some_and(|e| e.contains("blur denied")), "{v}"); + assert!(app.ui.dialogs.is_empty(), "no step dialog opened"); + assert!(app.paused_playbacks.paused.is_empty()); + } + + fn deny_select_all(id: &str, _: &Value) -> photocraft_engine::Result<()> { + if id == "select.all" { Err(photocraft_engine::EngineError::Other("select.all denied".into())) } else { Ok(()) } + } + + /// An action an automation client plays (`control::handle` installs the gate, then removes + /// it) pauses at a step dialog; confirming the dialog later, here with synthetic Enter or + /// OK, runs the remaining steps under the same gate. + #[test] + fn a_paused_playback_keeps_its_automation_gate_when_the_dialog_is_confirmed() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut a = Action::new("Seeded", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1})), ("select.all".into(), json!({}))]); + a.dialogs.insert(0); + app.session.actions.list.push(a); + app.session.authorize = Some(deny_select_all); + let v = play(&mut app, &json!({"action": "Seeded"})).unwrap(); + app.session.authorize = None; + let id = v["paused"]["dialog"].as_u64().unwrap(); + app.automation_input = true; + let _ = crate::dialogs::confirm(&mut app, id); + app.automation_input = false; + assert!(app.session.active().unwrap().doc.selection.is_none(), "the denied step did not run"); + assert!(app.ui.status.contains("select.all denied"), "{}", app.ui.status); + } + + /// The dialog names only its pause: changing its fields can't resume another action. + #[test] + fn a_step_dialog_resumes_only_the_playback_that_paused_it() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut a = Action::new("Blur", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1}))]); + a.dialogs.insert(0); + app.session.actions.list.push(a); + app.session.actions.list.push(Action::new("Seeded", vec![("select.all".into(), json!({}))])); + let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); + let id = v["paused"]["dialog"].as_u64().unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert(RESUME.into(), json!({"action": "Seeded", "from": 0})); + let r = crate::dialogs::confirm(&mut app, id); + assert!(app.session.active().unwrap().doc.selection.is_none(), "the other action did not play"); + assert!(r.is_err_and(|e| e.contains("paused action"))); + } + #[test] fn button_mode_plays_the_clicked_action_and_hides_its_steps() { use egui_kittest::{Harness, kittest::Queryable}; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 7f9db071c7..d2543a54c2 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5330,10 +5330,13 @@ pub(crate) fn layer_edges_rect(app: &PhotocraftApp, idx: usize) -> Option