Merge origin/main into pen-path-operations

Conflict in docs/ui-parity.md was only the status line: kept main's change list, prepended this branch's entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Khawar Zamman WaniandClaude Opus 5.5 committed 2026-10-23 09:49:48 +05:30
commit 375a278545
353 files changed
+1759 -296

No files matched your search

+1
View File
@@ -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
Generated
+34 -31
View File
@@ -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",
+3 -1
View File
@@ -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"
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -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 |
File renamed without changes.
+4
View File
@@ -0,0 +1,4 @@
//! The crate's integration tests, linked into one test binary.
mod cli;
mod orientation;
+1
View File
@@ -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 }
+40 -17
View File
@@ -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]
+5
View File
@@ -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;
+3 -3
View File
@@ -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`)
+1 -1
View File
@@ -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;
@@ -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();
+4
View File
@@ -0,0 +1,4 @@
//! The crate's integration tests, linked into one test binary.
mod compound_limits;
mod real_files;
File renamed without changes.
+5
View File
@@ -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;
File renamed without changes.
+4 -1
View File
@@ -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
}
+136
View File
@@ -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();
File renamed without changes.
File renamed without changes.
+16
View File
@@ -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;
File renamed without changes.
File renamed without changes.
+1 -1
View File
@@ -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
@@ -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};
File renamed without changes.
+6
View File
@@ -0,0 +1,6 @@
//! The crate's integration tests, linked into one test binary.
mod bench;
mod cms;
mod gpu_matrix_shaper;
mod regen;
@@ -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
+24 -1
View File
@@ -72,8 +72,31 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result<Image, CodecError> {
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 {
+9 -4
View File
@@ -206,11 +206,16 @@ fn decode_lines(lines: &[Vec<u8>], limits: &Limits) -> Result<Image, CodecError>
}
}
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"))?;
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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]
@@ -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::*;
File renamed without changes.
@@ -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::*;
File renamed without changes.
File renamed without changes.
@@ -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::*;
File renamed without changes.
@@ -8,7 +8,7 @@
#![cfg(all(feature = "corpus", feature = "heif"))]
mod common;
use crate::common;
use common::*;
use photocraft_codecs::*;
use std::sync::LazyLock;
@@ -1,6 +1,6 @@
//! Decompression-bomb guards.
mod common;
use crate::common;
use common::*;
use photocraft_codecs::*;
+35
View File
@@ -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;
@@ -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::*;
@@ -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");
@@ -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() {
@@ -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]
@@ -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::*;
File renamed without changes.
File renamed without changes.
@@ -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::*;
@@ -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::*;
File renamed without changes.
@@ -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;
File renamed without changes.
File renamed without changes.
@@ -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::*;
@@ -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::*;
@@ -1,4 +1,4 @@
mod common;
use crate::common;
use common::tiffgen::*;
use photocraft_codecs::{Image, decode, exif_orientation, upright_exif};
File renamed without changes.
@@ -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::*;
File renamed without changes.
+1
View File
@@ -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).
+24 -12
View File
@@ -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
}
+17
View File
@@ -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");
}
+5
View File
@@ -510,6 +510,8 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into<SaveOpts>) -> 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));
+5
View File
@@ -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);
+6
View File
@@ -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<Vec<u8>> {
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()
}
+16 -5
View File
@@ -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<Value> {
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<Value> {
}
}
}
Ok(())
}
fn apply_data_set(s: &mut Session, p: &Value) -> Result<Value> {
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());
File renamed without changes.
Loaded 100 of 353 files, more files were not shown because too many files have changed in this diff. Show more