Merge remote-tracking branch 'origin/main' into feat/6000-color-panel-modes

# Conflicts:
#	crates/ui-egui/src/dock.rs
#	docs/gaps.md
#	docs/scorecard.md
This commit is contained in:
Khawar Zamman Wani committed 2026-10-19 14:31:04 +05:30
commit 77650501e8
201 files changed
+7967 -630

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
version: 2
updates:
# Maintain Rust / Cargo dependencies
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "daily"
time: "06:00"
timezone: "America/New_York"
# Consolidate updates into a single PR rather than one PR per crate
groups:
cargo-dependencies:
patterns:
- "*"
commit-message:
prefix: "chore(deps)"
# Maintain GitHub Actions workflows
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
time: "06:00"
timezone: "America/New_York"
groups:
actions:
patterns:
- "*"
commit-message:
prefix: "ci(deps)"
Generated
+29 -13
View File
@@ -849,7 +849,7 @@ dependencies = [
"maybe-owned",
"rustix 1.1.5",
"rustix-linux-procfs",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
"winx",
]
@@ -1896,7 +1896,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -1934,6 +1934,18 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "exacl"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de9e551ced9d700a31dacb8b168129640240fcd7a279a3fa4d59608b84ebcae"
dependencies = [
"bitflags 2.13.2",
"log",
"scopeguard",
"uuid",
]
[[package]]
name = "exr"
version = "1.74.2"
@@ -3033,7 +3045,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
dependencies = [
"hermit-abi",
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -3695,7 +3707,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"png 0.18.1",
"thiserror 2.0.21",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -4441,7 +4453,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4699,6 +4711,7 @@ dependencies = [
"photocraft-geom",
"photocraft-io",
"rmcp",
"rustix 1.1.5",
"schemars",
"serde",
"serde_json",
@@ -4812,6 +4825,7 @@ dependencies = [
"photocraft-vector",
"rayon",
"roxmltree",
"same-file",
"serde",
"serde_json",
"tempfile",
@@ -4825,6 +4839,7 @@ version = "0.10.0"
dependencies = [
"blake3",
"crc32fast",
"exacl",
"flate2",
"libc",
"photocraft-codecs",
@@ -4838,6 +4853,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"winsafe",
]
[[package]]
@@ -5481,7 +5497,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6000,7 +6016,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6067,7 +6083,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6705,7 +6721,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -6932,10 +6948,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -7335,7 +7351,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -8095,7 +8111,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
+2
View File
@@ -427,6 +427,8 @@ fn services(inbox: Inbox, place_inbox: Inbox, cursor_pos: photocraft_ui_egui::Cu
}
})),
write: Some(Box::new(|path: &str, bytes: &[u8]| download(path, bytes))),
// A download may be cancelled and never reports back: it doesn't save the document.
write_unconfirmed: true,
encode_png: Some(Box::new(|w, h, rgba| {
let img = Image::from_u8(w, h, ChannelLayout::Rgba, rgba.to_vec()).map_err(|e| e.to_string())?;
photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string())
+2
View File
@@ -784,6 +784,7 @@ mod tests {
/// now-existing folder and the original is put back, so both autosaves stay (#6412 review).
#[test]
fn a_launch_that_times_out_never_writes_where_a_move_removes() {
let _spawns = crate::no_child_spawns();
let root = temp("recovery-timeout");
let legacy = root.join("roaming").join("Recovery");
autosave(&legacy, "old");
@@ -866,6 +867,7 @@ mod tests {
/// once the lock is released, the move happens.
#[test]
fn a_move_waits_for_another_process_holding_the_lock() {
let _spawns = crate::no_child_spawns();
let root = temp("recovery-lock");
let legacy = root.join("roaming").join("Recovery");
autosave(&legacy, "a");
+3
View File
@@ -420,6 +420,7 @@ mod tests {
#[test]
fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() {
let _spawns = crate::no_child_spawns();
let dir = temp_dir("rotate");
for run in 1..=4 {
let LogFile { path, file: _file, owner: _owner } = rotate(&dir).expect("rotate");
@@ -438,6 +439,7 @@ mod tests {
/// `.2.log`, and a fourth deleted it.
#[test]
fn a_second_start_leaves_the_running_instance_log_alone() {
let _spawns = crate::no_child_spawns();
let dir = temp_dir("second");
let mut first = rotate(&dir).expect("first start");
assert_eq!(first.path, dir.join(LOG_FILE));
@@ -461,6 +463,7 @@ mod tests {
#[test]
fn instance_logs_are_pruned_only_when_no_one_holds_them() {
let _spawns = crate::no_child_spawns();
let dir = temp_dir("prune");
let first = rotate(&dir).expect("first start");
// Earlier side-by-side runs that have exited, oldest first; the oldest has no lock file
+267 -101
View File
@@ -205,6 +205,131 @@ fn print_stdout(text: &str) {
let _ = out.write_all(text.as_bytes()).and_then(|()| out.flush());
}
/// Everything the desktop launcher takes from the command line, on top of the environment
/// defaults handed in to `parse_launch_args`.
#[derive(Debug, Default, PartialEq, Eq)]
struct LaunchArgs {
control_port: Option<u16>,
control_token: Option<String>,
control_token_file: Option<std::path::PathBuf>,
automation_read_root: Option<std::path::PathBuf>,
automation_write_root: Option<std::path::PathBuf>,
files: Vec<String>,
/// Arguments that are not valid Unicode (issue #1108): a file manager can hand over a Latin-1
/// file name on Linux, and `std::env::args()` would panic before any window opened. Paths are
/// reported in a notice once the app is up; a control token is a usage error like a bad port.
unreadable_paths: Vec<String>,
safe_gpu: bool,
new_instance: bool,
/// Options that apply only to the process they're given to; a launch with any keeps its own.
launch_options: Vec<&'static str>,
present_mode_arg: Option<String>,
frame_latency_arg: Option<String>,
stroke_trace_arg: Option<String>,
in_window_menus: bool,
/// `--help` / `-h`: print [`USAGE`] and exit 0; parsing stops there.
help: bool,
/// `--version`: print the version and exit 0; parsing stops there.
version: bool,
/// Usage errors (a bad or missing control/automation value, an unknown option); a non-empty
/// list fails the launch with exit status 2 (issues #701, #6429, #6431).
errors: Vec<String>,
}
/// Parse the desktop launch arguments over the environment defaults in `out`. A control or
/// automation flag with no value is a usage error naming the flag (issue #6429), never a silent
/// fall back to a generated token or to no root: like `--control` with a bad port, it exits 2.
/// So is an unknown option (#6431); a file whose name starts with `-` goes after `--`.
fn parse_launch_args(args: impl Iterator<Item = std::ffi::OsString>, mut out: LaunchArgs) -> LaunchArgs {
let mut args = args;
// After `--`, every argument is a file, even one that starts with `-`.
let mut only_files = false;
while let Some(a) = args.next() {
if only_files {
match a.into_string() {
Ok(s) => out.files.push(s),
Err(raw) => out.unreadable_paths.push(raw.to_string_lossy().into_owned()),
}
continue;
}
match a.to_str() {
Some("--") => only_files = true,
Some("--help" | "-h") => {
out.help = true;
break;
}
Some("--control") => match args.next() {
Some(value) => match parse_control_port(&value.to_string_lossy(), "--control") {
Ok(port) => out.control_port = Some(port),
Err(error) => out.errors.push(error),
},
None => out.errors.push("--control: missing port value (expected `--control <port>`)".to_string()),
},
Some("--control-token") => match args.next().map(std::ffi::OsString::into_string) {
Some(Ok(token)) => out.control_token = Some(token),
Some(Err(raw)) => out.errors.push(format!("--control-token: value is not valid Unicode (`{}`)", raw.to_string_lossy())),
None => out.errors.push("--control-token: missing token value (expected `--control-token <token>`)".to_string()),
},
Some("--control-token-file") => match args.next() {
Some(value) => out.control_token_file = Some(std::path::PathBuf::from(value)),
None => out.errors.push("--control-token-file: missing file path value (expected `--control-token-file <path>`)".to_string()),
},
Some("--automation-read-root") => {
out.launch_options.push("--automation-read-root");
match args.next() {
Some(value) => out.automation_read_root = Some(std::path::PathBuf::from(value)),
None => out.errors.push("--automation-read-root: missing directory value (expected `--automation-read-root <dir>`)".to_string()),
}
}
Some("--automation-write-root") => {
out.launch_options.push("--automation-write-root");
match args.next() {
Some(value) => out.automation_write_root = Some(std::path::PathBuf::from(value)),
None => out.errors.push("--automation-write-root: missing directory value (expected `--automation-write-root <dir>`)".to_string()),
}
}
Some("--safe-gpu") => {
out.launch_options.push("--safe-gpu");
out.safe_gpu = true;
}
Some(flag @ ("--present-mode" | "--frame-latency" | "--stroke-trace")) => {
out.launch_options.push(match flag {
"--present-mode" => "--present-mode",
"--frame-latency" => "--frame-latency",
_ => "--stroke-trace",
});
let flag = flag.to_string();
match args.next().map(std::ffi::OsString::into_string) {
Some(Ok(v)) => match flag.as_str() {
"--present-mode" => out.present_mode_arg = Some(v),
"--frame-latency" => out.frame_latency_arg = Some(v),
_ => out.stroke_trace_arg = Some(v),
},
// A bad value is reported and ignored; it never fails the launch.
_ => eprintln!("photocraft: {flag}: missing or unreadable value; ignored"),
}
}
Some("--in-window-menus") => {
out.launch_options.push("--in-window-menus");
out.in_window_menus = true;
}
Some("--new-instance") => out.new_instance = true,
Some("--version") => {
out.version = true;
break;
}
// Old macOS passes a process serial number when launched from Finder.
Some(s) if s.starts_with("-psn_") => {}
// A typo such as `--safegpu`, or `--help` spelt another way, must not open the window
// and then fail to open the flag as a file (#6431).
Some(s) if s.starts_with('-') => out.errors.push(format!("unknown option `{s}` (put `--` before a file name that starts with `-`)")),
Some(s) => out.files.push(s.to_owned()),
None => out.unreadable_paths.push(a.to_string_lossy().into_owned()),
}
}
out
}
#[cfg(test)]
mod control_port_tests {
use super::{parse_control_port, usage_exit_code};
@@ -234,124 +359,152 @@ mod control_port_tests {
}
}
#[cfg(test)]
mod launch_args_tests {
use super::{LaunchArgs, parse_launch_args, usage_exit_code};
use std::ffi::OsString;
fn parse(values: &[&str]) -> LaunchArgs {
parse_launch_args(values.iter().map(OsString::from), LaunchArgs::default())
}
#[test]
fn flags_without_a_value_are_usage_errors() {
// Issue #6429: a missing value must fail the launch, not silently fall back to a
// generated token or to no root.
for flag in ["--control", "--control-token", "--control-token-file", "--automation-read-root", "--automation-write-root"] {
let parsed = parse(&[flag]);
assert_eq!(parsed.errors.len(), 1, "{flag}: {:?}", parsed.errors);
assert!(parsed.errors[0].starts_with(flag), "{}", parsed.errors[0]);
assert!(parsed.errors[0].contains("missing"), "{}", parsed.errors[0]);
assert_eq!(usage_exit_code(&parsed.errors), Some(2));
}
}
#[test]
fn missing_value_does_not_clear_an_environment_default() {
// `--automation-read-root` with no value must not drop a root set through the env var.
let defaults = LaunchArgs { automation_read_root: Some("/env/read".into()), automation_write_root: Some("/env/write".into()), ..Default::default() };
let parsed = parse_launch_args(["--automation-read-root"].iter().map(OsString::from), defaults);
assert_eq!(parsed.automation_read_root.as_deref(), Some(std::path::Path::new("/env/read")));
assert_eq!(parsed.automation_write_root.as_deref(), Some(std::path::Path::new("/env/write")));
assert_eq!(parsed.errors.len(), 1, "{:?}", parsed.errors);
}
#[test]
fn values_are_parsed_and_no_errors_remain() {
let parsed = parse(&[
"--control",
"50494",
"--control-token",
"abcd",
"--control-token-file",
"/tmp/token",
"--automation-read-root",
"/r",
"--automation-write-root",
"/w",
"--safe-gpu",
"--in-window-menus",
"--new-instance",
"--present-mode",
"mailbox",
"photo.psd",
]);
assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
assert_eq!(parsed.control_port, Some(50494));
assert_eq!(parsed.control_token.as_deref(), Some("abcd"));
assert_eq!(parsed.control_token_file.as_deref(), Some(std::path::Path::new("/tmp/token")));
assert_eq!(parsed.automation_read_root.as_deref(), Some(std::path::Path::new("/r")));
assert_eq!(parsed.automation_write_root.as_deref(), Some(std::path::Path::new("/w")));
assert!(parsed.safe_gpu);
assert!(parsed.in_window_menus);
assert!(parsed.new_instance);
assert_eq!(parsed.present_mode_arg.as_deref(), Some("mailbox"));
assert_eq!(parsed.launch_options, vec!["--automation-read-root", "--automation-write-root", "--safe-gpu", "--in-window-menus", "--present-mode"]);
assert_eq!(parsed.files, vec!["photo.psd".to_string()]);
}
#[test]
fn version_stops_parsing() {
let parsed = parse(&["--version", "--control"]);
assert!(parsed.version);
assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
}
#[test]
fn help_stops_parsing_and_double_dash_ends_options() {
let parsed = parse(&["-h", "--safegpu", "--control"]);
assert!(parsed.help);
assert!(parsed.errors.is_empty(), "{:?}", parsed.errors);
let parsed = parse(&["--safegpu", "--", "--help", "-x"]);
assert!(!parsed.help);
assert_eq!(parsed.errors.len(), 1, "{:?}", parsed.errors);
assert!(parsed.errors[0].contains("unknown option `--safegpu`"), "{}", parsed.errors[0]);
assert_eq!(parsed.files, vec!["--help".to_string(), "-x".to_string()]);
}
}
fn main() -> eframe::Result {
// First, so the panic hook and every start-up warning are recorded (`logging`).
let logger = logging::install();
crash_guard::install_hook();
// The system font scan can take seconds (minutes on some Macs): run it off the UI thread.
photocraft_ui_egui::type_tool::warm_fonts();
let mut control_port: Option<u16> = None;
let mut usage_errors: Vec<String> = Vec::new();
let mut launch = LaunchArgs {
automation_read_root: std::env::var_os("PHOTOCRAFT_AUTOMATION_READ_ROOT").map(std::path::PathBuf::from),
automation_write_root: std::env::var_os("PHOTOCRAFT_AUTOMATION_WRITE_ROOT").map(std::path::PathBuf::from),
in_window_menus: std::env::var_os("PHOTOCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0"),
..Default::default()
};
if let Some(value) = std::env::var("PHOTOCRAFT_CONTROL_PORT").ok().filter(|v| !v.trim().is_empty()) {
match parse_control_port(&value, "PHOTOCRAFT_CONTROL_PORT") {
Ok(port) => control_port = Some(port),
Err(error) => usage_errors.push(error),
Ok(port) => launch.control_port = Some(port),
Err(error) => launch.errors.push(error),
}
}
let mut control_token = None;
let mut control_token_file = None;
let mut automation_read_root = std::env::var_os("PHOTOCRAFT_AUTOMATION_READ_ROOT").map(std::path::PathBuf::from);
let mut automation_write_root = std::env::var_os("PHOTOCRAFT_AUTOMATION_WRITE_ROOT").map(std::path::PathBuf::from);
let mut files = Vec::new();
// Arguments that are not valid Unicode (issue #1108): a file manager can hand over a Latin-1
// file name on Linux, and `std::env::args()` would panic before any window opened. Paths are
// reported in a notice once the app is up; a control token is a usage error like a bad port.
let mut unreadable_paths: Vec<String> = Vec::new();
let mut safe_gpu = false;
let mut new_instance = false;
// Options that apply only to the process they're given to; a launch with any keeps its own.
let mut launch_options: Vec<&'static str> = Vec::new();
let (mut present_mode_arg, mut frame_latency_arg, mut stroke_trace_arg): (Option<String>, Option<String>, Option<String>) = (None, None, None);
let mut in_window_menus = std::env::var_os("PHOTOCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
let mut args = std::env::args_os().skip(1);
// After `--`, every argument is a file, even one that starts with `-`.
let mut only_files = false;
while let Some(a) = args.next() {
if only_files {
match a.into_string() {
Ok(s) => files.push(s),
Err(raw) => unreadable_paths.push(raw.to_string_lossy().into_owned()),
}
continue;
}
match a.to_str() {
Some("--") => only_files = true,
Some("--help" | "-h") => {
print_stdout(USAGE);
return Ok(());
}
Some("--control") => match args.next() {
Some(value) => match parse_control_port(&value.to_string_lossy(), "--control") {
Ok(port) => control_port = Some(port),
Err(error) => usage_errors.push(error),
},
None => usage_errors.push("--control: missing port value (expected `--control <port>`)".to_string()),
},
Some("--control-token") => match args.next().map(std::ffi::OsString::into_string) {
Some(Ok(token)) => control_token = Some(token),
Some(Err(raw)) => usage_errors.push(format!("--control-token: value is not valid Unicode (`{}`)", raw.to_string_lossy())),
None => control_token = None,
},
Some("--control-token-file") => control_token_file = args.next().map(std::path::PathBuf::from),
Some("--automation-read-root") => {
launch_options.push("--automation-read-root");
automation_read_root = args.next().map(std::path::PathBuf::from);
}
Some("--automation-write-root") => {
launch_options.push("--automation-write-root");
automation_write_root = args.next().map(std::path::PathBuf::from);
}
Some("--safe-gpu") => {
launch_options.push("--safe-gpu");
safe_gpu = true;
}
Some(flag @ ("--present-mode" | "--frame-latency" | "--stroke-trace")) => {
launch_options.push(match flag {
"--present-mode" => "--present-mode",
"--frame-latency" => "--frame-latency",
_ => "--stroke-trace",
});
let flag = flag.to_string();
match args.next().map(std::ffi::OsString::into_string) {
Some(Ok(v)) => match flag.as_str() {
"--present-mode" => present_mode_arg = Some(v),
"--frame-latency" => frame_latency_arg = Some(v),
_ => stroke_trace_arg = Some(v),
},
// A bad value is reported and ignored; it never fails the launch.
_ => eprintln!("photocraft: {flag}: missing or unreadable value; ignored"),
}
}
Some("--in-window-menus") => {
launch_options.push("--in-window-menus");
in_window_menus = true;
}
Some("--new-instance") => new_instance = true,
Some("--version") => {
print_stdout(&format!("photocraft {}\n", photocraft_engine::build_info::long_version()));
return Ok(());
}
// Old macOS passes a process serial number when launched from Finder.
Some(s) if s.starts_with("-psn_") => {}
// A typo such as `--safegpu`, or `--help` spelt another way, must not open the window
// and then fail to open the flag as a file (#6431).
Some(s) if s.starts_with('-') => usage_errors.push(format!("unknown option `{s}` (put `--` before a file name that starts with `-`)")),
Some(s) => files.push(s.to_owned()),
None => unreadable_paths.push(a.to_string_lossy().into_owned()),
}
launch = parse_launch_args(std::env::args_os().skip(1), launch);
if launch.help {
print_stdout(USAGE);
return Ok(());
}
if launch.version {
print_stdout(&format!("photocraft {}\n", photocraft_engine::build_info::long_version()));
return Ok(());
}
// A malformed control port must not silently drop the control server (issue #701), and an
// unknown option must not open the window (#6431): name the bad argument and fail the launch,
// like `photocraft-cli` does for the same typos. Exit status 2 is the usual command-line usage
// error, so a launcher sees the failure.
if let Some(code) = usage_exit_code(&usage_errors) {
for error in &usage_errors {
// A malformed control port must not silently drop the control server (issue #701), a control
// or automation flag without its value must not silently fall back to a generated token or
// to no root (issue #6429), and an unknown option must not open the window (#6431): name the
// bad argument and fail the launch, like `photocraft-cli` does for the same typos. Exit
// status 2 is the usual command-line usage error, so a launcher sees the failure.
if let Some(code) = usage_exit_code(&launch.errors) {
for error in &launch.errors {
eprintln!("photocraft: {error}");
}
eprintln!("Run `photocraft --help` for usage.");
std::process::exit(code);
}
let LaunchArgs {
control_port,
control_token,
control_token_file,
automation_read_root,
automation_write_root,
files,
unreadable_paths,
safe_gpu,
new_instance,
launch_options,
present_mode_arg,
frame_latency_arg,
stroke_trace_arg,
in_window_menus,
help: _,
version: _,
errors: _,
} = launch;
// The log file lives under the settings directory; opened after the arguments, so `--version`
// and usage errors leave no file behind. Records logged until now are written to it first.
@@ -767,6 +920,19 @@ fn main() -> eframe::Result {
result
}
/// Tests that spawn child processes hold this for reading, tests that check who holds a file lock
/// for writing ([`no_child_spawns`]): until its `exec`, a child holds a copy of every open file,
/// `flock`s included, so a spawn in another test could keep a lock this process just dropped held
/// for a moment.
#[cfg(test)]
pub(crate) static CHILD_SPAWNS: std::sync::RwLock<()> = std::sync::RwLock::new(());
/// Held by a test that checks who holds a file lock: no other test spawns a child meanwhile.
#[cfg(test)]
pub(crate) fn no_child_spawns() -> std::sync::RwLockWriteGuard<'static, ()> {
CHILD_SPAWNS.write().unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(test)]
mod tests {
#[test]
+1
View File
@@ -495,6 +495,7 @@ mod tests {
#[cfg(unix)]
#[test]
fn a_hung_helper_is_stopped_and_big_replies_dont_block() {
let _spawns = crate::CHILD_SPAWNS.read().unwrap_or_else(std::sync::PoisonError::into_inner);
let t0 = std::time::Instant::now();
let e = run_helper(std::process::Command::new("sleep").arg("30"), std::time::Duration::from_millis(300)).unwrap_err();
assert!(e.contains("took longer than"), "{e}");
+6 -1
View File
@@ -36,17 +36,22 @@ fn mock_portal(script: Script) -> Option<(zbus::blocking::Connection, Seen, std:
/// once the user is done with it (here after 300 ms).
fn mock_portal_with(script: Script, own_paths: bool) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> {
use std::io::BufRead;
let spawns = crate::CHILD_SPAWNS.read().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut daemon =
std::process::Command::new("dbus-daemon").args(["--session", "--nofork", "--print-address=1"]).stdout(std::process::Stdio::piped()).spawn().ok()?;
drop(spawns);
let mut address = String::new();
std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?;
let address = address.trim().to_string();
let server = zbus::blocking::connection::Builder::address(address.as_str()).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap();
let seen: Seen = Arc::default();
let log = seen.clone();
// A stream only gets the messages that arrive after it exists: made in the thread, it could
// miss a `SaveFile` sent before the thread got going, and the call would wait forever.
let messages = zbus::blocking::MessageIterator::from(&server);
std::thread::spawn(move || {
let mut script = script.into_iter();
for msg in zbus::blocking::MessageIterator::from(&server) {
for msg in messages {
let Ok(msg) = msg else { break };
let header = msg.header();
if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("SaveFile") {
+61 -13
View File
@@ -36,16 +36,47 @@ fn open_filter_extensions(extensions: &[&str]) -> Vec<String> {
extensions.iter().map(|ext| if case_sensitive_globs { ext.chars().map(class).collect() } else { ext.to_string() }).collect()
}
/// An explicit SVG filter keeps vector artwork discoverable even when a native picker defaults to
/// the PhotoCraft-only filter. SVG is also included in All Formats for normal multi-format opens.
/// File › Open's file types after All Formats, as Photoshop lists them: one per format, so a folder
/// of mixed files can be narrowed to one kind (#6337). Together they cover every extension of
/// [`OPEN_EXTS`]. An explicit SVG filter also keeps vector artwork discoverable when a native
/// picker defaults to another filter.
const OPEN_FILTERS: &[(&str, &[&str])] = &[
("PhotoCraft", &["pcraft"]),
("Photoshop", &["psd", "psb", "psdt"]),
("Affinity", &["af", "afdesign", "afphoto", "afpub"]),
("Krita", &["kra", "krz"]),
("OpenRaster", &["ora"]),
("Paint.NET", &["pdn"]),
("SVG", SVG_EXTS),
("PNG", &["png"]),
("JPEG", &["jpg", "jpeg"]),
("HEIF", &["heic", "heif", "hif"]),
("TIFF", &["tif", "tiff"]),
("WebP", &["webp"]),
("GIF", &["gif"]),
("BMP", &["bmp"]),
("Targa", &["tga"]),
("ICO", &["ico"]),
("QOI", &["qoi"]),
("PCX", &["pcx"]),
("DDS", &["dds"]),
("XPM", &["xpm"]),
("Portable Bitmap", &["pbm", "pgm", "ppm", "pam", "pfm"]),
("OpenEXR", &["exr"]),
("Radiance HDR", &["hdr"]),
("FITS", &["fits", "fit", "fts"]),
("DPX and Cineon", &["dpx", "cin"]),
("Camera Raw", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]),
("Brushes", &["abr"]),
("Gradients", &["grd"]),
("Swatches", &["aco", "ase"]),
("Keyboard Shortcuts", &["kys"]),
];
fn open_filters() -> Vec<(&'static str, Vec<String>)> {
vec![
("All Formats", open_filter_extensions(OPEN_EXTS)),
("PhotoCraft", open_filter_extensions(&["pcraft"])),
("OpenRaster", open_filter_extensions(&["ora"])),
("Krita", open_filter_extensions(&["kra", "krz"])),
("SVG", open_filter_extensions(SVG_EXTS)),
]
std::iter::once(("All Formats", open_filter_extensions(OPEN_EXTS)))
.chain(OPEN_FILTERS.iter().map(|(name, exts)| (*name, open_filter_extensions(exts))))
.collect()
}
/// File › Save As formats: (filter name, extensions). The filter matching the suggested name's
@@ -160,10 +191,7 @@ fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>,
let dialog = if let Some(exts) = extensions {
dialog.add_filter("Supported Files", &open_filter_extensions(&exts.iter().map(String::as_str).collect::<Vec<_>>()))
} else {
open_filters()
.into_iter()
.fold(dialog, |dialog, (name, extensions)| dialog.add_filter(name, &extensions))
.add_filter("Paint.NET", &open_filter_extensions(&["pdn"]))
open_filters().into_iter().fold(dialog, |dialog, (name, extensions)| dialog.add_filter(name, &extensions))
};
if multiple {
let picked = dialog.pick_files();
@@ -729,6 +757,26 @@ mod tests {
assert!(svg_filter.iter().any(|glob| matches(glob, "svg")) && svg_filter.iter().any(|glob| matches(glob, "svgz")));
}
/// #6337: after All Formats, every format File › Open reads has its own filter, and no filter
/// offers an extension All Formats doesn't.
#[test]
fn every_open_format_has_its_own_filter() {
let filters = open_filters();
assert_eq!(filters[0], ("All Formats", open_filter_extensions(OPEN_EXTS)), "All Formats comes first");
let mut named: Vec<&str> = OPEN_FILTERS.iter().flat_map(|(_, exts)| exts.iter().copied()).collect();
let total = named.len();
named.sort_unstable();
named.dedup();
assert_eq!(named.len(), total, "an extension is listed under two filters");
let mut all = OPEN_EXTS.to_vec();
all.sort_unstable();
assert_eq!(named, all, "the named filters cover All Formats exactly");
let names: Vec<&str> = filters.iter().map(|(name, _)| *name).collect();
for name in ["Photoshop", "Affinity", "HEIF", "PNG", "JPEG", "TIFF", "Portable Bitmap", "OpenEXR", "Radiance HDR", "Paint.NET"] {
assert!(names.contains(&name), "{name}");
}
}
#[cfg(not(all(unix, not(target_os = "macos"))))]
#[test]
fn open_filters_keep_literal_extensions_on_windows_and_macos() {
+3
View File
@@ -169,3 +169,6 @@ sync_github_name = true
[people.Silvertree2010]
display_name = "Netter"
sync_github_name = false
[people.Byxis]
sync_github_name = true
+1 -1
View File
@@ -139,7 +139,7 @@ zstd window, 4096 saved revisions, array lengths no longer than the
bytes left, 16 777 216 decoded values per document stream (fields and array elements together, counted before
anything is allocated: a value takes about 40 bytes in memory however few it took in the file; the largest of
those 189 public documents uses 3.3 million), 384 levels of object nesting, 128 levels of layers, 500 000 layers, four million curve
nodes per curve, 64 megapixels per pixel layer (cropped to its content first) and 1024 gradient
nodes per curve, 4 levels of spot colours defined through spot colours, 64 megapixels per pixel layer (cropped to its content first) and 1024 gradient
stops; `photocraft-io` adds 300 000 pixels a side per document and 64 megapixels per image on the
canvas. Every archive entry's CRC-32 and size must match. Malformed input returns an `Error`; the
crate has no panics outside tests.
+16 -1
View File
@@ -134,8 +134,19 @@ fn floats(v: &Value) -> Option<Vec<f64>> {
}
}
/// Spot colours defined through spot colours. A spot colour (`Pant`) is read through its RGB
/// equivalent, else its base colour, which in real files hold plain colours. Colours are shared
/// objects, so one can link to itself, and with both links followed at every level a colour read
/// costs up to 2^(depth+1) lookups.
const MAX_SPOT_DEPTH: usize = 4;
/// A colour object (`RGBA`, `HSLA`, `CMYK`, `GRAY`, `LABA`, `Pant`).
pub(crate) fn color(r: &mut Reader, id: ObjId) -> Option<Color> {
color_at(r, id, 0)
}
/// [`color`] of an object `depth` spot colours down.
fn color_at(r: &mut Reader, id: ObjId, depth: usize) -> Option<Color> {
let s = r.s;
let class = s.class(id)?;
let col = || -> Option<Vec<f64>> {
@@ -166,8 +177,12 @@ pub(crate) fn color(r: &mut Reader, id: ObjId) -> Option<Color> {
Color::Lab { l: 100.0 * u(0)?, a: 255.0 * u(1)? - 128.0, b: 255.0 * u(2)? - 128.0, alpha: u(3)? }
}
b"Pant" => {
if depth >= MAX_SPOT_DEPTH {
r.warn("spot colours nested deeper than 4 levels (left empty)");
return None;
}
r.warn("spot colours (imported as their RGB equivalent)");
return s.obj(id, b"srgb").and_then(|c| color(r, c)).or_else(|| s.obj(id, b"base").and_then(|c| color(r, c)));
return s.obj(id, b"srgb").and_then(|c| color_at(r, c, depth + 1)).or_else(|| s.obj(id, b"base").and_then(|c| color_at(r, c, depth + 1)));
}
b"RegC" => Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0, a: 1.0 },
_ => {
+171
View File
@@ -538,3 +538,174 @@ mod pixels {
);
}
}
/// Spot colours that link to themselves or to each other. Each document is read on a 1 MiB
/// stack, the smallest main-thread stack PhotoCraft runs on (Windows), first in a child process
/// that must finish within 20 s. A stack overflow aborts the process it happens in, so unbounded
/// recursion fails the one test that caused it instead of taking the other tests in the binary
/// down with it.
mod spot_colours {
use std::io::{Read, Write};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use crate::container::Limits;
use crate::model::{Document, Kind};
use crate::paint::{Color, Paint};
use crate::stream::Tag;
use crate::synth::{self, F, Method, tag};
/// A one-page document whose page holds `top`, read in a child process first and then here.
fn read(top: Vec<F>) -> Document {
let spread = F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 400.0, 300.0])), (tag(b"Chld"), F::Shared(top))]);
let data = synth::stream(&[(tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]);
let bytes = synth::container(&[("doc.dat", &data, Method::Zlib)], None);
let test = std::thread::current().name().unwrap_or("reader").to_owned();
read_in_child(&bytes, &test);
read_on_small_stack(bytes, &test).unwrap()
}
/// Reads on a 1 MiB thread named after the test, so a stack overflow message names the test.
fn read_on_small_stack(bytes: Vec<u8>, test: &str) -> Result<Document, crate::Error> {
let reader = std::thread::Builder::new().name(test.to_owned()).stack_size(1 << 20).spawn(move || crate::read(&bytes, Limits::default())).unwrap();
reader.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic))
}
/// Set in the child process to the name of the test it reads for.
const CHILD: &str = "PHOTOCRAFT_AFFINITY_READ_CHILD";
/// Runs `read_child` in a new process of this test binary on `bytes` and fails the test if
/// that process crashes, panics or takes over 20 s, or never read the document.
fn read_in_child(bytes: &[u8], test: &str) {
let mut child = Command::new(std::env::current_exe().unwrap())
.args(["tests::spot_colours::read_child", "--exact", "--ignored", "--nocapture", "--test-threads=1"])
.env(CHILD, test)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let drain = |mut pipe: Box<dyn Read + Send>| {
std::thread::spawn(move || {
let mut text = String::new();
let _ = pipe.read_to_string(&mut text);
text
})
};
let stdout = drain(Box::new(child.stdout.take().unwrap()));
let stderr = drain(Box::new(child.stderr.take().unwrap()));
// Fed from a thread, so a child that never reads cannot block the deadline below; a child
// that dies first breaks the pipe and is reported by its exit status.
let (mut stdin, input) = (child.stdin.take().unwrap(), bytes.to_vec());
let feed = std::thread::spawn(move || {
let _ = stdin.write_all(&input);
});
let deadline = Instant::now() + Duration::from_secs(20);
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
break Some(status);
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
break None;
}
std::thread::sleep(Duration::from_millis(10));
};
feed.join().unwrap();
let output = format!("{}{}", stdout.join().unwrap(), stderr.join().unwrap());
match status {
None => panic!("reading the document did not finish within 20 s:\n{output}"),
Some(status) if !status.success() => panic!("reading the document failed in a child process ({status}):\n{output}"),
// A filter that matched no test would also exit successfully, having read nothing.
Some(_) => assert!(output.contains(&format!("read {} bytes", bytes.len())), "the child process did not read the document:\n{output}"),
}
}
/// Not a test of its own: `read_in_child` runs it in a child process to read the document on
/// its stdin. Without the variable, as when run with `--ignored`, it does nothing.
#[test]
#[ignore = "run by read_in_child in a child process"]
fn read_child() {
let Some(test) = std::env::var_os(CHILD) else { return };
let mut bytes = Vec::new();
std::io::stdin().read_to_end(&mut bytes).unwrap();
let len = bytes.len();
let _ = read_on_small_stack(bytes, &test.to_string_lossy());
println!("read {len} bytes");
}
/// An ellipse filled with `colour`.
fn filled(id: u32, colour: F) -> F {
F::Def(
id,
vec![tag(b"ShpN")],
vec![
(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 1.0, 1.0])),
(tag(b"Shpe"), F::Def(id + 1_000_000, vec![tag(b"ShpE")], vec![])),
(tag(b"BFFl"), F::Shared(vec![F::Def(id + 2_000_000, vec![tag(b"FilS")], vec![(tag(b"Colr"), colour)])])),
],
)
}
fn spot(id: u32, fields: Vec<(Tag, F)>) -> F {
F::Def(id, vec![tag(b"Pant")], fields)
}
fn fills(doc: &Document) -> &[Paint] {
match &doc.spreads[0].nodes[0].kind {
Kind::Shape { fills, .. } => fills,
other => panic!("expected a shape, got {other:?}"),
}
}
fn warned(doc: &Document, what: &str) -> bool {
doc.warnings.iter().any(|w| w.contains(what))
}
#[test]
fn a_spot_colour_that_is_its_own_rgb_equivalent_is_refused() {
let doc = read(vec![filled(10, spot(20, vec![(tag(b"srgb"), F::Ref(20))]))]);
assert!(fills(&doc).is_empty(), "{:?}", fills(&doc));
assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings);
}
#[test]
fn spot_colours_that_are_each_others_base_and_rgb_equivalent_are_refused() {
let doc = read(vec![filled(10, spot(20, vec![(tag(b"base"), spot(21, vec![(tag(b"srgb"), F::Ref(20))]))]))]);
assert!(fills(&doc).is_empty(), "{:?}", fills(&doc));
assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings);
}
#[test]
fn spot_colours_of_spot_colours_do_not_take_exponential_time() {
// Each level's RGB equivalent and base are the next level, and the last is in an unknown
// model, so both are followed everywhere: 2^41 colour reads before the fix.
fn level(id: u32, left: u32) -> F {
if left == 0 {
return F::Def(id, vec![tag(b"XXXX")], vec![]);
}
spot(id, vec![(tag(b"srgb"), level(id + 1, left - 1)), (tag(b"base"), F::Ref(id + 1))])
}
let doc = read(vec![filled(10, level(100, 40))]);
assert!(fills(&doc).is_empty(), "{:?}", fills(&doc));
}
/// `spots` spot colours, each defined through the next, around an opaque RGB colour.
fn spots(id: u32, spots: u32) -> F {
if spots == 0 {
let rgba: Vec<u8> = [1.0f32, 0.5, 0.25, 1.0].iter().flat_map(|c| c.to_le_bytes()).collect();
return F::Def(id, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct(rgba))]);
}
spot(id, vec![(tag(b"srgb"), self::spots(id + 1, spots - 1))])
}
#[test]
fn spot_colours_nest_four_levels_and_no_deeper() {
let doc = read(vec![filled(10, spots(100, 4))]);
assert_eq!(fills(&doc), [Paint::Solid(Color::Rgb { r: 1.0, g: 0.5, b: 0.25, a: 1.0 })]);
let doc = read(vec![filled(10, spots(100, 5))]);
assert!(fills(&doc).is_empty(), "{:?}", fills(&doc));
assert!(warned(&doc, "spot colours nested deeper than 4 levels"), "{:?}", doc.warnings);
}
}
+1 -1
View File
@@ -335,7 +335,7 @@ pub(crate) fn lens_blur(src: &Image, out: Rect, ctx: &Ctx, spec: &LensSpec) -> V
}
src.get(x, y, n - 1)
}
DepthSource::LayerMask => spec.depth_map?.get(x, y, 0),
DepthSource::LayerMask | DepthSource::Channel => spec.depth_map?.get(x, y, 0),
};
Some(if spec.invert { 1.0 - d } else { d })
};
+63 -6
View File
@@ -173,6 +173,39 @@ fn up(p: &Plane, w: usize, h: usize) -> Plane {
Plane { w, h, v: out }
}
/// The source rows of [`up`]`(p, w, h)` at output row `y`, one per tap (`None` where the
/// zero-stuffed row is all zeros).
fn up_rows(p: &Plane, h: usize, y: usize) -> [Option<usize>; 5] {
let lh = p.h.min(h.div_ceil(2));
std::array::from_fn(|k| {
let m = mirror(y as isize + k as isize - 2, h);
(m.is_multiple_of(2) && m / 2 < lh).then_some(m / 2)
})
}
/// One sample of [`up`]`(p, w, h)`: column `x` of the output row whose [`up_rows`] are `rows`.
/// It adds the same terms in the same order as `up`, so it gives the same bits.
fn up_at(p: &Plane, w: usize, rows: &[Option<usize>; 5], x: usize) -> f32 {
let lw = p.w.min(w.div_ceil(2));
let col = |j: usize| -> f32 { (0..5).filter_map(|k| rows[k].map(|r| TAPS[k] * (p.v[r * p.w + j] * 4.0))).sum() };
if x >= 2 && x + 2 < w {
// Away from the edges no tap mirrors.
(0..5)
.filter_map(|k| {
let i = x + k - 2;
(i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * col(i / 2))
})
.sum()
} else {
(0..5)
.filter_map(|k| {
let m = mirror(x as isize + k as isize - 2, w);
(m.is_multiple_of(2) && m / 2 < lw).then(|| TAPS[k] * col(m / 2))
})
.sum()
}
}
/// Levels down to about 2 pixels on the short side.
fn depth(w: usize, h: usize) -> usize {
let mut s = w.min(h);
@@ -217,14 +250,14 @@ fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane {
});
let gr = gaussian(m, n);
for l in 0..n - 1 {
let coarse = up(&gr[l + 1], gr[l].w, gr[l].h);
let (gl, fine, lw) = (&g[l].v, &gr[l].v, g[l].w);
let (gl, fine, lw, lh, coarse) = (&g[l].v, &gr[l].v, g[l].w, g[l].h, &gr[l + 1]);
rows(&mut lap[l], lw, |y, row| {
let taps = up_rows(coarse, lh, y);
for (x, o) in row.iter_mut().enumerate() {
let i = y * lw + x;
let wgt = (1.0 - (gl[i].clamp(lo, hi) - r).abs() / step).max(0.0);
if wgt > 0.0 {
*o += wgt * (fine[i] - coarse.v[i]);
*o += wgt * (fine[i] - up_at(coarse, lw, &taps, x));
}
}
});
@@ -244,8 +277,10 @@ fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane {
/// The `q` quantile (0 … 1) of `v`.
fn quantile(v: &[f32], q: f32) -> f32 {
let mut s = v.to_vec();
s.sort_by(f32::total_cmp);
s[((s.len() - 1) as f32 * q).round() as usize]
// Selecting the one element is linear, a full sort is not (5 sorts of the work copy were a
// fifteenth of a render). `total_cmp` ties are bit-identical, so it is the sorted element.
let i = ((s.len() - 1) as f32 * q).round() as usize;
*s.select_nth_unstable_by(i, f32::total_cmp).1
}
/// 1st and 99th percentiles of the log luminance on a copy at most 256 pixels across.
@@ -444,11 +479,33 @@ mod tests {
assert_eq!(blur_step(&p, step).v, blur_step_reference(&p, step).v, "blur {w}×{h} step {step}");
}
for (uw, uh) in [(w * 2, h * 2), (w * 2 - 1, h * 2 - 1), (w * 2, h * 2 - 1), (w.max(2) * 2 - 3, h * 2)] {
assert_eq!(up(&p, uw, uh).v, up_reference(&p, uw, uh).v, "up {w}×{h} → {uw}×{uh}");
let full = up(&p, uw, uh);
assert_eq!(full.v, up_reference(&p, uw, uh).v, "up {w}×{h} → {uw}×{uh}");
// The filter samples `up` one pixel at a time; every sample has the same bits.
for y in 0..uh {
let taps = up_rows(&p, uh, y);
for x in 0..uw {
assert_eq!(up_at(&p, uw, &taps, x).to_bits(), full.v[y * uw + x].to_bits(), "up_at {w}×{h} → {uw}×{uh} at {x},{y}");
}
}
}
}
}
#[test]
fn quantile_is_the_sorted_element() {
let p = noise_plane(301, 211, 9);
let mut v = p.v.clone();
// Ties and signed zeros, which `total_cmp` orders by their bits.
v.extend([0.0, -0.0, 0.0, -0.0, 3.5, 3.5, f32::MIN_POSITIVE]);
let mut sorted = v.clone();
sorted.sort_by(f32::total_cmp);
for q in [0.0, 0.001, 0.01, 0.25, 0.5, 0.99, 1.0] {
let want = sorted[((sorted.len() - 1) as f32 * q).round() as usize];
assert_eq!(quantile(&v, q).to_bits(), want.to_bits(), "q {q}");
}
}
fn grey(w: usize, h: usize, f: impl Fn(usize, usize) -> f32) -> Vec<[f32; 4]> {
(0..w * h).map(|i| f(i % w, i / w)).map(|v| [v, v, v, 1.0]).collect()
}
+5 -1
View File
@@ -482,7 +482,8 @@ pub enum FilterParams {
distribution: Distribution,
monochromatic: bool,
seed: u32,
/// Depth for [`DepthSource::LayerMask`] (channel 0, document coordinates), supplied by the caller.
/// Depth for [`DepthSource::LayerMask`] and [`DepthSource::Channel`] (channel 0, document
/// coordinates), supplied by the caller.
#[serde(skip)]
depth_map: Option<std::sync::Arc<Image>>,
},
@@ -972,6 +973,7 @@ fn auto_tile(params: &FilterParams, bounds: Rect) -> i32 {
}
/// [`apply`] / [`apply_in`] with an explicit tile size (tests use it to check tile independence).
/// Nonpositive tile sizes are treated as one pixel.
pub fn apply_tiled(
surface: &Surface,
params: &FilterParams,
@@ -1014,6 +1016,8 @@ fn apply_tiled_with_impl(
ctl: &photocraft_raster::Interrupt,
prepare_fast_paths: bool,
) -> Option<Surface> {
// Every dispatch path needs a positive step, including Motion Blur's fallback.
let tile = tile.max(1);
if ctl.cancelled() {
return None;
}
+3
View File
@@ -182,6 +182,9 @@ pub enum DepthSource {
None,
Transparency,
LayerMask,
/// An alpha channel of the document (Photoshop lists them after Layer Mask), supplied by the
/// caller like the layer mask.
Channel,
}
/// Built-in Shape Blur kernels.
+6 -2
View File
@@ -126,7 +126,9 @@ pub fn object_select(sampler: &dyn Sampler, canvas: Rect, rect: Rect, work_px: u
}
let (fg, bg) = grabcut(&img, &mut trimap, 8)?;
let low: Vec<bool> = trimap.iter().map(|t| is_fg(*t)).collect();
let low = super::clean_mask(&low, lw, lh, 0.1, 0.002);
let low = super::clean_mask(&low, lw, lh, 0.1, 0.0);
// Every enclosed hole, however small, fills only when it looks like the object, so background seen through it stays open.
let low = super::fill_holes_by_model(&low, &img, &fg, &bg, 0.0, 0.05);
super::finish_region(sampler, window, step, &low, lw, lh, Some((&fg, &bg)))
}
@@ -209,7 +211,9 @@ pub fn object_at(sampler: &dyn Sampler, canvas: Rect, x: f32, y: f32, work_px: u
let mut seeds = vec![false; w * h];
seeds[sy * w + sx] = true;
let low = super::keep_seeded(&low, &seeds, w, h);
let low = super::clean_mask(&low, w, h, 0.1, 0.01);
let low = super::clean_mask(&low, w, h, 0.1, 0.0);
// As in the rectangle mode: enclosed holes fill only when they look like the object.
let low = super::fill_holes_by_model(&low, &img, &fg, &bg, 0.0, 0.05);
if !low.iter().any(|v| *v) {
return None;
}
+58
View File
@@ -912,3 +912,61 @@ fn select_subject_dump_pictures() {
write("ring", &img, None);
write("ring-selected", &img, reg.as_ref());
}
/// A dark square on a light background with a square hole that shows the background colour.
fn square_with_hole(hole: usize) -> RgbImage {
let (w, h) = (400usize, 300usize);
let mut rng = Rng::new(11);
let (x0, y0) = (100usize, 50usize);
RgbImage::from_fn(w, h, |x, y| {
let n = 0.02 * rng.normal();
let in_square = x >= x0 && x < x0 + 200 && y >= y0 && y < y0 + 200;
let in_hole = x >= x0 + 96 && x < x0 + 96 + hole && y >= y0 + 96 && y < y0 + 96 + hole;
let c = if in_square && !in_hole { [0.1, 0.12, 0.15] } else { [0.9, 0.9, 0.85] };
c.map(|v: f32| (v + n).clamp(0.0, 1.0))
})
}
#[test]
fn object_select_keeps_small_background_hole_open() {
let img = square_with_hole(8);
let s = ImageSampler { img: &img, origin: (0, 0) };
let canvas = Rect::new(0, 0, 400, 300);
let reg = grabcut::object_select(&s, canvas, Rect::new(80, 30, 320, 270), 1_000_000).unwrap();
assert!(reg.at(150, 100) >= 0.5, "the square itself is selected");
assert!(reg.at(200, 150) < 0.5, "background seen through the object stays unselected");
}
#[test]
fn object_at_keeps_small_background_hole_open() {
let img = square_with_hole(16);
let s = ImageSampler { img: &img, origin: (0, 0) };
let canvas = Rect::new(0, 0, 400, 300);
let reg = grabcut::object_at(&s, canvas, 130.0, 80.0, 1_000_000).unwrap();
assert!(reg.at(150, 100) >= 0.5, "the square itself is selected");
assert!(reg.at(203, 153) < 0.5, "background seen through the object stays unselected");
}
#[test]
fn hole_fill_without_specks_fills_object_coloured_holes_only() {
// The hole check Object Selection uses: no hole fills just for being small, a speck of the object's colour still does.
let (w, h) = (40usize, 40usize);
let mut rng = Rng::new(5);
let in_square = |x: usize, y: usize| (5..35).contains(&x) && (5..35).contains(&y);
let bg_hole = |x: usize, y: usize| (10..12).contains(&x) && (10..12).contains(&y);
let fg_hole = |x: usize, y: usize| (25..27).contains(&x) && (25..27).contains(&y);
let img = RgbImage::from_fn(w, h, |x, y| {
let n = 0.02 * rng.normal();
let c = if in_square(x, y) && !bg_hole(x, y) { [0.1, 0.12, 0.15] } else { [0.9, 0.9, 0.85] };
c.map(|v: f32| (v + n).clamp(0.0, 1.0))
});
let mask: Vec<bool> = (0..w * h).map(|i| in_square(i % w, i / w) && !bg_hole(i % w, i / w) && !fg_hole(i % w, i / w)).collect();
// The colour models, as GrabCut would fit them: the object colour vs. the backdrop colour.
let dark: Vec<bool> = (0..w * h).map(|i| in_square(i % w, i / w) && !bg_hole(i % w, i / w)).collect();
let (fs, bs): (Vec<_>, Vec<_>) = img.px.iter().zip(&dark).partition(|(_, m)| **m);
let fit = |v: Vec<(&[f32; 3], &bool)>| Gmm::fit(&v.iter().map(|(p, _)| **p).collect::<Vec<_>>(), 3, gmm::DEFAULT_REG).unwrap();
let (fg, bg) = (fit(fs), fit(bs));
let out = fill_holes_by_model(&mask, &img, &fg, &bg, 0.0, 0.05);
assert!(out[25 * w + 25], "a speck of the object's colour fills");
assert!(!out[10 * w + 10], "a speck of the background's colour stays open");
}
+21
View File
@@ -90,6 +90,27 @@ fn radial_blur_quality_defaults_for_older_serialized_parameters() {
assert_eq!(decoded, FilterParams::RadialBlur { amount: 20.0, method: RadialMethod::Spin, quality: RadialQuality::Good, center_x: 0.5, center_y: 0.5 });
}
#[test]
fn nonpositive_tile_sizes_match_one_pixel_tiles() {
let area = Rect::new(0, 0, 4, 3);
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
let source = pattern(depth, area);
for params in all_filters().into_iter().chain([FilterParams::ShapeBlur { radius: 3.0, shape: BlurShape::Star }]) {
let expected = apply_tiled(&source, &params, area, area, None, 1, Some(area));
for tile in [0, -64, i32::MIN] {
let actual = apply_tiled(&source, &params, area, area, None, tile, Some(area));
assert_eq!(actual.read_region(area), expected.read_region(area), "{}: {depth:?}, tile={tile}", params.label());
let cancellable = apply_tiled_with(&source, &params, area, area, None, tile, Some(area), &photocraft_raster::Interrupt::NONE)
.expect("a nonpositive tile size is normalized, not rejected");
assert_eq!(cancellable.read_region(area), expected.read_region(area), "{}: {depth:?}, tile={tile}", params.label());
let cancelled = photocraft_raster::Interrupt::cancel_only(&|| true);
assert!(apply_tiled_with(&source, &params, area, area, None, tile, Some(area), &cancelled).is_none());
}
}
assert_eq!(source.read_region(area), pattern(depth, area).read_region(area));
}
}
#[test]
fn every_filter_is_tile_independent() {
let s = pattern(SampleType::U8, R);
+51
View File
@@ -65,6 +65,35 @@ pub fn replace_color(px: &mut [[f32; 4]], color: [f32; 3], fuzziness: f32, hue:
mask
}
/// Replace Color's Result swatch: `color` after the hue (±180°), saturation and lightness (±100)
/// shift, as a fully matched pixel of that colour becomes.
pub fn replace_color_result(color: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [f32; 3] {
let mut px = [[color[0], color[1], color[2], 1.0]];
replace_color_masked(&mut px, &[1.0], hue, saturation, lightness);
[px[0][0], px[0][1], px[0][2]]
}
/// The hue (±180°), saturation and lightness (±100) shift that turns `from` into `to`, as
/// Photoshop's Result Color Picker sets the sliders. A shift the sliders can't reach (a grey has
/// no hue to turn, black or white no saturation to give) goes as far as they do.
pub fn replace_color_shift(from: [f32; 3], to: [f32; 3]) -> (f32, f32, f32) {
let [fh, fs, fl] = rgb_to_hsl(from);
let [th, ts, tl] = rgb_to_hsl(to);
// Hue turns the short way round; a grey target keeps the hue where it is.
let hue = if ts <= 0.0 { 0.0 } else { ((th - fh + 0.5).rem_euclid(1.0) - 0.5) * 360.0 };
// Inverse of the shift in `replace_color_masked`: up moves toward 1, down toward 0.
let amount = |from: f32, to: f32| {
if to >= from {
if from >= 1.0 { 0.0 } else { (to - from) / (1.0 - from) * 100.0 }
} else if from <= 0.0 {
0.0
} else {
(to / from - 1.0) * 100.0
}
};
(hue.clamp(-180.0, 180.0), amount(fs, ts).clamp(-100.0, 100.0), amount(fl, tl).clamp(-100.0, 100.0))
}
/// Replace Color's hue, saturation and lightness shift, applied to each pixel as far as `mask`
/// (`0..=1`, one per pixel: the colour match, localized or not) covers it.
pub fn replace_color_masked(px: &mut [[f32; 4]], mask: &[f32], hue: f32, saturation: f32, lightness: f32) {
@@ -277,6 +306,28 @@ pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) {
mod tests {
use super::*;
/// #6278: the Result swatch is the sampled colour after the shift, and a picked Result sets
/// the sliders that give it.
#[test]
fn replace_color_result_and_shift_round_trip() {
let from = [0.8, 0.2, 0.2];
let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 2e-3);
assert!(near(replace_color_result(from, 0.0, 0.0, 0.0), from), "no shift, no change");
for to in [[0.2, 0.3, 0.9], [0.9, 0.85, 0.1], [0.4, 0.1, 0.1], [0.95, 0.6, 0.6], [0.1, 0.6, 0.3]] {
let (h, s, l) = replace_color_shift(from, to);
assert!((-180.0..=180.0).contains(&h) && (-100.0..=100.0).contains(&s) && (-100.0..=100.0).contains(&l));
assert!(near(replace_color_result(from, h, s, l), to), "{to:?}: ({h}, {s}, {l}) gives {:?}", replace_color_result(from, h, s, l));
}
// Red to blue turns the short way (−120°, not +240°).
assert!((replace_color_shift([1.0, 0.0, 0.0], [0.0, 0.0, 1.0]).0 + 120.0).abs() < 0.5);
// A grey target: saturation all the way down, the hue left alone.
let (h, s, _) = replace_color_shift(from, [0.5, 0.5, 0.5]);
assert_eq!((h, s), (0.0, -100.0));
// Black has no saturation to raise: the slider stays put rather than dividing by zero.
let (h, s, l) = replace_color_shift([0.0, 0.0, 0.0], [0.2, 0.6, 0.3]);
assert!(h.is_finite() && s.is_finite() && l > 0.0);
}
fn ramp(w: usize, h: usize) -> Vec<[f32; 4]> {
(0..w * h)
.map(|i| {
+22 -1
View File
@@ -333,7 +333,12 @@ fn warp(
// A source straddling the horizon draws only its front side: the inverse w at a pixel has the
// sign of the forward w at the source point it samples, and the other side would show as a
// mirrored copy wrapped round infinity (#4863).
let front = side.is_none().then(|| h.front_side([src_rect.x0 as f64, src_rect.y0 as f64, src_rect.x1 as f64, src_rect.y1 as f64]));
// A clip wholly on one side of the inverse horizon only samples that side, so that side is drawn
// (a Perspective Crop low on a converging photo has most of the layer beyond its horizon, #7557).
let clip_w = clip.map(|c| [(c.x0, c.y0), (c.x1, c.y0), (c.x1, c.y1), (c.x0, c.y1)].map(|(x, y)| inv.w(x as f64, y as f64)));
let clip_side = clip_w.and_then(|cw| [1.0, -1.0].into_iter().find(|&s| cw.iter().all(|&w| s * w > 0.0)));
let front =
side.is_none().then(|| clip_side.unwrap_or_else(|| h.front_side([src_rect.x0 as f64, src_rect.y0 as f64, src_rect.x1 as f64, src_rect.y1 as f64])));
let bounds = corner_bounds(&corners);
let dst = match (clip, bounds) {
// The warped corners only bound the result while the whole source is in front of the horizon.
@@ -713,6 +718,22 @@ mod tests {
assert_eq!(ok.front_side([0.0, 0.0, 100.0, 100.0]), ok.w(50.0, 50.0).signum());
}
/// #7557: a Perspective Crop quad low on a strongly converging photo puts the horizon across
/// the layer with most of it (and its centre) on the far side. The clip maps wholly into the
/// quad, so its side is the one drawn, not the source's majority.
#[test]
fn a_clip_wholly_on_one_side_draws_that_side() {
let mut s = rgba();
s.fill_rect(Rect::new(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]);
let q = [[40.0, 70.0], [60.0, 70.0], [90.0, 95.0], [10.0, 95.0]];
let h = quad_to_rect(&q, 50.0, 39.0).unwrap();
assert!(h.front_side([0.0, 0.0, 100.0, 100.0]) * h.w(50.0, 80.0) < 0.0, "the source's majority is behind the quad's side");
for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] {
let w = warp_surface_clipped(&s, s.content_bounds(), &h, interp, Rect::new(0, 0, 50, 39)).unwrap();
assert_eq!(w.rgba(25, 20), [1.0, 0.0, 0.0, 1.0], "{interp:?}");
}
}
#[test]
fn identity_and_translation_are_exact() {
let mut s = rgba();
+50 -10
View File
@@ -14,8 +14,9 @@
//! later (lower-right) cell wins. Work is split per destination tile (parallel on native).
use photocraft_color::PixelFormat;
use photocraft_geom::Rect;
use photocraft_raster::Surface;
use photocraft_geom::{Rect, TileCoord};
use photocraft_raster::{Surface, Tile};
use std::sync::Arc;
use crate::transform::{Interp, bicubic};
@@ -207,7 +208,7 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2
}
let n = fmt.channels();
let a = n - 1;
let work = |(t, tris): (&Rect, &Vec<[usize; 3]>)| -> Option<(Rect, Vec<f32>)> {
let work = |(t, tris): (&Rect, &Vec<[usize; 3]>)| -> Option<(TileCoord, Arc<Tile>)> {
if tris.is_empty() {
return None;
}
@@ -296,6 +297,11 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2
f64::from(px[((y - foot.y0) as usize * fw + (x - foot.x0) as usize) * n + c])
}
};
// Offset of pixel (x, y) when the `taps` x `taps` block from it lies inside `foot`, so
// the samplers can index `px` directly instead of bounds-checking every tap.
let base = |x: i32, y: i32, taps: i32| -> Option<usize> {
(x >= foot.x0 && y >= foot.y0 && x + taps <= foot.x1 && y + taps <= foot.y1).then(|| ((y - foot.y0) as usize * fw + (x - foot.x0) as usize) * n)
};
let mut outp = vec![0.0f32; w * h * n];
let mut any = false;
let mut acc = [0.0f64; 8];
@@ -313,6 +319,17 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2
Interp::Bilinear => {
let (ix, iy) = (u.floor() as i32, v.floor() as i32);
let (fx, fy) = (u - f64::from(ix), v - f64::from(iy));
if let Some(o) = base(ix, iy, 2) {
for (dy, wy) in [(0, 1.0 - fy), (1, fy)] {
for (dx, wx) in [(0, 1.0 - fx), (1, fx)] {
let p = &px[o + (dy * fw + dx) * n..][..n];
for (s, v) in acc.iter_mut().zip(p) {
*s += f64::from(*v) * wx * wy;
}
}
}
return;
}
for (dy, wy) in [(0, 1.0 - fy), (1, fy)] {
for (dx, wx) in [(0, 1.0 - fx), (1, fx)] {
for (c, s) in acc.iter_mut().enumerate().take(n) {
@@ -327,6 +344,21 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2
let (u, v) = (snap(u), snap(v));
let (ix, iy) = (u.floor() as i32, v.floor() as i32);
let (wx, wy) = (bicubic(u - f64::from(ix)), bicubic(v - f64::from(iy)));
if let Some(o) = base(ix - 1, iy - 1, 4) {
for (j, wyj) in wy.iter().enumerate() {
for (i, wxi) in wx.iter().enumerate() {
let k = wxi * wyj;
if k == 0.0 {
continue;
}
let p = &px[o + (j * fw + i) * n..][..n];
for (s, v) in acc.iter_mut().zip(p) {
*s += f64::from(*v) * k;
}
}
}
return;
}
for (j, wyj) in wy.iter().enumerate() {
for (i, wxi) in wx.iter().enumerate() {
let k = wxi * wyj;
@@ -378,19 +410,27 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2
}
outp[b + a] = al as f32;
}
any.then_some((*t, outp))
if !any {
return None;
}
// Encoded (and dropped if fully transparent) here, in parallel, rather than one tile at
// a time once all are done. `t` lies in one tile.
let mut one = Surface::new(fmt);
one.write_region(*t, &outp);
one.prune();
if one.tile_count() == 0 {
return None;
}
one.take_tiles(*t).pop()
};
#[cfg(not(target_arch = "wasm32"))]
let done: Vec<(Rect, Vec<f32>)> = {
let done: Vec<(TileCoord, Arc<Tile>)> = {
use rayon::prelude::*;
tiles.par_iter().zip(bins.par_iter()).filter_map(work).collect()
};
#[cfg(target_arch = "wasm32")]
let done: Vec<(Rect, Vec<f32>)> = tiles.iter().zip(bins.iter()).filter_map(work).collect();
for (r, v) in done {
out.write_region(r, &v);
}
out.prune();
let done: Vec<(TileCoord, Arc<Tile>)> = tiles.iter().zip(bins.iter()).filter_map(work).collect();
out.put_tiles(done);
out
}
+4
View File
@@ -30,3 +30,7 @@ cap-std = "4"
[dev-dependencies]
rmcp = { version = "3.5", default-features = false, features = ["client", "server", "macros", "transport-io"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }
# Reading back an extended attribute the write path should have preserved (#7095).
[target.'cfg(unix)'.dev-dependencies]
rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
+54 -4
View File
@@ -97,11 +97,15 @@ pub fn validate_token(token: &str) -> Result<(), AutomationError> {
}
/// Compare fixed-width tokens without an early exit on a mismatching byte.
///
/// Hex letters match in either case: [`validate_token`] accepts uppercase, and the server keeps
/// the token lowercased, so a client sending the token exactly as it was configured must still
/// authenticate (#6425). Only `A`–`Z` fold, so a non-hex byte never matches a hex digit.
pub fn token_matches(expected: &str, supplied: &str) -> bool {
if expected.len() != TOKEN_HEX_LEN || supplied.len() != TOKEN_HEX_LEN {
return false;
}
expected.bytes().zip(supplied.bytes()).fold(0u8, |different, (a, b)| different | (a ^ b)) == 0
expected.bytes().zip(supplied.bytes()).fold(0u8, |different, (a, b)| different | (a.to_ascii_lowercase() ^ b.to_ascii_lowercase())) == 0
}
/// Validate the first TCP frame without exposing any control method before authentication.
@@ -368,6 +372,45 @@ mod tests {
assert_eq!(reply["result"]["authenticated"], true);
}
fn auth_line(token: &str) -> String {
json!({"id": 1, "method": AUTH_METHOD, "params": {"token": token}}).to_string()
}
/// #6425: `validate_token` accepts uppercase hex and the server keeps the token lowercased, so a
/// client sending the token exactly as it was configured was refused.
#[test]
fn a_token_authenticates_in_any_letter_case() {
let configured = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF";
let mixed = "0123456789AbCdEf0123456789aBcDeF0123456789ABCDEF0123456789abcdef";
let expected = server_token(Some(configured), None).unwrap();
for supplied in [configured, &configured.to_ascii_lowercase(), mixed] {
let (reply, authenticated) = authentication_reply(&auth_line(supplied), &expected);
assert!(authenticated, "{supplied}: {reply}");
assert_eq!(reply["result"]["authenticated"], true);
}
// The comparison is case-insensitive in both directions.
assert!(token_matches(configured, &configured.to_ascii_lowercase()));
// A different token, or a non-hex character that only folds to a hex one, still fails.
let other = "1123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF";
let (_, authenticated) = authentication_reply(&auth_line(other), &expected);
assert!(!authenticated);
let not_hex = "0123456789ABCDEG0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF";
assert!(!token_matches(&expected, not_hex));
}
/// #6425: the same for a token file whose contents are uppercase.
#[test]
fn an_uppercase_token_file_authenticates_its_exact_contents() {
let path = std::env::temp_dir().join(format!("photocraft-control-token-upper-{}-{}.txt", std::process::id(), generate_token().unwrap()));
let contents = generate_token().unwrap().to_ascii_uppercase();
create_token_file(&path, &contents).unwrap();
let expected = server_token(None, Some(&path));
std::fs::remove_file(&path).unwrap();
let (reply, authenticated) = authentication_reply(&auth_line(&contents), &expected.unwrap());
assert!(authenticated, "{reply}");
}
#[test]
fn repeat_auth_on_an_authenticated_connection_says_so() {
let line = json!({"id": 3, "method": AUTH_METHOD, "params": {"token": "anything"}}).to_string();
@@ -437,16 +480,23 @@ mod tests {
#[test]
fn an_authenticated_connection_outlives_the_authentication_deadline() {
let (server, mut client) = tcp_pair();
// The test thread writes the first line before the deadline starts. The sender writes the
// second line once the connection has authenticated and the deadline has passed.
client.write_all(b"one\n").unwrap();
let limit = Duration::from_secs(1);
let mut reader = std::io::BufReader::new(AuthDeadlineStream::new(server, limit));
let deadline = Instant::now() + limit;
let (tx, rx) = std::sync::mpsc::channel();
let sender = std::thread::spawn(move || {
client.write_all(b"one\n").unwrap();
std::thread::sleep(Duration::from_millis(500));
rx.recv().unwrap();
std::thread::sleep((deadline + Duration::from_millis(300)).saturating_duration_since(Instant::now()));
client.write_all(b"two\n").unwrap();
});
let mut reader = std::io::BufReader::new(AuthDeadlineStream::new(server, Duration::from_millis(200)));
let mut line = String::new();
assert_eq!(read_bounded_line(&mut reader, &mut line).unwrap(), LineRead::Line);
assert_eq!(line, "one\n");
reader.get_mut().authenticated().unwrap();
tx.send(()).unwrap();
// Sent 300 ms after the deadline: only the idle timeout applies now.
assert_eq!(read_bounded_line(&mut reader, &mut line).unwrap(), LineRead::Line);
assert_eq!(line, "two\n");
+45 -2
View File
@@ -74,6 +74,13 @@ impl AuthorizedWorkspace {
/// as [`photocraft_format::atomic_write`], through the directory capability). On failure
/// the previous file is untouched and the temporary file is removed.
///
/// Replacing a file carries its extended attributes — macOS Finder tags, Linux `user.*` —
/// onto the file that takes its place (#7095), through the two open descriptors rather than
/// their paths, so nothing here reaches outside the write root to finish a write. The rest
/// of what [`photocraft_format::atomic_write`] preserves does not follow: its permission
/// step is tracked in #4963, and the Windows `ReplaceFileW` swap is path-based, which this
/// path may not use.
///
/// The parent directory must already exist. `cap-std` performs path
/// resolution and file creation relative to the held directory handle, so
/// a non-existent final target is supported without ambient path access.
@@ -85,10 +92,20 @@ impl AuthorizedWorkspace {
let tmp = parent.join(photocraft_format::atomic::temp_name(&leaf));
let mut options = OpenOptions::new();
options.write(true).create_new(true);
let written = root.dir.open_with(&tmp, &options).and_then(|mut file| {
let written = root.dir.open_with(&tmp, &options).and_then(|file| {
let mut file = file.into_std();
file.write_all(bytes)?;
#[cfg(unix)]
{
use std::os::fd::AsFd;
// Best effort, and only when there is a file being replaced: a save still
// succeeds for a document whose Finder tag could not come along.
if let Ok(old) = root.dir.open(&relative) {
let _ = photocraft_format::atomic::meta::copy_xattrs(old.as_fd(), file.as_fd());
}
}
// Falls back to a plain fsync on shares that refuse a full flush (#1336).
photocraft_format::atomic::sync_file(&file.into_std())
photocraft_format::atomic::sync_file(&file)
});
let renamed = written.and_then(|()| photocraft_format::atomic::retry_rename(RenameRetry::platform(), || root.dir.rename(&tmp, &root.dir, &relative)));
if let Err(e) = renamed {
@@ -572,6 +589,32 @@ mod tests {
assert!(temp_files(&inside).is_empty());
}
/// #7095: replacing a file through the automation path keeps the old file's extended
/// attributes, the same as a save through `atomic_write` does.
#[cfg(unix)]
#[test]
fn write_keeps_the_replaced_files_extended_attributes() {
#[cfg(target_os = "macos")]
const TAG: &str = "com.apple.metadata:_kMDItemUserTags";
#[cfg(not(target_os = "macos"))]
const TAG: &str = "user.photocraft.test";
let (inside, _, workspace) = roots("xattr");
let path = inside.join("doc.psd");
workspace.write("doc.psd", b"original").unwrap();
if rustix::fs::setxattr(&path, TAG, b"tagged", rustix::fs::XattrFlags::empty()).is_err() {
return; // a file system without extended attributes: nothing to assert
}
workspace.write("doc.psd", b"replacement, longer").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"replacement, longer");
let mut buf = [0u8; 64];
let len = rustix::fs::getxattr(&path, TAG, buf.as_mut_slice()).expect("the attribute was dropped");
assert_eq!(&buf[..len], b"tagged");
assert!(temp_files(&inside).is_empty());
}
#[cfg(unix)]
#[test]
fn write_into_read_only_folder_keeps_the_original() {
+4 -1
View File
@@ -33,6 +33,8 @@ pub(crate) struct JpegMeta {
pub exif: Option<Vec<u8>>,
pub xmp: Option<String>,
pub dpi: Option<(f32, f32)>,
/// The APP13 Photoshop image resource blocks (`8BIM` ...), segments joined, without the header.
pub photoshop: Option<Vec<u8>>,
pub adobe_transform: Option<u8>,
/// (width, height, components) from the first SOFn.
pub frame: Option<(u32, u32, u8)>,
@@ -108,6 +110,7 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta {
.or_else(|| m.xmp.as_deref().and_then(xmp_resolution))
.or_else(|| m.exif.as_deref().and_then(exif_resolution))
.or(jfif_dpi);
m.photoshop = Some(photoshop).filter(|p| !p.is_empty());
if !icc_parts.is_empty() {
icc_parts.sort_by_key(|p| p.0);
let total = icc_parts[0].1 as usize;
@@ -226,7 +229,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
}
let mut img = Image::from_raw(w, h, layout, SampleType::U8, px)?;
img.icc = meta.icc;
img.meta = Metadata { exif: meta.exif, xmp: meta.xmp, dpi: meta.dpi, ..Default::default() };
img.meta = Metadata { exif: meta.exif, xmp: meta.xmp, dpi: meta.dpi, photoshop_resources: meta.photoshop, ..Default::default() };
if end == DataEnd::Truncated {
img.warnings.push(DecodeWarning::Truncated { format: F });
}
+36 -10
View File
@@ -6,7 +6,9 @@
//! the same reader ([`super::tiff_ifd::File`]): reading a TIFF builds a block from the file's own
//! directories, writing one copies the block's directories into the file. Values are copied as
//! bytes (re-ordered when the byte orders differ), so tags PhotoCraft doesn't know survive.
//! Classic TIFF only on the reading side: an EXIF block has 4-byte offsets.
//! Classic TIFF only on the reading side: an EXIF block has 4-byte offsets. What is copied is
//! bounded by the stream's own size and a fixed cap, because entries of a hostile file can
//! overlap (see [`read`]).
use tiff::encoder::{DirectoryEncoder, TiffEncoder, TiffKind};
use tiff::tags::{Tag, Type};
@@ -27,6 +29,11 @@ const TAG_INTEROP_IFD: u16 = 40965;
const IFD0_TAGS: [u16; 7] = [270, 271, 272, 305, 306, 315, 33432];
/// At most this many entries are copied from one directory.
const MAX_FIELDS: usize = 1024;
/// At most this many value bytes are copied from one stream, over all its directories. Real EXIF
/// is far smaller (the largest Nikon maker note seen is under 1 MB); the cap leaves room for
/// that and for a few such notes. A stream never yields more than its own length either (see
/// [`read`]).
const MAX_COPIED_BYTES: usize = 4 * 1024 * 1024;
/// One entry with its value bytes in the byte order of the stream it came from.
#[derive(Clone, Debug, PartialEq)]
@@ -53,13 +60,22 @@ impl ExifDirs {
}
}
fn fields(f: &File<'_>, ifd: &Ifd, keep: impl Fn(u16) -> bool) -> Vec<Field> {
ifd.entries
.iter()
.filter(|e| keep(e.tag) && !matches!(e.tag, TAG_EXIF_IFD | TAG_GPS_IFD | TAG_INTEROP_IFD))
.filter_map(|e| Some(Field { tag: e.tag, ty: e.ty, count: u32::try_from(e.count).ok()?, value: f.data(e)?.to_vec() }))
.take(MAX_FIELDS)
.collect()
/// The entries of `ifd` that `keep` accepts, with their values copied. An entry's value only has
/// to lie inside the file, so entries may overlap: `budget` is the number of value bytes that may
/// still be copied (shared by all the directories of one stream), and an entry whose value does
/// not fit in what is left is skipped, so later, smaller entries can still be kept.
fn fields(f: &File<'_>, ifd: &Ifd, budget: &mut usize, keep: impl Fn(u16) -> bool) -> Vec<Field> {
let mut out = Vec::new();
for e in ifd.entries.iter().filter(|e| keep(e.tag) && !matches!(e.tag, TAG_EXIF_IFD | TAG_GPS_IFD | TAG_INTEROP_IFD)) {
if out.len() >= MAX_FIELDS {
break;
}
let (Ok(count), Some(value)) = (u32::try_from(e.count), f.data(e)) else { continue };
let Some(left) = budget.checked_sub(value.len()) else { continue };
*budget = left;
out.push(Field { tag: e.tag, ty: e.ty, count, value: value.to_vec() });
}
out
}
fn sub(f: &File<'_>, ifd: &Ifd, tag: u16) -> Option<Ifd> {
@@ -69,14 +85,24 @@ fn sub(f: &File<'_>, ifd: &Ifd, tag: u16) -> Option<Ifd> {
/// The EXIF parts of the classic TIFF stream `b` (a TIFF file, or an EXIF block without its
/// `Exif\0\0` prefix): IFD0's descriptive tags and the Exif and GPS directories.
///
/// The values copied add up to at most [`MAX_COPIED_BYTES`] and to at most `b.len()`: the values
/// of a well-formed stream are distinct bytes of it, while a hostile one can have many entries
/// point at the same bytes and so ask for far more than its size. Entries that do not fit in what
/// is left are left out (the small descriptive directories come first, so a huge maker note
/// cannot crowd out the GPS position).
pub(crate) fn read(b: &[u8]) -> Option<ExifDirs> {
let f = File::parse(b)?;
if f.big {
return None;
}
let ifd0 = f.ifd(f.first_ifd)?;
let dir = |tag: u16| sub(&f, &ifd0, tag).map(|d| fields(&f, &d, |_| true)).unwrap_or_default();
Some(ExifDirs { le: f.le, ifd0: fields(&f, &ifd0, |t| IFD0_TAGS.contains(&t)), exif: dir(TAG_EXIF_IFD), gps: dir(TAG_GPS_IFD) })
let mut budget = MAX_COPIED_BYTES.min(b.len());
let ifd0_fields = fields(&f, &ifd0, &mut budget, |t| IFD0_TAGS.contains(&t));
let mut dir = |tag: u16| sub(&f, &ifd0, tag).map(|d| fields(&f, &d, &mut budget, |_| true)).unwrap_or_default();
let gps = dir(TAG_GPS_IFD);
let exif = dir(TAG_EXIF_IFD);
Some(ExifDirs { le: f.le, ifd0: ifd0_fields, exif, gps })
}
/// Bytes per element whose order a byte-order change reverses: a RATIONAL is two LONGs.
+19 -7
View File
@@ -285,7 +285,8 @@ pub fn decode_wbmp(bytes: &[u8]) -> Result<(u32, u32, Vec<bool>), CodecError> {
}
/// JPEG from 8-bit RGB (`rgb.len() == 3·w·h`): quality 1..=100, optional progressive scans and
/// optimised Huffman tables (Save for Web's "Optimized"), optional ICC profile, density and XMP.
/// optimised Huffman tables (Save for Web's "Optimized"), optional ICC profile, density, EXIF and
/// XMP. EXIF that doesn't fit in one segment is left out (see [`jpeg_exif_fits`]).
#[allow(clippy::too_many_arguments)]
pub fn encode_jpeg_rgb8(
width: u32,
@@ -296,6 +297,7 @@ pub fn encode_jpeg_rgb8(
optimized: bool,
icc: Option<&[u8]>,
dpi: Option<f32>,
exif: Option<&[u8]>,
xmp: Option<&str>,
) -> Result<Vec<u8>, CodecError> {
let e = |e: jpeg_encoder::EncodingError| CodecError::encode(Format::Jpeg, e);
@@ -319,9 +321,14 @@ pub fn encode_jpeg_rgb8(
let v = d.round().min(65535.0) as u16;
enc.set_density(jpeg_encoder::Density::Inch { x: v, y: v });
}
let ppi = dpi.filter(|d| *d >= 1.0).map(|d| (d, d));
// Upright, without the source's thumbnail, at the JFIF resolution, as Save As writes it.
if let Some(seg) = exif.and_then(|x| crate::codecs::jpeg::exif_segment(x, ppi)) {
enc.add_app_segment(1, &seg).map_err(e)?;
}
if let Some(x) = xmp {
// Its `tiff:` resolution, if any, says what the JFIF density says (#1691).
let x = crate::resolution::export_xmp(x, dpi.filter(|d| *d >= 1.0).map(|d| (d, d)));
let x = crate::resolution::export_xmp(x, ppi);
let mut seg = b"http://ns.adobe.com/xap/1.0/\0".to_vec();
seg.extend_from_slice(x.as_bytes());
enc.add_app_segment(1, &seg).map_err(e)?;
@@ -333,6 +340,11 @@ pub fn encode_jpeg_rgb8(
Ok(out)
}
/// Whether [`encode_jpeg_rgb8`] can write `exif` at `dpi` (it must fit in one APP1 segment).
pub fn jpeg_exif_fits(exif: &[u8], dpi: Option<f32>) -> bool {
crate::codecs::jpeg::exif_segment(exif, dpi.filter(|d| *d >= 1.0).map(|d| (d, d))).is_some()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -359,7 +371,7 @@ mod tests {
let rgb: Vec<u8> = (0..16 * 16 * 3).map(|i| (i * 37 % 256) as u8).collect();
for (q, want) in [(1, (2, 2)), (50, (2, 2)), (51, (1, 1)), (60, (1, 1)), (89, (1, 1)), (100, (1, 1))] {
for progressive in [false, true] {
let bytes = encode_jpeg_rgb8(16, 16, &rgb, q, progressive, false, None, None, None).unwrap();
let bytes = encode_jpeg_rgb8(16, 16, &rgb, q, progressive, false, None, None, None, None).unwrap();
assert_eq!(luma_sampling(&bytes), Some(want), "quality {q} progressive {progressive}");
}
}
@@ -428,8 +440,8 @@ mod tests {
#[test]
fn progressive_jpeg_decodes() {
let rgb: Vec<u8> = (0..64 * 48 * 3).map(|i| (i % 251) as u8).collect();
let base = encode_jpeg_rgb8(64, 48, &rgb, 80, false, false, None, Some(72.0), Some("<x:xmpmeta/>")).unwrap();
let prog = encode_jpeg_rgb8(64, 48, &rgb, 80, true, true, None, None, None).unwrap();
let base = encode_jpeg_rgb8(64, 48, &rgb, 80, false, false, None, Some(72.0), None, Some("<x:xmpmeta/>")).unwrap();
let prog = encode_jpeg_rgb8(64, 48, &rgb, 80, true, true, None, None, None, None).unwrap();
assert_ne!(base, prog);
assert_eq!(crate::decode(&base).unwrap().meta.xmp.as_deref(), Some("<x:xmpmeta/>"));
// SOF2 marks a progressive frame.
@@ -442,7 +454,7 @@ mod tests {
fn web_jpeg_xmp_resolution_follows_the_density() {
let rgb = vec![100u8; 8 * 8 * 3];
let xmp = r#"<rdf:Description tiff:XResolution="300/1" tiff:YResolution="300/1"/>"#;
let out = encode_jpeg_rgb8(8, 8, &rgb, 80, false, false, None, Some(72.0), Some(xmp)).unwrap();
let out = encode_jpeg_rgb8(8, 8, &rgb, 80, false, false, None, Some(72.0), None, Some(xmp)).unwrap();
let img = crate::decode(&out).unwrap();
assert_eq!(img.meta.dpi, Some((72.0, 72.0)));
assert_eq!(img.meta.xmp.as_deref().and_then(crate::xmp_resolution), Some((72.0, 72.0)));
@@ -461,7 +473,7 @@ mod subsampling_tests {
let rgb: Vec<u8> = (0..w * h).flat_map(|i| [((i % w) * 4) as u8, 76, ((i / w) * 5) as u8]).collect();
for q in [30, 60, 95] {
for (prog, opt) in [(false, false), (false, true), (true, false), (true, true)] {
let bytes = encode_jpeg_rgb8(w, h, &rgb, q, prog, opt, None, None, None).unwrap();
let bytes = encode_jpeg_rgb8(w, h, &rgb, q, prog, opt, None, None, None, None).unwrap();
let ours = crate::decode(&bytes).unwrap().convert(crate::ChannelLayout::Rgb, crate::SampleType::U8);
let err = ours.data().iter().zip(&rgb).map(|(a, b)| i32::from(*a).abs_diff(i32::from(*b))).max().unwrap();
assert!(err < 24, "q{q} progressive={prog} optimized={opt}: max error {err}");
+94
View File
@@ -166,3 +166,97 @@ fn no_exif_is_written_without_embed_metadata() {
let tiff = encode(&img, Format::Tiff, &EncodeOptions { embed_metadata: false, ..Default::default() }).unwrap();
assert_eq!(decode(&tiff).unwrap().meta.exif, None);
}
// ---------------------------------------------------------------------------
// Bounded copying: an entry's value only has to lie inside the file, so a hostile file can have
// many entries point at the same bytes.
// ---------------------------------------------------------------------------
/// A valid 1x1 gray TIFF whose Exif directory has `entries` UNDEFINED entries of `count` bytes
/// that all point at the same `count` bytes: the file is about `count` bytes long and asks to
/// copy `entries * count`.
fn overlapping_tiff(entries: usize, count: u32) -> Vec<u8> {
let entry = |tag: u16, ty: u16, count: u32, value: u32| {
[tag.to_le_bytes().to_vec(), ty.to_le_bytes().to_vec(), count.to_le_bytes().to_vec(), value.to_le_bytes().to_vec()].concat()
};
let at_exif = 8 + 2 + 12 * 10 + 4;
let data_at = at_exif + 2 + 12 * entries + 4;
let mut out = b"II".to_vec();
out.extend(42u16.to_le_bytes());
out.extend(8u32.to_le_bytes());
out.extend(10u16.to_le_bytes());
for (tag, ty, value) in
[(256, 3, 1), (257, 3, 1), (258, 3, 8), (259, 3, 1), (262, 3, 1), (273, 4, 0), (277, 3, 1), (278, 3, 1), (279, 4, 1), (34665, 4, at_exif as u32)]
{
out.extend(entry(tag, ty, 1, value));
}
out.extend(0u32.to_le_bytes());
out.extend((entries as u16).to_le_bytes());
for i in 0..entries {
out.extend(entry(i as u16 + 1, 7, count, data_at as u32));
}
out.extend(0u32.to_le_bytes());
out.extend(vec![0x5A; count as usize]);
out
}
#[test]
fn overlapping_field_values_are_bounded() {
// About 62 KB on disk; copied entry by entry it would be 1,000 x 50,000 bytes.
let tiff = overlapping_tiff(1000, 50_000);
assert!(tiff.len() < 64 * 1024);
let img = decode(&tiff).expect("the image itself is fine");
assert_eq!(img.dimensions(), (1, 1));
let exif = img.meta.exif.expect("the first entries are kept");
assert!(exif.len() <= 2 * tiff.len(), "{} bytes of EXIF from a {} byte file", exif.len(), tiff.len());
}
#[test]
fn overlapping_field_values_in_an_exif_block_are_bounded_on_export() {
// The same block as an image's EXIF: the writer reads it with the same code.
let block = overlapping_tiff(1000, 50_000);
let mut img = Image::from_raw(2, 2, ChannelLayout::Gray, SampleType::U8, vec![0; 4]).unwrap();
img.meta.exif = Some(block.clone());
let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
assert!(tiff.len() <= 2 * block.len(), "a {} byte block wrote a {} byte file", block.len(), tiff.len());
}
/// An EXIF block with a maker note of `len` bytes, an exposure time and a GPS latitude reference.
fn block_with_maker_note(le: bool, len: usize) -> Vec<u8> {
let b = Block { le };
b.build(
vec![(271, 2, 4, b"Cam\0".to_vec())],
vec![(33434, 5, 1, b.rational(1, 125)), (37500, 7, len as u32, (0..len).map(|i| (i * 7) as u8).collect())],
vec![(1, 2, 2, b"N\0".to_vec())],
)
}
#[test]
fn large_maker_notes_still_survive() {
// Nikon maker notes run from 100 KB to nearly 1 MB.
for len in [200 * 1024, 1000 * 1024] {
let block = block_with_maker_note(true, len);
let mut img = Image::from_raw(4, 3, ChannelLayout::Rgb, SampleType::U8, vec![90; 36]).unwrap();
img.meta.exif = Some(block.clone());
let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
let back = decode(&tiff).unwrap().meta.exif.expect("EXIF read back");
let (ble, _, bexif, bgps) = dirs(&back);
let (ole, _, oexif, ogps) = dirs(&block);
assert_eq!(normalized(&bexif, ble), normalized(&oexif, ole), "{len} byte maker note");
assert_eq!(normalized(&bgps, ble), normalized(&ogps, ole));
}
}
#[test]
fn a_field_beyond_the_cap_is_dropped_and_the_rest_kept() {
let block = block_with_maker_note(false, 6 * 1024 * 1024);
let mut img = Image::from_raw(2, 2, ChannelLayout::Gray, SampleType::U8, vec![0; 4]).unwrap();
img.meta.exif = Some(block);
let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
assert!(tiff.len() < 1024 * 1024, "{} bytes", tiff.len());
let back = decode(&tiff).unwrap().meta.exif.expect("EXIF read back");
let (_, ifd0, exif, gps) = dirs(&back);
assert_eq!(exif.iter().map(|e| e.0).collect::<Vec<_>>(), [33434], "the exposure time stays, the 6 MiB maker note goes");
assert_eq!(gps.iter().map(|e| e.0).collect::<Vec<_>>(), [1]);
assert_eq!(ifd0.iter().map(|e| e.0).collect::<Vec<_>>(), [271]);
}
+5
View File
@@ -43,6 +43,11 @@ roxmltree = "0.20"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tempfile = "3"
# `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).
[target.'cfg(windows)'.dependencies]
same-file = "1"
# Printing on Unix: an IPP client for CUPS (pure Rust); the web build cannot print.
[target.'cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies]
photocraft-ipp = { workspace = true }
+2 -2
View File
@@ -18,13 +18,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let settings = WebSettings::from_params(&json!({"format": "gif", "colors": 128, "dither": "diffusion"}), "bench")?;
let rect = Rect::new(0, 0, w as i32, h as i32);
let started = Instant::now();
let original = optimize(&pixels, w, rect, &settings, None, None, 72.0, false)?;
let original = optimize(&pixels, w, rect, &settings, None, None, None, 72.0, false)?;
println!("24 MP generated palette: {:.1} ms", started.elapsed().as_secs_f64() * 1000.0);
let mut edited = settings;
edited.color_table = Some(original.color_table);
edited.color_table_edits.insert(0, [0, 255, 0]);
let started = Instant::now();
let result = optimize(&pixels, w, rect, &edited, None, None, 72.0, false)?;
let result = optimize(&pixels, w, rect, &edited, None, None, None, 72.0, false)?;
println!("24 MP edited fixed palette: {:.1} ms ({} bytes)", started.elapsed().as_secs_f64() * 1000.0, result.bytes.len());
Ok(())
}
+3 -1
View File
@@ -270,6 +270,8 @@ pub(crate) fn adjust_as_smart_filter(s: &mut Session, kind: &str, label: &str, p
if !smart {
return Ok(false);
}
// A pixel or full lock refuses the smart filter, as for `filter.*` on a smart object.
crate::commands::check_pixels_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?;
// The recorded params are the command's own, minus the engine's private `__kind` key.
let mut params = p.clone();
if let Value::Object(m) = &mut params {
@@ -347,7 +349,7 @@ fn shadows_highlights_params(p: &Value) -> ShadowsHighlights {
fn replace_color(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "image.adjustments.replaceColor";
let c = crate::commands::color_param(p, "color", s.tools.foreground);
let c = crate::commands::color_param(CMD, p, "color", s.tools.foreground)?;
let fuzz = num(p, "fuzziness", 40.0).clamp(0.0, 200.0);
let (h, sat, l) = (num(p, "hue", 0.0).clamp(-180.0, 180.0), num(p, "saturation", 0.0).clamp(-100.0, 100.0), num(p, "lightness", 0.0).clamp(-100.0, 100.0));
// Localized Color Clusters, as in Select › Color Range: the colour only matches within Range
+20
View File
@@ -479,6 +479,26 @@ fn adjustment_smart_filters_take_a_selection_as_their_mask() {
assert_eq!(at(&now, 40, 16), at(&original, 40, 16), "outside the mask the composite is unchanged");
}
/// #5655: as for `filter.*` smart filters, a pixel or full lock refuses an adjustment smart
/// filter, leaving the layer and the history as they were.
#[test]
fn locked_smart_objects_refuse_adjustment_smart_filters() {
let adjustments =
[("image.adjustments.invert", json!({})), ("image.adjustments.shadowsHighlights", json!({"shadowAmount": 100, "blackClip": 0, "whiteClip": 0}))];
for lock in [json!({"all": true}), json!({"pixels": true})] {
for (cmd, p) in &adjustments {
let mut s = smart_session();
s.execute("layer.lockLayers", lock.clone()).unwrap();
let (steps, flat) = (s.active().unwrap().history.past_len(), flatten(&s));
let r = s.execute(cmd, p.clone());
assert!(r.is_err(), "{cmd} added a smart filter to a smart object locked with {lock}: {r:?}");
assert!(smart_filters_of(&s).is_empty(), "{cmd} {lock}: nothing recorded");
assert_eq!(s.active().unwrap().history.past_len(), steps, "{cmd} {lock}: no history step");
assert_eq!(flatten(&s), flat, "{cmd} {lock}: pixels untouched");
}
}
}
/// A wrong-typed value errors before anything is recorded (never a panic), and the adjustments
/// that can't re-render from a source (Replace Color, Match Color) stay off a smart object.
#[test]
+17 -8
View File
@@ -722,10 +722,12 @@ fn group_index(d: &Document, p: &Value) -> Option<usize> {
(i < d.measurement.count_groups.len()).then_some(i)
}
fn color_of(p: &Value, key: &str) -> Option<Color> {
p.get(key)?;
let c = crate::commands::color_param(p, key, [1.0, 0.0, 0.0, 1.0]);
Some(Color::rgb(c[0], c[1], c[2]))
fn color_of(cmd: &str, p: &Value, key: &str) -> Result<Option<Color>> {
if p.get(key).is_none() {
return Ok(None);
}
let c = crate::commands::color_param(cmd, p, key, [1.0, 0.0, 0.0, 1.0])?;
Ok(Some(Color::rgb(c[0], c[1], c[2])))
}
/// Photoshop's colours for new count groups, in order.
@@ -755,7 +757,12 @@ fn count_add(s: &mut Session, p: &Value) -> Result<Value> {
if !at[0].is_finite() || !at[1].is_finite() {
return Err(bad("count.add", "coordinates must be finite"));
}
let gi = p.get("group").and_then(Value::as_u64).map(|v| v as usize);
let gi = p.get("group").and_then(Value::as_u64).map(|v| usize::try_from(v).map_err(|_| bad("count.add", "no such group"))).transpose()?;
// The first marker creates group zero, but an explicit target must never be redirected.
let group_count = doc(s)?.measurement.count_groups.len().max(1);
if gi.is_some_and(|i| i >= group_count) {
return Err(bad("count.add", "no such group"));
}
let n = s.edit("Count", |d, _| {
if d.measurement.count_groups.is_empty() {
let g = new_group(d, None, None);
@@ -840,7 +847,7 @@ fn count_clear(s: &mut Session, p: &Value) -> Result<Value> {
fn count_new_group(s: &mut Session, p: &Value) -> Result<Value> {
let name = p.get("name").and_then(Value::as_str).map(str::to_string);
let color = color_of(p, "color");
let color = color_of("count.newGroup", p, "color")?;
s.edit("New Count Group", |d, _| {
let g = new_group(d, name, color);
d.measurement.count_groups.push(g);
@@ -856,7 +863,9 @@ fn count_delete_group(s: &mut Session, p: &Value) -> Result<Value> {
s.edit("Delete Count Group", |d, _| {
d.measurement.count_groups.remove(g);
let n = d.measurement.count_groups.len();
d.measurement.active_count_group = d.measurement.active_count_group.min(n.saturating_sub(1));
// Removing a group before the active one shifts it down a slot.
let a = d.measurement.active_count_group;
d.measurement.active_count_group = (if g < a { a - 1 } else { a }).min(n.saturating_sub(1));
Ok(())
})?;
Ok(count_json(doc(s)?.as_ref()))
@@ -887,7 +896,7 @@ fn count_set_group(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(n) = p.get("name").and_then(Value::as_str) {
grp.name = n.to_string();
}
if let Some(c) = color_of(p, "color") {
if let Some(c) = color_of(CMD, p, "color")? {
grp.color = c;
}
if let Some(v) = whole_size(CMD, p, "markerSize", 1, 10)? {
+65
View File
@@ -291,6 +291,27 @@ fn count_groups_markers_and_undo() {
assert!(s.execute("count.add", json!({"x": 1})).is_err());
}
#[test]
fn deleting_an_earlier_count_group_keeps_the_active_group() {
let mut s = session(100, 100, 8);
s.execute("count.add", json!({"x": 10, "y": 10})).unwrap();
for _ in 0..3 {
s.execute("count.newGroup", json!({})).unwrap();
}
s.execute("count.setGroup", json!({"group": 2})).unwrap();
let r = s.execute("count.deleteGroup", json!({"group": 0})).unwrap();
assert_eq!(r["activeGroup"], 1);
assert_eq!(r["groups"][1]["name"], "Count Group 3");
// A later group leaves the active index alone.
let r = s.execute("count.deleteGroup", json!({"group": 2})).unwrap();
assert_eq!(r["activeGroup"], 1);
assert_eq!(r["groups"][1]["name"], "Count Group 3");
// Deleting the active last group selects the new last group.
let r = s.execute("count.deleteGroup", json!({})).unwrap();
assert_eq!(r["activeGroup"], 0);
assert_eq!(r["groups"][0]["name"], "Count Group 2");
}
#[test]
fn log_delete_and_csv_export() {
let mut s = session(10, 10, 8);
@@ -470,3 +491,47 @@ fn count_set_group_rejects_sizes_that_are_not_whole_numbers() {
assert_eq!((g.marker_size, g.label_size), (3, 12), "a rejected call changes nothing");
assert_eq!(s.active().unwrap().history.past_len(), past);
}
#[test]
fn count_add_rejects_unknown_groups_without_changing_the_document() {
for groups in [0, 1, 3] {
for group in [(groups as u64).max(1), u64::MAX] {
let mut s = session(10, 10, 8);
for _ in 0..groups {
s.execute("count.newGroup", json!({})).unwrap();
}
let before = d(&s);
let history = s.active().unwrap().history.past_len();
let journal = s.journal.len();
let error = s.execute("count.add", json!({"x": 2, "y": 3, "group": group})).unwrap_err();
assert!(error.to_string().contains("no such group"), "{error}");
assert!(Arc::ptr_eq(&before, &d(&s)), "an invalid target must not create a group or add a marker");
assert_eq!(s.active().unwrap().history.past_len(), history);
assert_eq!(s.journal.len(), journal);
}
}
}
#[test]
fn count_add_keeps_first_group_creation_and_targets_the_requested_group() {
let mut s = session(10, 10, 8);
// Group zero can be requested before the first marker creates it.
let r = s.execute("count.add", json!({"x": 2, "y": 3, "group": 0})).unwrap();
assert_eq!(r["groups"][0]["points"], json!([[2.0, 3.0]]));
s.execute("count.newGroup", json!({})).unwrap();
let before = d(&s).measurement.clone();
let history = s.active().unwrap().history.past_len();
let r = s.execute("count.add", json!({"x": 4, "y": 5, "group": 0})).unwrap();
assert_eq!(r["activeGroup"], 1);
assert_eq!(r["groups"][0]["points"], json!([[2.0, 3.0], [4.0, 5.0]]));
assert_eq!(r["groups"][1]["count"], 0);
assert_eq!(s.active().unwrap().history.past_len(), history + 1);
let after = d(&s).measurement.clone();
assert!(s.undo());
assert_eq!(d(&s).measurement, before);
assert!(s.redo());
assert_eq!(d(&s).measurement, after);
// Omitting the group still uses the active group.
let r = s.execute("count.add", json!({"x": 6, "y": 7})).unwrap();
assert_eq!(r["groups"][1]["points"], json!([[6.0, 7.0]]));
}
+10 -5
View File
@@ -9,7 +9,7 @@
use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
use photocraft_doc::{Artboard, ArtboardBackground, Document, Layer, LayerContent, LayerId, Size};
use photocraft_geom::Rect;
use photocraft_geom::{Affine, Rect};
use photocraft_raster::Surface;
use serde_json::{Value, json};
@@ -92,10 +92,12 @@ fn preset_size(name: &str) -> Option<(u32, u32)> {
}
fn background_param(p: &Value, cmd: &str) -> Result<Option<ArtboardBackground>> {
let custom = p.get("color").map(|_| {
let c = color_param(p, "color", [1.0; 4]);
ArtboardBackground::Custom(Color::rgba(c[0], c[1], c[2], c[3]))
});
let custom = if p.get("color").is_some() {
let c = color_param(cmd, p, "color", [1.0; 4])?;
Some(ArtboardBackground::Custom(Color::rgba(c[0], c[1], c[2], c[3])))
} else {
None
};
Ok(match p.get("background").and_then(Value::as_str) {
None => custom,
Some("white") => Some(ArtboardBackground::White),
@@ -504,6 +506,9 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Result<Option<Document>
one.layer_comps.clear();
one.last_applied_comp = None;
one.last_document_state = None;
// Paths, notes, slices and Count/Ruler marks move with the board. This also shifts
// `one.guides`, but they are rebuilt below from the source's, so nothing moves twice.
crate::canvas_geom::transform_doc_marks(&mut one, &Affine::translate(f64::from(dx), f64::from(dy)));
let shift = |v: &[f64], o: i32, len: u32| v.iter().map(|g| g - f64::from(o)).filter(|g| *g > 0.0 && *g < f64::from(len)).collect::<Vec<_>>();
one.guides.vertical = shift(&doc.guides.vertical, r.x0, r.width());
one.guides.horizontal = shift(&doc.guides.horizontal, r.y0, r.height());
+27
View File
@@ -331,6 +331,33 @@ fn export_rejects_a_board_too_far_from_the_origin() {
assert_eq!(one.artboards()[0].2.rect, Rect::new(0, 0, 50, 50));
}
/// Artboards to Files moves paths, notes, slices and Count/Ruler marks with the board, like its
/// layers and guides, so they land on the same pixels in the exported file.
#[test]
fn artboard_export_moves_paths_notes_slices_and_marks_with_the_board() {
use photocraft_doc::{CountGroup, NamedPath, Note, Path, Slice, Subpath};
let mut s = session(8);
s.execute("layer.new.artboard", json!({"x": 200, "y": 100, "width": 50, "height": 50})).unwrap();
s.edit("marks", |d, _| {
d.paths.push(NamedPath { name: "P".into(), path: Path::new(vec![Subpath::polygon(&[(210.0, 110.0), (240.0, 110.0), (240.0, 140.0)])]), psd_raw: None });
d.work_path = Some(Path::new(vec![Subpath::polygon(&[(205.0, 105.0), (215.0, 105.0), (215.0, 115.0)])]));
d.notes.push(Note { position: [220.0, 120.0], popup: [220.0, 120.0, 260.0, 160.0], ..Default::default() });
d.slices.list.push(Slice { id: 1, rect: Rect::new(210, 110, 230, 130), ..Default::default() });
d.measurement.count_groups.push(CountGroup { points: vec![[225.0, 125.0]], ..Default::default() });
Ok(())
})
.unwrap();
let one = artboard_document(doc(&s), doc(&s).artboards()[0].0).unwrap().unwrap();
let k = &one.paths[0].path.subpaths[0].knots[0].anchor;
assert_eq!((k.x, k.y), (10.0, 10.0));
let w = &one.work_path.as_ref().unwrap().subpaths[0].knots[0].anchor;
assert_eq!((w.x, w.y), (5.0, 5.0));
assert_eq!(one.notes[0].position, [20.0, 20.0]);
assert_eq!(one.notes[0].popup, [20.0, 20.0, 60.0, 60.0]);
assert_eq!(one.slices.list[0].rect, Rect::new(10, 10, 30, 30));
assert_eq!(one.measurement.count_groups[0].points, vec![[25.0, 25.0]]);
}
/// #1531: a board 40×40 at (10, 10) holding a red square at (10..30)², the artboard active.
fn board_with_square(s: &mut Session) -> LayerId {
add_square(s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]);
+22 -6
View File
@@ -881,11 +881,18 @@ macro_rules! ev {
Some(m) => step($id, Value::Object(m)),
None => Mapped::Unsupported { harmless: false },
},
to: |_, p| fields_to(p, $fields, desc("null")),
to: |_, p| if pixel_target(p) { fields_to(p, $fields, desc("null")) } else { None },
}
};
}
/// Whether `p` edits the layer's pixels: no `"target"` or `"target":"pixels"`. Photoshop's
/// descriptor for a plain event has no field for a mask, Quick Mask or channel target, so such
/// a step can't be exported faithfully.
fn pixel_target(p: &Value) -> bool {
p.get("target").is_none_or(|t| t.as_str() == Some("pixels"))
}
const INTERPOLATION: &[(&str, &str)] = &[
("Bcbc", "bicubic"),
("Blnr", "bilinear"),
@@ -1577,7 +1584,12 @@ fn close_from(d: &Descriptor) -> Mapped {
if get_enum(d, "Svng").as_deref() == Some("Ys") { steps(vec![("file.save", json!({})), ("file.close", json!({}))]) } else { none("file.close") }
}
fn close_to(_: &str, _: &Value) -> Option<Descriptor> {
/// A Close of an explicit document has no mapping here: written as a plain Close it would
/// close the active document on playback, so it is left to `skipUnsupported`.
fn close_to(_: &str, p: &Value) -> Option<Descriptor> {
if p.get("document").is_some_and(|d| !d.is_null()) {
return None;
}
Some(desc("null").with("Svng", enm("YsN ", "N ")))
}
@@ -1608,14 +1620,17 @@ fn transform_from(d: &Descriptor) -> Mapped {
if d.get("Skew").is_some() || d.get("Usng").is_some() {
return unsupported;
}
let geometry_only = p.keys().all(|k| k == "dx" || k == "dy");
// A whole-pixel move is a plain `layer.translate`; a fractional one needs `edit.transform`
// to keep its sub-pixel placement and interpolation.
let whole_pixels = ["dx", "dy"].iter().all(|k| p.get(*k).and_then(Value::as_f64).is_none_or(|v| v.fract() == 0.0));
let geometry_only = p.keys().all(|k| k == "dx" || k == "dy") && whole_pixels;
match (ref_class(r).as_deref(), target(r)) {
(Some("Chnl"), Target::Property(prop)) if prop == "fsel" => step("select.transformSelection", Value::Object(p)),
(Some("Lyr"), _) => {
let Some(mut lp) = layer_target(r) else { return unsupported };
if geometry_only {
lp.insert("dx".into(), p.get("dx").and_then(Value::as_f64).unwrap_or(0.0).round().into());
lp.insert("dy".into(), p.get("dy").and_then(Value::as_f64).unwrap_or(0.0).round().into());
lp.insert("dx".into(), p.get("dx").and_then(Value::as_f64).unwrap_or(0.0).into());
lp.insert("dy".into(), p.get("dy").and_then(Value::as_f64).unwrap_or(0.0).into());
return step("layer.translate", Value::Object(lp));
}
lp.extend(p);
@@ -3259,7 +3274,8 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
#[cfg(not(target_arch = "wasm32"))]
fn write_file(path: &str, bytes: &[u8]) -> std::io::Result<()> {
std::fs::write(path, bytes)
// Atomic replacement (temporary file + rename): a failed write keeps the previous ATN (#7290).
photocraft_format::atomic_write(std::path::Path::new(path), bytes)
}
#[cfg(target_arch = "wasm32")]
+85 -1
View File
@@ -585,6 +585,33 @@ fn save_writes_the_file_and_the_set_of_the_selected_action() {
std::fs::remove_dir_all(&dir).ok();
}
/// #7290: saving over an existing ATN must replace it atomically (a temporary file renamed over
/// it), never truncate and rewrite it in place, so a write that fails partway (a full disk)
/// leaves the previously valid file readable. A handle opened on the old file still sees the old
/// bytes after an atomic replacement; an in-place rewrite changes them under it.
#[cfg(unix)]
#[test]
fn save_over_an_existing_file_never_rewrites_it_in_place() {
use std::io::Read;
let mut s = Session::new();
s.actions.list.push(Action::new("Owned", vec![("select.all".into(), json!({}))]));
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("Owned.atn");
let p = path.to_string_lossy().to_string();
s.execute("actions.save", json!({"path": p})).unwrap();
let before = std::fs::read(&path).unwrap();
let mut old = std::fs::File::open(&path).unwrap();
s.actions.list.push(Action::new("Second", vec![("select.all".into(), json!({}))]));
s.execute("actions.save", json!({"path": p})).unwrap();
let mut seen = Vec::new();
old.read_to_end(&mut seen).unwrap();
assert_eq!(seen, before, "the existing ATN was rewritten in place");
let after = atn::parse(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(after.actions.len(), 2);
let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect();
assert_eq!(names, vec![std::ffi::OsString::from("Owned.atn")], "no temporary file is left behind");
}
#[test]
fn layer_param_accepts_a_name() {
let mut s = Session::new();
@@ -622,7 +649,7 @@ fn remaining_events_import_in_their_photoshop_shapes() {
let moved = desc("null")
.with("null", target_ref("Lyr "))
.with("FTcs", enm("QCSt", "Qcsa"))
.with("Ofst", D::Descriptor(desc("Ofst").with("Hrzn", px(-57.4)).with("Vrtc", px(12.0))))
.with("Ofst", D::Descriptor(desc("Ofst").with("Hrzn", px(-57.0)).with("Vrtc", px(12.0))))
.with("Intr", enm("Intp", "Bcbc"));
let scaled = desc("null")
.with("null", target_ref("Lyr "))
@@ -1005,3 +1032,60 @@ fn remove_white_clears_the_targeted_layer_not_the_converted_background() {
assert!(!st.doc.is_background(bottom.id), "the Background became a normal layer");
assert!(bottom.surface().unwrap().sample_channel(2, 2, 1) > 0.99, "and kept its pixels");
}
/// Photoshop's Close has no document target: a Close of a specific document must not be
/// exported as a plain Close, which would close the active document on playback.
#[test]
fn close_with_document_target_is_not_exported_as_plain_close() {
let targeted = Action { name: "Probe".into(), steps: vec![("file.close".into(), json!({"document": 0}))], ..Default::default() };
assert!(export("Audit4", &[&targeted], &[], false).is_err());
let (_, skipped) = export("Audit4", &[&targeted], &[], true).unwrap();
assert_eq!(skipped, vec![Skipped { action: "Probe".into(), step: 0, id: "file.close".into() }]);
let plain = Action { name: "Plain".into(), steps: vec![("file.close".into(), json!({}))], ..Default::default() };
let (bytes, skipped) = export("Audit4", &[&plain], &[], false).unwrap();
assert!(skipped.is_empty());
let imported = import(&bytes).unwrap();
assert_eq!(imported.actions[0].steps, vec![("file.close".to_string(), json!({}))]);
}
/// A translation-only Free Transform with a fractional offset must not collapse into an
/// integer `layer.translate`: the sub-pixel placement and interpolation have to survive.
#[test]
fn fractional_translation_only_transform_keeps_offset_and_interpolation() {
let params = json!({"dx": 0.5, "dy": 0, "interpolation": "bilinear"});
let d = transform_to("edit.transform", &params).unwrap();
let file = AtnFile {
name: UnicodeString::new_nul("Frac"),
expanded: false,
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item("transform", "Transform", Some(d))], ..Default::default() }],
warnings: vec![],
};
let imp = import(&atn::write(&file).unwrap()).unwrap();
assert!(imp.unsupported.is_empty());
let steps = &imp.actions[0].steps;
assert_eq!(steps.len(), 1);
assert_eq!(steps[0].0, "edit.transform");
assert_eq!(steps[0].1.get("dx").and_then(Value::as_f64), Some(0.5));
assert_eq!(steps[0].1.get("interpolation"), Some(&json!("bilinear")));
}
/// A filter recorded against a layer mask must not export as a plain filter that edits the
/// layer's pixels on replay: Photoshop's descriptor has no field for PhotoCraft's `target`.
#[test]
fn add_noise_with_mask_target_is_not_exported_as_pixel_filter() {
let masked = Action {
name: "Probe".into(),
steps: vec![("filter.noise.addNoise".into(), json!({"amount": 75, "seed": 123, "target": "mask"}))],
..Default::default()
};
assert!(export("Audit", &[&masked], &[], false).is_err());
let (_, skipped) = export("Audit", &[&masked], &[], true).unwrap();
assert_eq!(skipped, vec![Skipped { action: "Probe".into(), step: 0, id: "filter.noise.addNoise".into() }]);
for params in [json!({"amount": 75, "seed": 123}), json!({"amount": 75, "seed": 123, "target": "pixels"})] {
let plain = Action { name: "Plain".into(), steps: vec![("filter.noise.addNoise".into(), params)], ..Default::default() };
let (bytes, skipped) = export("Audit", &[&plain], &[], false).unwrap();
assert!(skipped.is_empty());
let imported = import(&bytes).unwrap();
assert_eq!(imported.actions[0].steps, vec![("filter.noise.addNoise".to_string(), json!({"amount": 75, "seed": 123}))]);
}
}
+51
View File
@@ -371,6 +371,57 @@ fn resizing_a_brush_resizes_its_enabled_secondary_tip() {
assert_eq!((s.tools.brush.size, s.tools.brush.dual_brush.size), (40.0, 9.0));
}
/// Every way of changing the main size scales the Dual Brush tip as Photoshop does (#4809): `[` /
/// `]`, the options bar / Brushes panel / Alt+right-drag (`tools.setBrush` with only a size), down
/// to 1 px and back without losing the proportion to a floor.
#[test]
fn every_size_change_scales_the_dual_tip_and_keeps_its_proportion() {
let mut s = session(32, 32);
s.execute("tools.setBrush", json!({"brush": {"size": 100, "dualBrush": {"enabled": true, "size": 20}}})).unwrap();
let sizes = |s: &Session| (s.tools.brush.size, s.tools.brush.dual_brush.size);
s.execute("tools.decreaseBrushSize", json!({})).unwrap();
assert_eq!(sizes(&s), (80.0, 16.0));
s.execute("tools.increaseBrushSize", json!({})).unwrap();
assert_eq!(sizes(&s), (100.0, 20.0));
// A coalesced drag (options bar slider, Alt+right-drag) is a run of size-only patches.
for size in [60, 10, 1] {
s.execute("tools.setBrush", json!({"brush": {"size": size}, "coalesce": "drag"})).unwrap();
}
assert_eq!(s.tools.brush.size, 1.0);
assert!((s.tools.brush.dual_brush.size - 0.2).abs() < 1e-5, "no 0.5 px floor: {}", s.tools.brush.dual_brush.size);
s.execute("tools.setBrush", json!({"brush": {"size": 100}})).unwrap();
assert_eq!(s.tools.brush.size, 100.0);
assert!((s.tools.brush.dual_brush.size - 20.0).abs() < 1e-3, "back to 20 px: {}", s.tools.brush.dual_brush.size);
// Painting with the sub-pixel dual tip works (the renderer bounds it).
s.execute("tools.setBrush", json!({"brush": {"size": 1}})).unwrap();
s.execute("paint.stroke", json!({"points": [[4, 16], [28, 16]]})).unwrap();
}
/// Picking a preset that captured its size sets both diameters from the preset: the dual tip is
/// not scaled on top of that.
#[test]
fn a_captured_preset_size_is_not_scaled_twice() {
let mut s = session(32, 32);
s.execute("tools.setBrush", json!({"size": 40, "dualBrush": {"enabled": true, "size": 10}})).unwrap();
s.execute("brush.presets.save", json!({"name": "Dual40"})).unwrap();
s.execute("tools.setBrush", json!({"size": 200})).unwrap();
assert_eq!(s.tools.brush.dual_brush.size, 50.0);
s.execute("tools.setBrush", json!({"preset": "Dual40"})).unwrap();
assert_eq!((s.tools.brush.size, s.tools.brush.dual_brush.size), (40.0, 10.0));
}
#[test]
fn bad_sizes_fail_and_leave_the_dual_tip_alone() {
let mut s = session(32, 32);
s.execute("tools.setBrush", json!({"brush": {"size": 100, "dualBrush": {"enabled": true, "size": 20}}})).unwrap();
for bad in [json!(1e30), json!("big"), json!([1]), json!({"x": 1}), json!(null)] {
let _ = s.execute("tools.setBrush", json!({"brush": {"size": bad}}));
assert_eq!(s.tools.brush.dual_brush.size, 20.0, "{bad}");
assert_eq!(s.tools.brush.size, 100.0, "{bad}");
}
assert!(s.execute("tools.setBrush", json!({"brush": {"size": 1e30}})).is_err());
}
#[test]
fn an_uncaptured_preset_size_keeps_dual_brush_proportions() {
let mut s = session(32, 32);
+8 -2
View File
@@ -55,9 +55,15 @@ fn map_fill(a: &Affine, f: &mut Fill) {
if let Fill::Gradient { angle, offset, .. } = f {
*angle = map_angle(a, *angle);
// The centre offset (a fraction of the frame) turns with the canvas: exact for 90° turns
// and flips, where the frame's sides swap with the axes.
// and flips, where the frame's sides swap with the axes. Scale (Image Size) resizes the
// frame too, so only each axis's direction applies.
let unit = |x: f64, y: f64| {
let n = x.hypot(y);
if n < EPS { (x, y) } else { (x / n, y / n) }
};
let ((m0, m1), (m2, m3)) = (unit(a.m[0], a.m[1]), unit(a.m[2], a.m[3]));
let (ox, oy) = (f64::from(offset.0), f64::from(offset.1));
*offset = ((a.m[0] * ox + a.m[2] * oy) as f32, (a.m[1] * ox + a.m[3] * oy) as f32);
*offset = ((m0 * ox + m2 * oy) as f32, (m1 * ox + m3 * oy) as f32);
}
}
+33
View File
@@ -188,6 +188,39 @@ fn gradient_fill_angle_follows_the_canvas() {
assert_eq!(map_angle(&Turn::Ccw90.affine(10.0, 20.0), 0.0), 90.0);
}
/// The gradient fill's centre offset after `cmd`, as `gradient.fill.get` reports it (% of the frame).
fn fill_offset_after(cmd: &str, p: serde_json::Value) -> (f64, f64) {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
s.execute("gradient.fill.create", json!({"from": [10, 50], "to": [90, 50], "style": "radial"})).unwrap();
s.execute("gradient.fill.set", json!({"angle": 0, "offset": [25, 0]})).unwrap();
s.execute(cmd, p).unwrap();
let g = s.execute("gradient.fill.get", json!({})).unwrap();
(g["offset"][0].as_f64().unwrap(), g["offset"][1].as_f64().unwrap())
}
#[test]
fn gradient_fill_offset_stays_a_fraction_of_the_frame() {
let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-3 && (a.1 - b.1).abs() < 1e-3;
// Image Size scales the frame, so the offset (a fraction of it) stays put.
for (w, h) in [(200, 200), (50, 50), (200, 50)] {
let o = fill_offset_after("image.imageSize", json!({"width": w, "height": h}));
assert!(near(o, (25.0, 0.0)), "{w}x{h}: {o:?}");
}
// Flips and 90° turns still mirror and turn it.
assert!(near(fill_offset_after("image.imageRotation.flipCanvasHorizontal", json!({})), (-25.0, 0.0)));
assert!(near(fill_offset_after("image.imageRotation.90cw", json!({})), (0.0, 25.0)));
assert!(near(fill_offset_after("image.imageRotation.180", json!({})), (-25.0, 0.0)));
// Non-uniform scale with a turn: only the axis swap applies.
let mut f = Fill::gradient(Vec::new(), 0.0, 1.0, photocraft_doc::GradientStyle::Linear, false);
if let Fill::Gradient { offset, .. } = &mut f {
*offset = (0.25, -0.1);
}
map_fill(&Affine { m: [0.0, 3.0, -0.5, 0.0, 7.0, 1.0] }, &mut f);
let Fill::Gradient { offset, .. } = f else { panic!("not a gradient") };
assert!((offset.0 - 0.1).abs() < 1e-6 && (offset.1 - 0.25).abs() < 1e-6, "{offset:?}");
}
fn type_and_shape_origin(d: &Document) -> ([f64; 6], [f64; 2]) {
let mut t = None;
let mut k = None;
+9 -7
View File
@@ -1086,17 +1086,19 @@ fn indicates_param(v: Option<&Value>) -> Option<ColorIndicates> {
}
}
fn color_value(p: &Value, key: &str) -> Option<Color> {
p.get(key)?;
let c = crate::commands::color_param(p, key, [1.0, 0.0, 0.0, 1.0]);
Some(Color::rgb(c[0], c[1], c[2]))
fn color_value(cmd: &str, p: &Value, key: &str) -> Result<Option<Color>> {
if p.get(key).is_none() {
return Ok(None);
}
let c = crate::commands::color_param(cmd, p, key, [1.0, 0.0, 0.0, 1.0])?;
Ok(Some(Color::rgb(c[0], c[1], c[2])))
}
fn new_channel(s: &mut Session, p: &Value) -> Result<Value> {
let fill = p.get("fill").and_then(Value::as_str).unwrap_or("black").to_string();
let name = p.get("name").and_then(Value::as_str).map(str::to_string);
let indicates = indicates_param(p.get("indicates"));
let color = color_value(p, "color");
let color = color_value("channel.new", p, "color")?;
let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0));
let i = s.edit("New Channel", |doc, _| {
let area = doc.bounds();
@@ -1125,7 +1127,7 @@ fn new_channel(s: &mut Session, p: &Value) -> Result<Value> {
}
fn new_spot(s: &mut Session, p: &Value) -> Result<Value> {
let color = color_value(p, "color").unwrap_or(Color::rgb(1.0, 0.0, 0.0));
let color = color_value("channel.newSpot", p, "color")?.unwrap_or(Color::rgb(1.0, 0.0, 0.0));
let solidity = p.get("solidity").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 100.0) as f32 / 100.0;
let name = p.get("name").and_then(Value::as_str).map(str::to_string);
let from_sel = p.get("fromSelection").and_then(Value::as_bool).unwrap_or(true);
@@ -1421,7 +1423,7 @@ fn options(s: &mut Session, p: &Value) -> Result<Value> {
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
let r = p.get("channel").and_then(|v| parse_ref(v, doc)).ok_or_else(|| bad(cmd, "missing or unknown `channel`"))?;
let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
let color = color_value(p, "color");
let color = color_value(cmd, p, "color")?;
let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0));
let solidity = p.get("solidity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0));
let kind = p.get("indicates").and_then(Value::as_str).map(str::to_string);
+1 -1
View File
@@ -34,7 +34,7 @@ fn unit(v: f32, default: f32) -> f32 {
/// Algorithm parameters (lenient: out-of-range values are clamped, unreadable ones fall back to
/// the defaults). [`run`] validates strictly before it gets here.
pub(crate) fn params(p: &Value) -> FilterParams {
let c = crate::commands::color_param(p, "color", WHITE);
let c = crate::commands::color_param(ID, p, "color", WHITE).unwrap_or(WHITE);
let num = |k: &str, d: f32| p.get(k).and_then(Value::as_f64).map_or(d, |v| unit(v as f32, d));
FilterParams::ColorToAlpha {
color: [unit(c[0], 1.0), unit(c[1], 1.0), unit(c[2], 1.0), 1.0],
+50 -10
View File
@@ -235,15 +235,53 @@ pub(crate) fn u32_id_param(cmd: &str, p: &Value, key: &str) -> Result<Option<u32
fn f32_or(p: &Value, key: &str, default: f32) -> f32 {
p.get(key).and_then(Value::as_f64).map(|v| v as f32).unwrap_or(default)
}
pub(crate) fn color_param(p: &Value, key: &str, default: [f32; 4]) -> [f32; 4] {
match p.get(key) {
/// JSON numbers may be finite f64 values but overflow when stored in a document's f32 field.
pub(crate) fn finite_f32(cmd: &str, key: &str, value: f64) -> Result<f32> {
let narrowed = value as f32;
if narrowed.is_finite() { Ok(narrowed) } else { Err(bad(cmd, format!("`{key}` must fit a finite 32-bit number"))) }
}
/// Effect/type parameters contain nested colour arrays and snapshots as well as scalars.
/// Validate before parsing or editing, including numbers hidden in an effect snapshot.
pub(crate) fn check_f32_values(cmd: &str, value: &Value) -> Result<()> {
// Bound the call stack, without allocating a work list proportional to an input array.
fn check(cmd: &str, value: &Value, depth: usize) -> Result<()> {
if depth > 64 {
return Err(bad(cmd, "parameters nested deeper than 64 levels"));
}
match value {
Value::Number(n) => {
finite_f32(cmd, "number", n.as_f64().ok_or_else(|| bad(cmd, "invalid number"))?)?;
}
Value::Array(a) => {
for v in a {
check(cmd, v, depth + 1)?;
}
}
Value::Object(o) => {
for v in o.values() {
check(cmd, v, depth + 1)?;
}
}
_ => {}
}
Ok(())
}
check(cmd, value, 0)
}
pub(crate) fn color_param(cmd: &str, p: &Value, key: &str, default: [f32; 4]) -> Result<[f32; 4]> {
Ok(match p.get(key) {
Some(Value::Array(a)) if a.len() >= 3 => {
let v: Vec<f32> = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();
[v[0], v[1], v[2], v.get(3).copied().unwrap_or(1.0)]
let mut out = [0.0, 0.0, 0.0, 1.0];
for (slot, value) in out.iter_mut().zip(a) {
*slot = finite_f32(cmd, key, value.as_f64().unwrap_or(0.0))?;
}
out
}
Some(Value::String(s)) => parse_hex(s).unwrap_or(default),
_ => default,
}
})
}
pub(crate) fn parse_hex(s: &str) -> Option<[f32; 4]> {
let s = s.trim_start_matches('#');
@@ -994,7 +1032,7 @@ fn build() -> Vec<CommandSpec> {
r##"{"color":"#rrggbb"=foreground,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##,
has_doc,
|s, p| {
let c = color_param(p, "color", s.tools.foreground);
let c = color_param("layer.newFillLayer.solidColor", p, "color", s.tools.foreground)?;
let id = s.edit("New Color Fill Layer", |doc, active| {
let fill = Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode);
let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill));
@@ -1014,8 +1052,8 @@ fn build() -> Vec<CommandSpec> {
r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask)}"##,
has_doc,
|s, p| {
let a = color_param(p, "from", s.tools.foreground);
let b = color_param(p, "to", s.tools.background);
let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?;
let b = color_param("layer.newFillLayer.gradient", p, "to", s.tools.background)?;
let angle = f32_or(p, "angle", 90.0);
let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear"));
let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false);
@@ -1146,8 +1184,10 @@ fn build() -> Vec<CommandSpec> {
}
};
let (fg_cmyk, bg_cmyk) = (cmyk("foregroundCmyk")?, cmyk("backgroundCmyk")?);
s.tools.foreground = color_param(p, "foreground", s.tools.foreground);
s.tools.background = color_param(p, "background", s.tools.background);
let foreground = color_param("tools.setColors", p, "foreground", s.tools.foreground)?;
let background = color_param("tools.setColors", p, "background", s.tools.background)?;
s.tools.foreground = foreground;
s.tools.background = background;
if let Some(k) = fg_cmyk {
let [r, g, b, _] = s.tools.foreground;
s.tools.remember_cmyk([r, g, b], k);
+64 -10
View File
@@ -35,15 +35,14 @@ pub struct Clip {
/// Photoshop's layer-based copy (CC 2018 on): with no selection, Copy takes the active layer
/// whole when it is a smart object (#2428), a type or shape layer, or a group (its whole subtree)
/// (#2670), so Paste recreates it instead of its pixels. Pixel layers still copy their pixels;
/// several selected layers are [`multi_copy_ids`].
/// (#2670), so Paste recreates it instead of its pixels. Fill and adjustment layers have no
/// pixels of their own, so they are taken whole too rather than refused (#2344). Pixel layers
/// still copy their pixels; several selected layers are [`multi_copy_ids`].
fn takes_whole(d: &crate::DocState, id: LayerId) -> bool {
d.doc.selection.is_none()
&& d.selected_layers().len() <= 1
&& crate::layer_copy_cmds::layered(d.doc.mode)
&& d.doc
.layer(id)
.is_some_and(|l| matches!(l.content, LayerContent::Smart(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Group(_)))
&& d.doc.layer(id).is_some_and(|l| !matches!(l.content, LayerContent::Raster(_)))
}
/// A scratch document in the source's colour, to hold copied layers.
@@ -280,13 +279,18 @@ fn copy(s: &mut Session, merged: bool) -> Result<Value> {
}
match (d.doc.layer(id).and_then(Layer::surface).filter(|_| several.is_empty()), &layers) {
(Some(surf), _) => Clip { layers, ..lift(surf, d.doc.selection.as_ref(), canvas)? },
// A group has no pixels of its own: the clipboard pixels are what it shows.
// A group or fill layer has no pixels of its own: the clipboard pixels are what it
// shows. Adjustment layers show nothing by themselves, so their clip spans the canvas
// they apply to: Paste places them as a full-canvas layer, and the UI still mirrors
// the clip to the OS clipboard (an empty clip would let a stale OS image replace it).
(None, Some(copies)) => {
let mut shown = (**copies).clone();
for l in &mut shown.layers {
l.visible = true;
}
Clip { layers, ..lift(&merged_surface(&shown), None, canvas)? }
let clip = lift(&merged_surface(&shown), None, canvas)?;
let bounds = if clip.bounds.is_empty() { canvas } else { clip.bounds };
Clip { layers, bounds, ..clip }
}
(None, None) => return Err(EngineError::Other("the active layer has no pixels".into())),
}
@@ -1454,12 +1458,12 @@ mod tests {
assert!(s.clipboard.is_none(), "a refused copy leaves the clipboard alone");
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
assert!(s.execute("edit.copy", json!({"target": "mask"})).is_ok());
// An adjustment layer has no pixels of its own: Copy is only enabled while its mask is
// targeted (#2928).
// An adjustment layer has no pixels of its own: Copy takes the layer whole (#2344), and
// its mask while that is targeted (#2928).
s.execute("file.new", json!({"width": 20, "height": 20})).unwrap();
let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.select", json!({"layer": a})).unwrap();
assert!(!s.is_enabled("edit.copy"), "no pixels to copy");
assert!(s.is_enabled("edit.copy"), "the layer itself can be copied");
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
assert!(s.is_enabled_with("edit.copy", &json!({"target": "mask"})), "the mask can be copied");
}
@@ -1916,6 +1920,56 @@ mod tests {
assert_eq!(shape.surface().map(|c| c.format().sample), Some(s.active().unwrap().doc.depth), "converted to 16 bits");
}
/// #2344: fill and adjustment layers have no pixels of their own, so with no selection Copy
/// takes them whole and Paste recreates them, in the same or another document, in one step.
#[test]
fn copy_paste_keeps_fill_and_adjustment_layers() {
for (depth, other) in [(8, 16), (16, 32), (32, 8)] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 60, "height": 40, "depth": depth})).unwrap();
s.execute("layer.newFillLayer.gradient", json!({"from": "#000000", "to": "#ffffff", "angle": 0})).unwrap();
let LayerContent::Fill(fill) = active_content(&s) else { panic!("a fill layer") };
let src = s.active().unwrap().active_layer.unwrap();
assert!(s.is_enabled("edit.copy"), "{depth}-bit: a fill layer can be copied");
assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: what it shows");
let clip = s.clipboard.clone().unwrap();
assert!(clip.surface.rgba(59, 20)[0] > clip.surface.rgba(0, 20)[0], "{depth}-bit: the clip holds the gradient's pixels");
let steps = s.active().unwrap().history.past_len();
s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap();
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{depth}-bit: one history step");
assert_eq!(active_content(&s), LayerContent::Fill(fill.clone()), "{depth}-bit: the paste is the same fill layer");
assert_ne!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: a new layer");
s.undo();
assert_eq!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: undo removes the paste");
s.redo();
assert!(matches!(active_content(&s), LayerContent::Fill(_)), "{depth}-bit: redo brings it back");
s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap();
let LayerContent::Adjustment(levels) = active_content(&s) else { panic!("an adjustment layer") };
assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: it applies to the canvas");
s.execute("file.new", json!({"width": 30, "height": 30, "depth": other})).unwrap();
s.execute("edit.paste", json!({})).unwrap();
assert_eq!(active_content(&s), LayerContent::Adjustment(levels), "{depth}-bit: the same Levels layer in the {other}-bit document");
assert_eq!(s.active().unwrap().doc.layers.len(), 2, "{depth}-bit: pasted above the Background");
}
}
/// #2344: several adjustment layers, which show nothing alone, still copy and paste together.
#[test]
fn several_adjustment_layers_copy_together() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 40, "height": 40})).unwrap();
let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap();
let b = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.select", json!({"layer": a})).unwrap();
s.execute("layer.select", json!({"layer": b, "mode": "toggle"})).unwrap();
assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 40, 40]));
s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap();
let d = &s.active().unwrap().doc;
assert_eq!(d.layers.len(), 5, "both are pasted");
assert!(d.layers[3..].iter().all(|l| matches!(l.content, LayerContent::Adjustment(_))));
}
#[test]
fn merge_visible_keeps_hidden_layers() {
let mut s = session();
+12 -3
View File
@@ -68,7 +68,7 @@ pub(crate) fn after_command(s: &mut Session, id: &str) {
let now = st.doc.layer(layer);
let was = prev.layer(layer);
let surf_eq = |a: Option<&Surface>, b: Option<&Surface>| match (a, b) {
(Some(a), Some(b)) => crate_fingerprint(a) == crate_fingerprint(b),
(Some(a), Some(b)) => a.format() == b.format() && a.default_pixel() == b.default_pixel() && crate_fingerprint(a) == crate_fingerprint(b),
(None, None) => true,
_ => false,
};
@@ -214,7 +214,9 @@ fn fade(s: &mut Session, p: &Value) -> Result<Value> {
if now.format() != before.format() {
return Err(EngineError::Other("can't fade a step that changed the layer's pixel format".into()));
}
let area = before.content_bounds().union(&now.content_bounds());
// A uniform mask can change every pixel without storing a single tile. In that case
// the content bounds are empty, but Fade must still blend across the canvas.
let area = if before.default_pixel() != now.default_pixel() { st.doc.bounds() } else { before.content_bounds().union(&now.content_bounds()) };
let label = format!("Fade {}", src.label);
s.edit(&label, |doc, _| {
let l = doc.layer_mut(src.layer).ok_or(EngineError::NoLayer(src.layer))?;
@@ -329,7 +331,7 @@ fn can_caf(s: &Session) -> std::result::Result<(), String> {
}
/// Mask surface (gray) of an alpha channel by index or name.
fn channel_mask<'a>(doc: &'a Document, v: &Value) -> Option<&'a Surface> {
pub(crate) fn channel_mask<'a>(doc: &'a Document, v: &Value) -> Option<&'a Surface> {
match v {
Value::Number(n) => doc.channels.get(n.as_u64()? as usize).map(|c| &c.surface),
Value::String(name) => doc.channels.iter().find(|c| c.name == *name).map(|c| &c.surface),
@@ -719,6 +721,13 @@ fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &
let cancel = || ctx.cancelled();
let plan = content_aware_plan_with(&doc, id, &p, cmd, &photocraft_raster::Interrupt::cancel_only(&cancel))?;
let CafPlan { layer, rect, fmt, img, layer_px, cover, hole, source, opts, output, .. } = plan;
// Patches come only from the sampling area outside the fill area. With none (a
// Rectangular `margin` of 0, a Custom area inside the selection or off the canvas)
// the fill would be black (#6532), so refuse instead. The workspace's preview builds
// the same plan and may show an empty area while the Sampling Brush adds to it.
if !source.iter().any(|s| *s) {
return Err(bad(cmd, "nothing to sample from: the sampling area has no pixels outside the fill area"));
}
let (w, h) = (rect.width() as usize, rect.height() as usize);
let n = fmt.channels();
// The fill changes only the fill area: keep the layer's pixels and the coverage over
+58 -4
View File
@@ -57,6 +57,38 @@ fn fade_with_blend_mode_and_invalidation() {
assert!(s.execute("edit.fade", json!({"mode": "nonsense"})).is_err());
}
#[test]
fn fade_uniform_layer_mask_invert_at_all_depths() {
for depth in [8, 16, 32] {
for (opacity, expected) in [(0, 1.0), (50, 0.5), (100, 0.0)] {
let mut s = session(depth);
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
s.execute("channel.target", json!({"channel": "mask"})).unwrap();
let mask_pixel = |s: &Session| {
let layer = active(s);
let mask = &layer.mask.as_ref().unwrap().surface;
mask.pixel(5, 5)[0]
};
assert!((mask_pixel(&s) - 1.0).abs() < 0.01);
s.execute("image.adjustments.invert", json!({})).unwrap();
assert!(mask_pixel(&s) < 0.01, "depth {depth}: invert changed the mask");
assert!(s.edit_state.fade.as_ref().is_some_and(|f| f.mask), "depth {depth}: Fade must target the mask");
let history_before_fade = s.active().unwrap().history.past_len();
s.execute("edit.fade", json!({"opacity": opacity})).unwrap();
for (x, y) in [(0, 0), (5, 5), (63, 47)] {
let pixel = active(&s).mask.as_ref().unwrap().surface.pixel(x, y)[0];
assert!((pixel - expected).abs() < 0.02, "depth {depth}, opacity {opacity}, ({x}, {y}): {pixel}");
}
assert_eq!(s.active().unwrap().history.past_len(), history_before_fade + 1);
assert!(s.undo());
assert!(mask_pixel(&s) < 0.01, "undo restores inverted mask");
assert!(s.redo());
assert!((mask_pixel(&s) - expected).abs() < 0.02, "redo restores faded mask");
}
}
}
#[test]
fn purge_commands() {
let mut s = session(8);
@@ -105,10 +137,15 @@ fn blob_session(depth: u32) -> Session {
fn content_aware_fill_huge_area_neither_panics_nor_wraps() {
let mut s = blob_session(8);
// `[1e30, 0, 1e30, 10]` overflowed the i32 additions in the area parser (a debug-build
// panic, a garbage sampling window in release); the additions saturate now, so this is
// simply a whole-canvas window.
let r = s.execute("edit.contentAwareFill", json!({"sampling": "custom", "area": [1e30, 0.0, 1e30, 10.0], "colorAdaptation": "none"})).unwrap();
assert!(r["filled"].as_u64().unwrap() > 100);
// panic, a garbage sampling window in release); the additions saturate now, so the area lies
// wholly right of the canvas: nothing to sample, which is an error, not a black fill (#6532).
let before = s.active().unwrap().doc.clone();
let past = s.active().unwrap().history.past_len();
let err = s.execute("edit.contentAwareFill", json!({"sampling": "custom", "area": [1e30, 0.0, 1e30, 10.0], "colorAdaptation": "none"})).unwrap_err();
assert!(err.to_string().contains("nothing to sample from"), "{err}");
let st = s.active().unwrap();
assert!(std::sync::Arc::ptr_eq(&before, &st.doc), "the document changed");
assert_eq!(st.history.past_len(), past, "a history step was recorded");
// A malformed area names the problem instead of silently falling back.
for area in [json!([0.0, 0.0, null, 10.0]), json!([0.0, 0.0, 10.0]), json!("nope")] {
let err = s.execute("edit.contentAwareFill", json!({"sampling": "custom", "area": area})).unwrap_err();
@@ -312,6 +349,23 @@ fn content_aware_fill_takes_the_workspace_edits() {
assert!(r["filled"].as_u64().unwrap() > 2800);
}
/// #6532: a sampling area with no pixels outside the fill area is refused instead of filling it
/// black, and leaves the document untouched; any margin past the selection fills.
#[test]
fn content_aware_fill_with_nothing_to_sample_is_refused() {
let mut s = blob_session(8);
let before = px(&s, 30, 22);
let revision = s.active().unwrap().revision;
for p in [json!({"sampling": "rectangular", "margin": 0}), json!({"sampling": "custom", "area": [28, 18, 4, 4]})] {
let e = s.execute("edit.contentAwareFill", p.clone()).unwrap_err().to_string();
assert!(e.contains("nothing to sample from"), "{p}: {e}");
assert_eq!(px(&s, 30, 22), before, "{p}: nothing was filled");
assert_eq!(s.active().unwrap().revision, revision, "{p}: no history step");
}
s.execute("edit.contentAwareFill", json!({"sampling": "rectangular", "margin": 1})).unwrap();
assert_ne!(px(&s, 30, 22), before, "the red blob is filled from around the selection");
}
#[test]
fn content_aware_fill_outputs_and_sampling() {
let mut s = blob_session(8);
+1 -1
View File
@@ -135,7 +135,7 @@ fn map_pixels(s: &mut Session, label: &str, p: &Value, f: impl FnOnce(Rect, &mut
fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
// Whole pixels, rounded up, as in Photoshop (0.5 px strokes 1 px).
let width = p.get("width").and_then(Value::as_f64).filter(|w| w.is_finite()).unwrap_or(1.0).clamp(1.0, 250.0).ceil() as usize;
let color = color_param(p, "color", s.tools.foreground);
let color = color_param("edit.stroke", p, "color", s.tools.foreground)?;
// A colour picked as CMYK strokes a CMYK document with the picked inks (#4196).
let picked = s.tools.picked_cmyk([color[0], color[1], color[2]]);
let mode = match p.get("mode") {
+16 -2
View File
@@ -234,7 +234,12 @@ pub fn same_file(a: &str, b: &str) -> bool {
}
#[cfg(windows)]
{
// NTFS and FAT compare names without case.
// The volume serial number and file index of each, as unix compares dev and inode, so a
// hard link (another name for the file) is the same file.
if let Ok(same) = same_file::is_same_file(a, b) {
return same;
}
// Should a file not open: NTFS and FAT compare names without case.
if let (Ok(x), Ok(y)) = (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
return x.to_string_lossy().to_lowercase() == y.to_string_lossy().to_lowercase();
}
@@ -481,6 +486,15 @@ fn revert(s: &mut Session) -> Result<Value> {
fn save_a_copy(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path", "file.saveACopy")?.to_string();
let d = s.active().ok_or(EngineError::NoDocument)?;
// A copy over the document's own file replaces it, and a flat or lossy format can't be
// undone, so it takes an explicit `overwrite` (#7437). The desktop dialog writes through the
// shell, after the OS has confirmed the replace.
if d.path.as_deref().is_some_and(|own| same_file(&path, own)) && p.get("overwrite").and_then(Value::as_bool) != Some(true) {
return Err(EngineError::BadParams {
cmd: "file.saveACopy".into(),
msg: "`path` is the document's own file, so the copy would replace it: choose another path, or pass \"overwrite\": true".into(),
});
}
let mut doc = (*d.doc).clone();
if p.get("layers").and_then(Value::as_bool) == Some(false) {
// "Layers" unchecked in Save a Copy: write the flattened image.
@@ -1639,7 +1653,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save a Copy…",
&["File"],
Some("Cmd+Alt+S"),
r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)}"##,
r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)}"##,
native_doc,
save_a_copy
),
+38
View File
@@ -135,6 +135,44 @@ fn save_a_copy_keeps_path_and_dirty_state() {
assert!(s.execute("file.saveACopy", json!({})).is_err());
}
/// A copy over the document's own file, however the path is spelt, would replace it (a lossy
/// re-encode can't be undone), so it is refused unless `overwrite` is passed (#7437).
#[test]
fn save_a_copy_refuses_the_documents_own_file() {
let dir = tmp("copy-own");
let path = png(&dir, "own.png", 6, 4, "#ff0000");
let bytes = std::fs::read(&path).unwrap();
let mut s = Session::new();
open_bytes_as(&mut s, &path, &bytes, None, Some(path.clone())).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap();
let link = join(&dir, "link.png");
std::fs::hard_link(&path, &link).unwrap();
let rev = s.active().unwrap().revision;
for p in [path.clone(), format!("{dir}/./own.png"), link] {
let r = s.execute("file.saveACopy", json!({"path": p}));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("overwrite")), "{p}: {r:?}");
assert!(s.execute("file.saveACopy", json!({"path": p, "overwrite": false})).is_err(), "{p}");
assert_eq!(std::fs::read(&path).unwrap(), bytes, "{p}");
let st = s.active().unwrap();
assert_eq!(st.path.as_deref(), Some(path.as_str()), "{p}");
assert_eq!(st.revision, rev, "{p}");
assert!(st.is_dirty(), "{p}");
}
let other = join(&dir, "other.png");
s.execute("file.saveACopy", json!({"path": other})).unwrap();
assert!(std::fs::metadata(&other).unwrap().len() > 0);
s.execute("file.saveACopy", json!({"path": path, "overwrite": true})).unwrap();
assert_ne!(std::fs::read(&path).unwrap(), bytes);
assert_eq!(s.active().unwrap().path.as_deref(), Some(path.as_str()));
assert!(s.active().unwrap().is_dirty());
// A document that was never saved has no file of its own: it copies anywhere, as before.
let mut fresh = session(4, 4, 8);
fresh.execute("file.saveACopy", json!({"path": path})).unwrap();
assert_eq!(fresh.active().unwrap().path, None);
}
/// `tgaBits` picks the Targa's bits per pixel (byte 16 of the header); unset, a document with an
/// alpha channel is written as 32-bit, with the channel as the alpha.
#[test]
+1 -1
View File
@@ -106,7 +106,7 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {
let source = match contents {
"foreground" => color_source(s, s.tools.foreground),
"background" => color_source(s, s.tools.background),
"color" => color_source(s, color_param(p, "color", s.tools.foreground)),
"color" => color_source(s, color_param(CMD, p, "color", s.tools.foreground)?),
"black" => Source::Color([0.0, 0.0, 0.0, 1.0]),
"gray" => Source::Color([128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]),
"white" => Source::Color([1.0; 4]),
+6 -1
View File
@@ -292,6 +292,11 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value>
let surf = match &mut l.content {
LayerContent::Raster(surf) => surf,
LayerContent::Smart(_) => {
// A smart filter re-renders from its params alone, without the document's
// channels, so Lens Blur's alpha-channel depth would be lost (#7400).
if matches!(fp, FilterParams::LensBlur { depth: algo::DepthSource::Channel, .. }) {
return Err(EngineError::Other("Lens Blur can't read an alpha channel as depth on a Smart Object: rasterize the layer first".into()));
}
// Non-destructive: record the filter and re-render the smart object from its source.
let sf =
SmartFilter { command: id.clone(), params: params.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true };
@@ -313,7 +318,7 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value>
}
/// Lock transparency: put the layer's alpha back after a filter, in the tiles it changed.
fn keep_alpha(old: &photocraft_raster::Surface, new: &mut photocraft_raster::Surface) {
pub(crate) fn keep_alpha(old: &photocraft_raster::Surface, new: &mut photocraft_raster::Surface) {
if old.format() != new.format() || !new.format().alpha {
return;
}
+5 -3
View File
@@ -123,9 +123,11 @@ fn choices(id: &str) -> Option<&'static [(&'static str, &'static str)]> {
"filter.distort.zigZag" => &[("style", "pondRipples|outFromCenter|aroundCenter")],
"filter.render.lensFlare" => &[("lens", "zoom|prime35|prime105|moviePrime")],
"filter.render.lightingEffects" => &[("lightType", "spot|point|infinite"), ("texture", "none|red|green|blue|alpha|luminance")],
"filter.blur.lensBlur" => {
&[("shape", "hexagon|triangle|square|pentagon|heptagon|octagon"), ("depthMap", "none|transparency|layerMask"), ("distribution", "uniform|gaussian")]
}
"filter.blur.lensBlur" => &[
("shape", "hexagon|triangle|square|pentagon|heptagon|octagon"),
("depthMap", "none|transparency|layerMask|channel"),
("distribution", "uniform|gaussian"),
],
"filter.other.hsbHsl" => &[("inputMode", "rgb|hsb|hsl"), ("rowOrder", "hsb|hsl|rgb")],
"filter.video.deInterlace" => &[("eliminate", "oddFields|evenFields"), ("createBy", "interpolation|duplication")],
_ => return None,
+14 -2
View File
@@ -277,6 +277,7 @@ pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {
depth: match s(p, "depthMap", "none") {
"transparency" => DepthSource::Transparency,
"layerMask" => DepthSource::LayerMask,
"channel" => DepthSource::Channel,
_ => DepthSource::None,
},
focal_distance: f(p, "focalDistance", 0.0).clamp(0.0, 255.0),
@@ -429,8 +430,19 @@ fn map_from_document(doc: &Document, layer: Option<u64>) -> Option<algo::Image>
}
/// Resolves inputs that live outside the target layer: Displace's map (`mapPath`, or
/// `mapDocument` index with optional `mapLayer` id).
/// `mapDocument` index with optional `mapLayer` id), and the alpha channel Lens Blur reads its
/// depth from (`depthChannel`, an index or a name).
pub(crate) fn resolve(s: &Session, fp: &mut FilterParams, p: &Value) -> Result<()> {
if let FilterParams::LensBlur { depth: DepthSource::Channel, depth_map, .. } = fp {
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
let channel = p
.get("depthChannel")
.ok_or_else(|| EngineError::Other("Lens Blur: `depthMap` channel needs `depthChannel` (an alpha channel's index or name)".into()))?;
let surface = crate::edit_menu_cmds::channel_mask(doc, channel)
.ok_or_else(|| EngineError::Other(format!("Lens Blur: the document has no alpha channel {channel}")))?;
*depth_map = Some(Arc::new(algo::Image::read(surface, doc.bounds())));
return Ok(());
}
let FilterParams::Displace { map, .. } = fp else { return Ok(()) };
if map.is_some() {
return Ok(());
@@ -662,7 +674,7 @@ pub fn specs() -> Vec<CommandSpec> {
"filter.blur.lensBlur",
"Lens Blur…",
["Filter", "Blur"],
r##"{"radius":0..100=15,"shape":"hexagon|triangle|square|pentagon|heptagon|octagon","bladeCurvature":0..100=0,"rotation":0..360=0,"depthMap":"none|transparency|layerMask","focalDistance":0..255=0,"invert":bool,"brightness":0..100=0,"threshold":0..255=255,"noise":0..100=0,"distribution":"uniform|gaussian","monochromatic":bool,"seed":u32=0}"##
r##"{"radius":0..100=15,"shape":"hexagon|triangle|square|pentagon|heptagon|octagon","bladeCurvature":0..100=0,"rotation":0..360=0,"depthMap":"none|transparency|layerMask|channel","depthChannel":index|name?,"focalDistance":0..255=0,"invert":bool,"brightness":0..100=0,"threshold":0..255=255,"noise":0..100=0,"distribution":"uniform|gaussian","monochromatic":bool,"seed":u32=0}"##
),
cmd!(
"filter.blur.shapeBlur",
+45
View File
@@ -220,6 +220,51 @@ fn lens_blur_uses_the_layer_mask_as_depth() {
assert_ne!(pixels(&s), before);
}
/// #7400: an alpha channel is a Lens Blur depth source, by name or index, as Photoshop lists
/// the document's channels in Depth Map › Source. A missing channel is an error that changes
/// nothing, and on a Smart Object (whose smart filters re-render without the channels) it is
/// refused instead of silently blurring without depth.
#[test]
fn lens_blur_reads_an_alpha_channel_as_depth() {
let mut s = session();
// A white channel: depth 1 everywhere. Creating it targets it; the filter is for the layer.
s.execute("channel.new", json!({"name": "Depth Map", "fill": "white"})).unwrap();
s.execute("channel.target", json!({"channel": "composite"})).unwrap();
let before = pixels(&s);
for channel in [json!("Depth Map"), json!(0)] {
let p = |focal: f64| json!({"radius": 6, "depthMap": "channel", "depthChannel": channel, "focalDistance": focal});
// Focal distance 255 puts depth 1 in focus: nothing blurs.
s.execute("filter.blur.lensBlur", p(255.0)).unwrap();
assert_eq!(pixels(&s), before, "{channel}: in focus");
s.execute("filter.blur.lensBlur", p(0.0)).unwrap();
assert_ne!(pixels(&s), before, "{channel}: out of focus blurs");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(pixels(&s), before);
}
for bad in [
json!({"radius": 6, "depthMap": "channel"}),
json!({"radius": 6, "depthMap": "channel", "depthChannel": "Nope"}),
json!({"radius": 6, "depthMap": "channel", "depthChannel": 7}),
] {
let doc = s.active().unwrap().doc.clone();
let past = s.active().unwrap().history.past_len();
let e = s.execute("filter.blur.lensBlur", bad.clone()).unwrap_err().to_string();
assert!(e.contains("Lens Blur"), "{bad}: {e}");
assert_eq!(pixels(&s), before, "{bad}: nothing changed");
let st = s.active().unwrap();
assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "{bad}: the document was replaced");
assert_eq!(st.history.past_len(), past, "{bad}: a history step was recorded");
}
s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
let doc = s.active().unwrap().doc.clone();
let past = s.active().unwrap().history.past_len();
let e = s.execute("filter.blur.lensBlur", json!({"radius": 6, "depthMap": "channel", "depthChannel": "Depth Map"})).unwrap_err().to_string();
assert!(e.contains("Smart Object"), "{e}");
let st = s.active().unwrap();
assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "no smart filter was added");
assert_eq!(st.history.past_len(), past, "no history step");
}
#[test]
fn params_map_to_algorithm_units() {
assert_eq!(params_for("filter.pixelate.crystallize", &json!({"cellSize": 1})), Some(FilterParams::Crystallize { cell_size: 3.0, seed: 0 }));
+60
View File
@@ -54,6 +54,18 @@ pub(crate) fn for_each_surface(layers: &mut [Layer], masks: bool, f: &mut dyn Fn
}
}
/// Drops every fill cache of a layer tree. A fill layer covers the whole canvas, but its cache
/// (the pixels a PSD stored) only the old one: after the canvas grows the fill must re-render
/// from its model, or the added area stays transparent (#7362).
fn drop_fill_caches(layers: &mut [Layer]) {
for l in layers {
l.fill_cache = None;
if let LayerContent::Group(g) = &mut l.content {
drop_fill_caches(&mut g.children);
}
}
}
/// Converts every pixel surface of a layer tree (masks included) to `depth`.
pub(crate) fn convert_layers_depth(layers: &mut [Layer], depth: SampleType) {
for_each_surface(layers, true, &mut |surf, _| {
@@ -171,6 +183,12 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
let d = s.active().ok_or(EngineError::NoDocument)?;
let (ow, oh) = (d.doc.size.width, d.doc.size.height);
let resample = parse_resample(p.get("resample").and_then(Value::as_str).unwrap_or("bicubic"));
// An Indexed Color document holds only its colour table's colours, and a save quantises to
// them: interpolation showed blends that the saved file didn't have (#6019).
let resample = match resample {
Method::Filter(_) | Method::Automatic if d.doc.mode == ColorMode::Indexed => Method::Filter(Resample::Nearest),
m => m,
};
let mut pw = p.get("width").and_then(Value::as_f64);
let mut ph = p.get("height").and_then(Value::as_f64);
// `percent` scales both sides (what a Photoshop action records as "200%"); an explicit side wins.
@@ -337,6 +355,9 @@ fn crop_doc(doc: &mut Document, cmd: &str, r: Rect, delete_pixels: bool, extensi
surf.write_interleaved(keep, &saved);
}
}
if extends {
drop_fill_caches(&mut doc.layers);
}
crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes);
Ok(())
}
@@ -397,6 +418,9 @@ fn canvas_size(s: &mut Session, p: &Value) -> Result<Value> {
s.edit("Canvas Size", |doc, _| {
translate_doc(doc, "image.canvasSize", dx, dy)?;
doc.size = Size::new(nw, nh);
if nw > ow as u32 || nh > oh as u32 {
drop_fill_caches(&mut doc.layers);
}
crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes);
let canvas = doc.bounds();
let old = Rect::from_xywh(dx, dy, ow as u32, oh as u32);
@@ -525,8 +549,10 @@ fn crop_target(p: &Value) -> Result<CropTarget> {
let side = |key: &str| -> Result<Option<u32>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
// Whole-number floats (`100.0`) count too, as for the crop rectangle.
Some(v) => v
.as_u64()
.or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && (0.0..=f64::from(MAX_CROP_SIDE)).contains(f)).map(|f| f as u64))
.and_then(|n| u32::try_from(n).ok())
.filter(|n| (1..=MAX_CROP_SIDE as u32).contains(n))
.map(Some)
@@ -938,6 +964,28 @@ mod tests {
}
}
/// #6019: Image Size on an Indexed Color document makes no colours the colour table doesn't have.
#[test]
fn image_size_resamples_indexed_color_with_nearest_neighbor() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 2, "height": 1})).unwrap();
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
s.execute("select.rect", json!({"x": 1, "y": 0, "width": 1, "height": 1})).unwrap();
s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s.execute("image.mode.indexedColor", json!({})).unwrap();
for resample in ["bicubic", "automatic", "bilinear", "lanczos", "preserveDetails"] {
s.execute("image.imageSize", json!({"width": 8, "resample": resample})).unwrap();
let st = s.active().unwrap();
let surf = st.doc.layers[0].surface().unwrap();
for x in 0..8 {
let px = surf.pixel(x, 0);
assert!(px[..3] == [1.0, 0.0, 0.0] || px[..3] == [0.0, 0.0, 1.0], "{resample}: no blended colour at x {x}: {px:?}");
}
s.execute("history.undo", json!({})).unwrap();
}
}
/// The canvas border stays opaque after Image Size (it used to fade into transparency, so a
/// Background or a 200 % export got a translucent frame), and a full selection stays full.
/// #1544: 64 x 48 to 300000 x 300000 (90 billion pixels) started allocating resampled bands
@@ -1372,6 +1420,14 @@ mod tests {
assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(30, 10), 150.0));
}
#[test]
fn crop_target_accepts_whole_number_floats() {
// `json.dumps(100.0)` and many other JSON writers send whole numbers as floats.
let mut s = session();
s.execute("image.crop", json!({"x": 0, "y": 0, "width": 20, "height": 10, "targetWidth": 40.0, "targetHeight": 20.0})).unwrap();
assert_eq!(doc(&s).size, Size::new(40, 20));
}
#[test]
fn crop_target_rejects_bad_params_without_changing_the_document() {
let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10});
@@ -1381,6 +1437,10 @@ mod tests {
json!({"targetWidth": 0, "targetHeight": 10}),
json!({"targetWidth": -5, "targetHeight": 10}),
json!({"targetWidth": 10.5, "targetHeight": 10}),
json!({"targetWidth": -1.0, "targetHeight": 10}),
json!({"targetWidth": 0.0, "targetHeight": 10}),
json!({"targetWidth": 1e39, "targetHeight": 10}),
json!({"targetWidth": 300_001.0, "targetHeight": 10}),
json!({"targetWidth": "10", "targetHeight": 10}),
json!({"targetWidth": 300_001, "targetHeight": 10}),
json!({"targetWidth": 4_294_967_306_u64, "targetHeight": 10}),
+23 -8
View File
@@ -594,6 +594,9 @@ fn overlay_gradient(g: &mut Gradient, p: &Value) {
/// a dialog round trip never touches what it doesn't model: an imported
/// gradient stroke keeps its gradient while its opacity is edited.
pub fn overlay_effect(fx: &mut Effect, p: &Value) {
if crate::commands::check_f32_values("layer.layerStyle", p).is_err() {
return;
}
fn set_color(p: &Value, k: &str, c: &mut Color) {
if let Some(x) = color_of(p, k) {
*c = x;
@@ -821,6 +824,7 @@ pub fn overlay_effect(fx: &mut Effect, p: &Value) {
/// Builds an effect of `kind` from JSON params (Photoshop units: opacity,
/// spread, range in percent; sizes in px; angles in degrees).
pub fn effect_from_params(kind: &str, p: &Value) -> Option<Effect> {
crate::commands::check_f32_values("layer.layerStyle", p).ok()?;
let mut fx = fresh_effect(kind)?;
overlay_effect(&mut fx, p);
Some(fx)
@@ -856,6 +860,7 @@ const MAX_EFFECTS: usize = 256;
/// mismatches and malformed snapshots are errors, never panics.
fn replace_effects(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "layer.layerStyle.replace";
crate::commands::check_f32_values(CMD, p)?;
let id = crate::commands::layer_param(s, p)?;
let entries = p.get("effects").and_then(Value::as_array).ok_or_else(|| bad(CMD, "need `effects`: [{kind, params, fx?}]"))?;
if entries.len() > MAX_EFFECTS {
@@ -905,6 +910,7 @@ fn replace_effects(s: &mut Session, p: &Value) -> Result<Value> {
}
fn set_effect(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
crate::commands::check_f32_values(&format!("layer.layerStyle.{kind}"), p)?;
let fx = effect_from_params(kind, p).ok_or_else(|| EngineError::Other(format!("unknown effect {kind}")))?;
let (fx, pattern) = crate::pattern_cmds::resolve_effect(s, fx)?;
let label = format!("Layer Style: {}", fx.label());
@@ -936,6 +942,7 @@ fn make_default(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) if v.is_object() => v.clone(),
_ => return Err(bad(CMD, "`params` must be an object")),
};
crate::commands::check_f32_values(CMD, &params)?;
s.presets.layer_defaults.insert(kind.to_string(), params);
s.presets_changed();
Ok(json!({"kind": kind}))
@@ -1152,17 +1159,25 @@ mod tests {
/// blur kernel of 2^62 taps ("capacity overflow"), or ran for minutes at 1e6. The blur width
/// is capped at the effect reach, so the document still renders, quickly.
#[test]
fn oversized_satin_and_bevel_sizes_render() {
for (cmd, p) in [
("satin", json!({"size": 1e308})),
("satin", json!({"size": 1_000_000})),
("bevelEmboss", json!({"size": 1e308})),
("bevelEmboss", json!({"soften": 1e308})),
("bevelEmboss", json!({"size": 1_000_000, "soften": 1_000_000})),
fn oversized_satin_and_bevel_sizes_stay_saveable_and_render() {
for (cmd, p, accepted) in [
("satin", json!({"size": 1e308}), false),
("satin", json!({"size": 1e30}), true),
("satin", json!({"size": 1_000_000}), true),
("bevelEmboss", json!({"size": 1e308}), false),
("bevelEmboss", json!({"soften": 1e308}), false),
("bevelEmboss", json!({"size": 1e30, "soften": 1e30}), true),
("bevelEmboss", json!({"size": 1_000_000, "soften": 1_000_000}), true),
] {
let mut s = session();
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
s.execute(&format!("layer.layerStyle.{cmd}"), p.clone()).unwrap();
let result = s.execute(&format!("layer.layerStyle.{cmd}"), p.clone());
if accepted {
result.unwrap();
} else {
assert!(matches!(result, Err(EngineError::BadParams { .. })));
}
photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap();
let start = std::time::Instant::now();
s.execute("document.pixel", json!({"x": 0, "y": 0})).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"));
assert!(start.elapsed().as_secs() < 20, "{cmd} {p}: {:?}", start.elapsed());
+1 -1
View File
@@ -62,7 +62,7 @@ pub fn lens_params(cmd: &str, p: &Value, frame: Rect, info: Option<&exif::Camera
"edgeExtension" | "extension" => EdgeMode::Extension,
"black" => EdgeMode::Color([0.0, 0.0, 0.0, 1.0]),
"white" => EdgeMode::Color([1.0, 1.0, 1.0, 1.0]),
"background" | "color" => EdgeMode::Color(crate::commands::color_param(p, "edgeColor", [0.0, 0.0, 0.0, 1.0])),
"background" | "color" => EdgeMode::Color(crate::commands::color_param(cmd, p, "edgeColor", [0.0, 0.0, 0.0, 1.0])?),
other => return Err(bad(cmd, format!("unknown edge `{other}` (transparency|edgeExtension|black|white|color)"))),
};
let focal = num(p, "focalLength", 0.0);
+7 -3
View File
@@ -63,7 +63,8 @@ pub fn rotated_size(size: Size, deg: f64) -> Size {
pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "image.rotation.arbitrary";
let angle = f64::from(num(p, "angle", 0.0));
// At full precision: an f32 angle can grow the canvas 1 px past what `rotated_size` gives callers.
let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(0.0);
if !angle.is_finite() || angle.abs() > 3600.0 {
return Err(bad(CMD, "angle out of range"));
}
@@ -75,15 +76,18 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result<Value> {
if deg.rem_euclid(360.0).abs() < 1e-9 {
return Ok(json!({"width": s.active().map(|d| d.doc.size.width), "height": s.active().map(|d| d.doc.size.height)}));
}
let bg = s.tools.background;
// The Background stays opaque, whatever the background colour's alpha.
let bg = [s.tools.background[0], s.tools.background[1], s.tools.background[2], 1.0];
// Color Sampler points turn with the canvas (the same map the edit applies to the geometry).
// They are pixel indices, so map the pixel's centre, as the warp samples the pixels.
{
let old = s.active().ok_or(EngineError::NoDocument)?.doc.size;
let new = rotated_size(old, deg);
let (sn, cs) = deg.to_radians().sin_cos();
let (cx, cy) = (f64::from(old.width) / 2.0, f64::from(old.height) / 2.0);
let (nx, ny) = (f64::from(new.width) / 2.0, f64::from(new.height) / 2.0);
s.set_sampler_map(Affine { m: [cs, sn, -sn, cs, nx - (cs * cx - sn * cy), ny - (sn * cx + cs * cy)] });
let a = Affine { m: [cs, sn, -sn, cs, nx - (cs * cx - sn * cy), ny - (sn * cx + cs * cy)] };
s.set_sampler_map(Affine::translate(0.5, 0.5).then(&a).then(&Affine::translate(-0.5, -0.5)));
}
let size = s.edit("Rotate Canvas", |doc, _| {
let old = doc.size;
+21
View File
@@ -81,6 +81,27 @@ fn rotate_arbitrary_other_modes() {
}
}
#[test]
fn rotate_arbitrary_keeps_the_background_opaque_with_a_translucent_background_colour() {
let mut s = session(40, 20, 8, "rgb");
s.execute("tools.setColors", json!({"background": "#00ff0080"})).unwrap();
s.execute("image.rotation.arbitrary", json!({"angle": 30})).unwrap();
let corner = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
assert_eq!(corner, [0.0, 1.0, 0.0, 1.0], "the uncovered corner is opaque background colour");
}
#[test]
fn rotate_arbitrary_keeps_the_full_precision_angle() {
// Rounded to f32 this angle crosses a whole pixel: 1003 px instead of 1002, so a rotated crop
// that sized its canvas with `rotated_size` at f64 would land 1 px off.
let angle = 0.114_706_514_493_370_71;
let mut s = Session::new();
s.execute("file.new", json!({"width": 1000, "height": 1000})).unwrap();
let r = s.execute("image.rotation.arbitrary", json!({"angle": angle})).unwrap();
assert_eq!(rotated_size(Size::new(1000, 1000), angle), Size::new(1002, 1002));
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(1002), Some(1002)));
}
#[test]
fn rotate_arbitrary_rotates_grouped_locked_children_and_preserves_lock() {
let mut s = Session::new();
+8 -6
View File
@@ -40,10 +40,12 @@ fn list_json(d: &Document) -> Value {
json!({"notes": d.notes.iter().enumerate().map(|(i, n)| note_json(i, n)).collect::<Vec<_>>()})
}
fn color_of(p: &Value) -> Option<Color> {
p.get("color")?;
let c = crate::commands::color_param(p, "color", [1.0, 1.0, 0.51, 1.0]);
Some(Color::rgb(c[0], c[1], c[2]))
fn color_of(cmd: &str, p: &Value) -> Result<Option<Color>> {
if p.get("color").is_none() {
return Ok(None);
}
let c = crate::commands::color_param(cmd, p, "color", [1.0, 1.0, 0.51, 1.0])?;
Ok(Some(Color::rgb(c[0], c[1], c[2])))
}
fn index_of(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
@@ -68,7 +70,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
modified: pdf_date(),
..Default::default()
};
if let Some(c) = color_of(p) {
if let Some(c) = color_of(CMD, p)? {
n.color = c;
}
let i = s.edit("New Note", |d, _| {
@@ -90,7 +92,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(a) = p.get("author").and_then(Value::as_str) {
n.author = a.to_string();
}
if let Some(c) = color_of(p) {
if let Some(c) = color_of(CMD, p)? {
n.color = c;
}
if let Some(o) = p.get("open").and_then(Value::as_bool) {
+27 -1
View File
@@ -188,7 +188,8 @@ fn warp_layers(layers: &mut [Layer], h: &Homography, interp: Interp, clip: Rect,
fn apply(doc: &mut Document, q: &[[f64; 2]; 4], h: &Homography, size: (u32, u32), interp: Interp, bg: [f32; 4]) -> Result<()> {
let (w, ht) = size;
let clip = Rect::from_xywh(0, 0, w, ht);
let bg = photocraft_raster::from_rgba(&doc.pixel_format(), bg);
// The Background stays opaque, whatever the background colour's alpha.
let bg = photocraft_raster::from_rgba(&doc.pixel_format(), [bg[0], bg[1], bg[2], 1.0]);
let background_id = doc.background().map(|l| l.id);
warp_layers(&mut doc.layers, h, interp, clip, &bg, background_id)?;
for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
@@ -298,6 +299,31 @@ mod tests {
}
}
/// Corners past the canvas: the uncovered Background is the background colour, opaque even
/// when that colour has alpha (the Background stays opaque).
#[test]
fn uncovered_background_is_opaque() {
let q = [[-20.0, -20.0], [180.0, -20.0], [180.0, 140.0], [-20.0, 140.0]];
let mut s = skewed_ramp(SampleType::U8, &q, 100.0, 80.0);
s.execute("tools.setColors", json!({"background": "#00ff0080"})).unwrap();
s.execute(CMD, json!({"corners": q, "width": 100, "height": 80})).unwrap();
let corner = s.active().unwrap().doc.layers[0].surface().unwrap().rgba(0, 0);
assert_eq!(corner, [0.0, 1.0, 0.0, 1.0]);
}
/// #7557: a quad low on a strongly converging photo (its horizon crosses the canvas, with the
/// canvas centre beyond it) is cropped, not left blank in the background colour.
#[test]
fn a_quad_below_a_horizon_across_the_canvas_keeps_its_content() {
let mut doc = Document::with_background("red", Size::new(100, 100), ColorMode::Rgb, SampleType::U8, Color::WHITE);
doc.layers[0].surface_mut().unwrap().fill_rect(Rect::from_xywh(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]);
let mut s = Session::new();
s.add_document(doc, None);
s.execute(CMD, json!({"corners": [[40, 70], [60, 70], [90, 95], [10, 95]], "width": 50, "height": 39})).unwrap();
let px = s.active().unwrap().doc.layers[0].surface().unwrap().rgba(25, 20);
assert_eq!(px, [1.0, 0.0, 0.0, 1.0]);
}
/// Bad quads and params are refused with an error, and the document is untouched.
#[test]
fn perspective_crop_rejects_bad_quads() {
+57 -3
View File
@@ -859,6 +859,7 @@ fn crop_and_straighten(s: &mut Session, _p: &Value) -> Result<Value> {
let mut nd = Document::new(format!("{} copy {}", doc.name, k + 1), Size::new(pw, ph), doc.mode, doc.depth);
nd.icc_profile = doc.icc_profile.clone();
nd.resolution_dpi = doc.resolution_dpi;
nd.duotone = doc.duotone.clone();
let mut bg = Layer::new("Background", LayerContent::Raster(px));
bg.locks.transparency = true;
bg.locks.position = true;
@@ -871,8 +872,13 @@ fn crop_and_straighten(s: &mut Session, _p: &Value) -> Result<Value> {
// ---------- specs ----------
fn has_doc(s: &Session) -> std::result::Result<(), String> {
s.active().map(|_| ()).ok_or_else(|| "no document open".into())
/// Photoshop greys Crop and Straighten Photos out for Indexed Color documents.
fn not_indexed(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.doc.mode == ColorMode::Indexed {
return Err("not available for Indexed Color documents".into());
}
Ok(())
}
fn always(_: &Session) -> std::result::Result<(), String> {
@@ -907,7 +913,7 @@ pub fn specs() -> Vec<CommandSpec> {
menu: &["File", "Automate"],
shortcut: None,
params: "{} → one new document per photo found on the scan",
enabled: has_doc,
enabled: not_indexed,
run: crop_and_straighten,
journal: true,
},
@@ -1106,6 +1112,54 @@ mod tests {
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
}
/// A light scan with one dark tilted print on it.
fn scan_with_one_photo() -> Document {
let (w, h) = (300usize, 220usize);
let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h];
let (s, co) = 5.0f64.to_radians().sin_cos();
for y in 0..h {
for x in 0..w {
let (dx, dy) = (x as f64 + 0.5 - 150.0, y as f64 + 0.5 - 110.0);
let (u, v) = (co * dx + s * dy, -s * dx + co * dy);
if u.abs() < 80.0 && v.abs() < 55.0 {
px[y * w + x] = [0.2 + (u / 160.0) as f32 * 0.3, 0.25, 0.3, 1.0];
}
}
}
doc_from("scan", &px, w, h, SampleType::U8)
}
#[test]
fn crop_and_straighten_keeps_duotone_inks() {
let mut s = Session::new();
s.add_document(scan_with_one_photo(), None);
s.execute("image.mode.grayscale", json!({})).unwrap();
s.execute(
"image.mode.duotone",
json!({"type": "duotone", "inks": [{"name": "Black", "color": [0, 0, 0]}, {"name": "Orange", "color": [255, 128, 0]}]}),
)
.unwrap();
let src = s.documents()[0].doc.duotone.clone();
assert!(src.is_some());
let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap();
assert_eq!(r["photos"].as_array().unwrap().len(), 1, "{r}");
let d = &s.documents()[1].doc;
assert_eq!(d.mode, ColorMode::Duotone);
assert_eq!(d.duotone, src);
}
#[test]
fn crop_and_straighten_disabled_for_indexed() {
// Photoshop greys the command out for Indexed Color documents.
let mut s = Session::new();
s.add_document(scan_with_one_photo(), None);
s.execute("image.mode.indexedColor", json!({})).unwrap();
assert_eq!(s.documents()[0].doc.mode, ColorMode::Indexed);
assert!(!s.is_enabled("file.automate.cropAndStraightenPhotos"));
assert!(s.execute("file.automate.cropAndStraightenPhotos", json!({})).is_err());
assert_eq!(s.documents().len(), 1);
}
#[test]
fn crop_and_straighten_makes_documents() {
let (w, h) = (500usize, 360usize);
+7
View File
@@ -77,10 +77,17 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
*surf = plugin.apply(surf, canvas, selection.as_ref(), &resolved).map_err(err)?;
return Ok(());
}
crate::commands::check_pixels_unlocked(doc, layer)?;
let keep_alpha = doc.effective_locks(layer).transparency;
let l = doc.layer_mut(layer).ok_or(EngineError::NoLayer(layer))?;
match &mut l.content {
LayerContent::Raster(surf) => {
// Lock Transparency: the plug-in may change colour but not alpha (as built-in filters).
let before = keep_alpha.then(|| surf.clone());
*surf = plugin.apply(surf, canvas, selection.as_ref(), &resolved).map_err(err)?;
if let Some(before) = &before {
crate::filters::keep_alpha(before, surf);
}
Ok(())
}
LayerContent::Smart(_) => {
+50
View File
@@ -155,6 +155,56 @@ fn params_are_validated_and_passed() {
Session::new().execute("plugin.remove", json!({"id": "test.cmds.grey"})).unwrap();
}
#[test]
fn locked_layers_refuse_plugin_filters() {
// Like built-in filters: locked pixels (or Lock All) refuse the run with no undo step.
let id = "test.cmds.locks";
Session::new().execute("plugin.install", json!({"data": b64(&wat_plugin(id, "{}", GREY))})).unwrap();
for lock_all in [false, true] {
let mut s = doc(16);
let layer = s.active().unwrap().active_layer.unwrap();
s.edit("lock", |doc, _| {
let l = doc.layer_mut(layer).unwrap();
if lock_all {
l.locks.all = true;
} else {
l.locks.pixels = true;
}
Ok(())
})
.unwrap();
let before = pixels(&s);
let r = s.execute("plugin.run", json!({"id": id}));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("is locked")), "lock_all {lock_all}: {r:?}");
assert_eq!(pixels(&s), before, "lock_all {lock_all}");
s.execute("edit.undo", json!({})).unwrap();
let l = s.active().unwrap().doc.layer(layer).unwrap();
assert!(!l.locks.pixels && !l.locks.all, "the refused run left no undo step");
// Unlocked, the plug-in runs.
s.execute("plugin.run", json!({"id": id})).unwrap();
assert_ne!(pixels(&s), before);
}
// Lock Transparency: the run changes colour but keeps every pixel's alpha (GREY sets alpha too).
let mut s = doc(16);
let layer = s.active().unwrap().active_layer.unwrap();
s.edit("lock", |doc, _| {
doc.layer_mut(layer).unwrap().locks.transparency = true;
Ok(())
})
.unwrap();
let before = pixels(&s);
s.execute("plugin.run", json!({"id": id})).unwrap();
let after = pixels(&s);
assert_ne!(after, before);
for (a, b) in after.as_chunks::<4>().0.iter().zip(before.as_chunks::<4>().0) {
assert_eq!(a[3], b[3], "alpha kept");
if b[3] > 0.0 {
assert!((a[0] - 0.5).abs() < 1e-3, "colour changed: {a:?}");
}
}
Session::new().execute("plugin.remove", json!({"id": id})).unwrap();
}
#[test]
fn hostile_plugins_fail_without_touching_the_document() {
for (id, body) in [
-1
View File
@@ -1040,7 +1040,6 @@ pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[
"type.textEngine",
"type.recentFonts",
"enhancedControls.scrubbySliderAcceleration",
"enhancedControls.touchGestures",
"rawDefaults.colorSpace",
"rawDefaults.bitDepth",
"rawDefaults.resolution",
+3
View File
@@ -362,6 +362,9 @@ pub(crate) fn edit_groups<T: Named>(groups: &mut Vec<Group<T>>, action: &str, p:
let g = req_str(p, "group", cmd)?;
let to = req_str(p, "name", cmd)?.to_string();
let i = groups.iter().position(|x| x.name == g).ok_or_else(|| bad(cmd, format!("no group \"{g}\"")))?;
if g != to && groups.iter().any(|x| x.name == to) {
return Err(bad(cmd, format!("a group named \"{to}\" already exists")));
}
groups[i].name = to.clone();
Ok(json!({"group": to}))
}
+35
View File
@@ -317,6 +317,23 @@ fn gradient_new_rename_move_delete_groups() {
assert!(s.execute("gradient.presets.edit", json!({"action": "explode"})).is_err());
}
#[test]
fn gradient_rename_group_refuses_a_name_another_group_has() {
let mut s = Session::new();
s.execute("gradient.presets.edit", json!({"action": "newGroup", "name": "Pastels"})).unwrap();
let names = |s: &mut Session| -> Vec<Value> {
s.execute("gradient.presets.list", json!({})).unwrap()["groups"].as_array().unwrap().iter().map(|g| g["name"].clone()).collect()
};
let before = names(&mut s);
assert!(before.contains(&json!("Blues")));
let err = s.execute("gradient.presets.edit", json!({"action": "renameGroup", "group": "Pastels", "name": "Blues"})).unwrap_err();
assert!(err.to_string().contains("already exists"), "{err}");
assert_eq!(names(&mut s), before, "a refused rename leaves the groups unchanged");
// Renaming a group to its own name is fine.
s.execute("gradient.presets.edit", json!({"action": "renameGroup", "group": "Pastels", "name": "Pastels"})).unwrap();
assert_eq!(names(&mut s), before);
}
#[test]
fn presets_persist_through_preferences_json() {
let mut s = Session::new();
@@ -774,3 +791,21 @@ fn a_damaged_preset_set_keeps_the_other_sets() {
assert_eq!(next.presets.gradients.len(), Session::new().presets.gradients.len());
assert_eq!(next.presets.documents, s.presets.documents);
}
// ------------------------------------------------------------------ export presets
#[test]
fn export_presets_survive_a_presets_json_round_trip() {
let mut s = Session::new();
s.execute("file.export.presets.save", json!({"name": "Web", "settings": {"format": "jpg", "quality": 70}})).unwrap();
assert_eq!(s.presets.export_presets.len(), 1);
let saved = s.presets.to_json(&s);
assert_eq!(saved["export_presets"].as_array().map(Vec::len), Some(1));
let mut restored = Session::new();
restored.load_presets_json(saved);
assert_eq!(restored.presets.export_presets.len(), 1);
assert_eq!(restored.presets.export_presets[0].name, "Web");
assert_eq!(restored.presets.export_presets[0].settings.format, "jpg");
}
+34 -2
View File
@@ -654,7 +654,11 @@ fn native_rgb_compatible(page: &PrintPage, handling: &str) -> bool {
&& page.label.as_deref().is_none_or(str::is_empty)
}
/// Print One Copy repeats these.
/// Where the settings of the last print are kept in Preferences' remembered dialog settings.
pub const REMEMBERED: &str = "file.print";
/// Print One Copy repeats these, and Print opens with them. They are kept in the preferences as
/// well, so they survive a relaunch, as Photoshop's do (#7410).
fn remember_print(s: &mut Session, p: &Value) {
let mut remembered = p.clone();
if let Some(o) = remembered.as_object_mut() {
@@ -663,9 +667,31 @@ fn remember_print(s: &mut Session, p: &Value) {
// Output and dry-run choices are not remembered, so a send override must not survive them.
o.remove("send");
}
let kept = remembered.clone();
s.prefs.edit(|prefs| {
prefs.dialogs.insert(REMEMBERED.into(), kept);
});
s.file_menu.last_print = Some(remembered);
}
/// Drops the `printer` of the settings `q` (and its driver settings) when the print server lists
/// printers but not that one, so the job goes to the default printer. An empty list can't tell.
fn drop_vanished_printer(q: &mut Value, listed: &[&str]) {
let Some(name) = q.get("printer").and_then(Value::as_str).filter(|n| !n.is_empty()) else { return };
if listed.is_empty() || listed.iter().any(|l| l.eq_ignore_ascii_case(name)) {
return;
}
if let Some(o) = q.as_object_mut() {
o.remove("printer");
o.remove("printerSettings");
}
}
/// The settings of the last print: this session's, else those remembered from an earlier one.
pub fn last_print(s: &Session) -> Option<Value> {
s.file_menu.last_print.clone().or_else(|| s.prefs().dialogs.get(REMEMBERED).filter(|v| v.is_object()).cloned())
}
/// The `printer` parameter, or the system's default printer.
fn printer_name(p: &Value) -> Result<String> {
if let Some(name) = p.get("printer").and_then(Value::as_str).filter(|v| !v.trim().is_empty()) {
@@ -788,7 +814,13 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
}
fn print_one_copy(s: &mut Session, p: &Value) -> Result<Value> {
let mut q = s.file_menu.last_print.clone().unwrap_or_else(|| json!({}));
let mut q = last_print(s).unwrap_or_else(|| json!({}));
// A printer remembered from an earlier session may be gone: then the default takes the job,
// as the Print dialog falls back (#7410). A list that can't be read decides nothing.
if let Ok(listed) = system_printers(s, &q) {
let names: Vec<&str> = listed["printers"].as_array().into_iter().flatten().filter_map(|p| p["name"].as_str()).collect();
drop_vanished_printer(&mut q, &names);
}
if let (Some(o), Some(extra)) = (q.as_object_mut(), p.as_object()) {
for (k, v) in extra {
o.insert(k.clone(), v.clone());
+42
View File
@@ -226,6 +226,48 @@ fn printer_profile_can_be_an_installed_icc_file() {
let _ = std::fs::remove_dir_all(&dir);
}
/// #7410: the settings of the last print survive a relaunch, as Photoshop's do. They are kept in
/// the preferences (without the output, dry-run and send choices), and a new session with those
/// preferences, before printing anything, repeats them with Print One Copy.
#[test]
fn the_last_print_settings_survive_a_relaunch() {
let mut s = session("rgb", 8);
assert!(last_print(&s).is_none());
s.execute("file.print", json!({"dryRun": true, "copies": 3, "paper": "a5", "scale": 50, "intent": "perceptual"})).unwrap();
let kept = s.prefs().dialogs.get(REMEMBERED).cloned().expect("kept in the preferences");
assert_eq!((&kept["paper"], &kept["scale"], &kept["intent"]), (&json!("a5"), &json!(50), &json!("perceptual")));
assert!(kept.get("dryRun").is_none() && kept.get("output").is_none() && kept.get("send").is_none(), "{kept}");
// A relaunch: a new session with these preferences, nothing printed in it yet.
let mut t = session("rgb", 8);
t.prefs.edit(|p| {
p.dialogs.insert(REMEMBERED.into(), kept.clone());
});
assert_eq!(last_print(&t), Some(kept));
let r = t.execute("file.printOneCopy", json!({"dryRun": true})).unwrap();
assert_eq!(r["copies"], 1);
assert_eq!(r["paper"], json!([419.53, 595.28]));
assert_eq!(r["scale"], 50.0);
}
/// #7410: a printer remembered from an earlier session that the print server no longer lists is
/// dropped before Print One Copy repeats the settings (with its driver settings), so the default
/// printer takes the job; a listed one (in any case) stays, and an empty list can't tell.
#[test]
fn a_vanished_remembered_printer_falls_back_to_the_default() {
let settings = || json!({"printer": "Office", "printerSettings": "00ff", "paper": "a5"});
let mut q = settings();
drop_vanished_printer(&mut q, &["Studio", "Lab"]);
assert_eq!(q, json!({"paper": "a5"}), "gone: the default printer takes it");
for listed in [&["Studio", "office"][..], &[][..]] {
let mut q = settings();
drop_vanished_printer(&mut q, listed);
assert_eq!(q, settings(), "{listed:?}");
}
let mut q = json!({"printer": "", "paper": "a5"});
drop_vanished_printer(&mut q, &["Studio"]);
assert_eq!(q, json!({"printer": "", "paper": "a5"}), "the default printer stays the default");
}
#[test]
fn print_one_copy_repeats_the_last_settings() {
let mut s = session("rgb", 8);
+75 -10
View File
@@ -15,7 +15,7 @@ use photocraft_algo::retouch::{ToneRange, dodge_burn, local_blur, local_sharpen,
use photocraft_color::{BlendMode, PixelFormat, SampleType};
use photocraft_doc::{Document, LayerContent, LayerId};
use photocraft_geom::Rect;
use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke, stroke_coverage};
use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke};
use photocraft_paint::{BrushSettings, Stroke, StrokePoint};
use photocraft_raster::{Surface, from_rgba_into, to_rgba};
use serde_json::{Value, json};
@@ -35,6 +35,64 @@ fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
/// A single stroke's accumulated coverage must stay at or under this many pixels (8192², so a
/// stroke corner to corner across a 24–36 MP canvas fits). Larger footprints return an error
/// instead of allocating.
const MAX_STROKE_PIXELS: u64 = 67_108_864;
/// Refuse a stroke whose footprint would not fit the coverage budget, from the points and brush
/// size alone, before the renderer allocates anything for it.
fn reject_huge_stroke(cmd: &str, stroke: &Stroke) -> Result<()> {
// Dynamics place dabs beyond the input points, so half the tip is not the whole reach:
// Scattering offsets a centre by up to its amount times the tip size, and a Dual Brush dab
// reaches its own radius further. Pad by what those can add so this estimate does not fall
// short of what the renderer will cover. It is only the cheap early-out; the rendered extent
// is admitted for real in `coverage` below.
let b = &stroke.brush;
let size = f64::from(b.size.max(1.0));
let scatter = if b.scattering.enabled { size * f64::from(b.scattering.scatter.jitter.max(0.0)) } else { 0.0 };
let dual = if b.dual_brush.enabled { f64::from(b.dual_brush.size.max(0.0)) * 0.5 } else { 0.0 };
let pad = size.mul_add(0.5, 4.0) + scatter + dual;
let mut min_x = f64::INFINITY;
let mut min_y = f64::INFINITY;
let mut max_x = f64::NEG_INFINITY;
let mut max_y = f64::NEG_INFINITY;
for q in &stroke.points {
min_x = min_x.min(q.x);
min_y = min_y.min(q.y);
max_x = max_x.max(q.x);
max_y = max_y.max(q.y);
}
if !min_x.is_finite() || !min_y.is_finite() || !max_x.is_finite() || !max_y.is_finite() {
return Err(bad(cmd, "point coordinates must be finite"));
}
let w = (max_x - min_x + pad * 2.0).ceil().max(1.0);
let h = (max_y - min_y + pad * 2.0).ceil().max(1.0);
if !w.is_finite() || !h.is_finite() || w > 1.0e9 || h > 1.0e9 {
return Err(bad(cmd, format!("stroke too large (at most {MAX_STROKE_PIXELS} px)")));
}
let area = (w as u64).saturating_mul(h as u64);
if area > MAX_STROKE_PIXELS {
return Err(bad(cmd, format!("stroke too large ({w:.0}×{h:.0} px, at most {MAX_STROKE_PIXELS})")));
}
Ok(())
}
/// The stroke's coverage, with the **rendered** extent admitted before the dense buffer exists.
///
/// `reject_huge_stroke` estimates from the input points; this is the real bound. Rendering is
/// tiled, so it holds only the tiles the dabs touch; the extent is read from those tiles once
/// every dab is placed (tips, dynamics and scattering included) and checked against `max`, and
/// only a stroke that fits is made dense. `max` is a parameter so tests can inject a small budget.
fn coverage_within(cmd: &str, stroke: &Stroke, max: u64) -> Result<(Rect, Vec<f32>)> {
photocraft_paint::retouch::stroke_coverage_within(stroke, max).ok_or_else(|| bad(cmd, format!("stroke too large (at most {max} px)")))
}
/// [`coverage_within`] at the shared allowance.
fn coverage(cmd: &str, stroke: &Stroke) -> Result<(Rect, Vec<f32>)> {
coverage_within(cmd, stroke, MAX_STROKE_PIXELS)
}
/// A pixel layer, a layer with a mask, or a targeted alpha channel / Quick Mask (as the Brush).
fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> {
if crate::channel_cmds::edits_channel(s) {
@@ -312,6 +370,7 @@ fn clamp_samples(fmt: &PixelFormat, data: &mut [f32]) {
fn clone_stamp(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "paint.cloneStamp";
let (stroke, id) = parse_brush(s, p, CMD)?;
reject_huge_stroke(CMD, &stroke)?;
let which = sample_layers(p, CMD)?;
let mode = blend_param(p, CMD)?;
let aligned = flag(p, "aligned", true);
@@ -336,7 +395,7 @@ fn clone_stamp(s: &mut Session, p: &Value) -> Result<Value> {
return periodic::Composite { target: surf, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection: sel, lock, mode }
.draw(bounds, &stroke.brush, &stroke.points, |r| clone_sample(pre, id, &before, which, r, &map, true, CMD));
}
let (bounds, cov) = stroke_coverage(&stroke);
let (bounds, cov) = coverage(CMD, &stroke)?;
// Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned.
let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?;
Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
@@ -592,13 +651,14 @@ fn heal_region(fmt: &PixelFormat, src: &Region, dst: &Region, mask: &[bool]) ->
fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "paint.healingBrush";
let (stroke, id) = parse_brush(s, p, CMD)?;
reject_huge_stroke(CMD, &stroke)?;
let which = sample_layers(p, CMD)?;
let mode = blend_param(p, CMD)?;
let aligned = flag(p, "aligned", true);
let map = clone_mapping(s, p, &stroke, CMD)?;
let off = map.offset();
let dmg = run_stroke(s, "Healing Brush", id, p, |pre, surf, sel, lock| {
let (bounds, cov) = stroke_coverage(&stroke);
let (bounds, cov) = coverage(CMD, &stroke)?;
let (g, cov) = pad_coverage(bounds, &cov, 2);
let fmt = surf.format();
let src = clone_sample(pre, id, surf, which, g, &map, false, CMD)?;
@@ -631,6 +691,10 @@ fn history_brush(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "paint.historyBrush";
let (stroke, id) = parse_brush(s, p, CMD)?;
let mode = blend_param(p, CMD)?;
// The coverage and the source region below are both dense over the stroke's bounds, so a
// thin stroke across a large canvas would still ask for the whole box. Refuse it from the
// points and brush size, before the source surface is cloned or anything is rendered (#4961).
reject_huge_stroke(CMD, &stroke)?;
let live = s.live_commit.take().filter(|l| l.matches(s, CMD, p, &stroke.points));
let from_live = live.is_some();
let src_surface = history_source(s, id, p, CMD)?;
@@ -641,7 +705,7 @@ fn history_brush(s: &mut Session, p: &Value) -> Result<Value> {
}
let fmt = surf.format();
let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) };
let (bounds, cov) = stroke_coverage(&stroke);
let (bounds, cov) = coverage(CMD, &stroke)?;
let paint = Region::read(&src, bounds);
Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
})?;
@@ -718,12 +782,12 @@ enum SpotType {
/// Photoshop 25.4 (measured): a dab changes exactly the brush's footprint, and Content-Aware takes
/// its texture from around it, as Edit › Fill does from its window
/// ([`crate::fill_cmds::sampling_window`] of the stroke's bounds), which is what this samples.
fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: SpotType, all: bool, sel: Option<&Surface>, lock: bool) -> Rect {
let (bounds, cov) = stroke_coverage(stroke);
fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: SpotType, all: bool, sel: Option<&Surface>, lock: bool) -> Result<Rect> {
let (bounds, cov) = coverage("paint.spotHealing", stroke)?;
let size = stroke.brush.size;
let region_rect = crate::fill_cmds::sampling_window(bounds, pre.bounds());
if region_rect.is_empty() {
return Rect::EMPTY;
return Ok(Rect::EMPTY);
}
// Proximity Match looks for its source anywhere in that window.
let margin = (region_rect.width().max(region_rect.height()) / 2) as i32;
@@ -740,7 +804,7 @@ fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind:
}
let hole: Vec<bool> = stroke_cov.iter().map(|c| *c > 0.0).collect();
if !hole.iter().any(|h| *h) {
return Rect::EMPTY;
return Ok(Rect::EMPTY);
}
// Synthesise over a slightly larger domain than the Poisson region, so the solve's boundary pixels
// carry synthesised values that differ from the untouched surroundings: that mismatch is what the
@@ -764,12 +828,13 @@ fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind:
let healed = heal_region(&fmt, &src, &img, &heal_mask);
let dmg = bounds.intersect(&region_rect);
let dmg_cov: Vec<f32> = (dmg.y0..dmg.y1).flat_map(|y| (dmg.x0..dmg.x1).map(move |x| (x, y))).map(|(x, y)| stroke_cov[img.index(x, y)]).collect();
apply_coverage(surf, dmg, &dmg_cov, stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal)
Ok(apply_coverage(surf, dmg, &dmg_cov, stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal))
}
fn spot_healing(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "paint.spotHealing";
let (stroke, id) = parse_brush(s, p, CMD)?;
reject_huge_stroke(CMD, &stroke)?;
let kind = match string(p, "type", "contentAware") {
"contentAware" => SpotType::ContentAware,
"createTexture" => SpotType::CreateTexture,
@@ -777,7 +842,7 @@ fn spot_healing(s: &mut Session, p: &Value) -> Result<Value> {
o => return Err(bad(CMD, format!("unknown type `{o}` (contentAware|createTexture|proximityMatch)"))),
};
let all = sample_all_layers(p);
let dmg = run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| Ok(spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock)))?;
let dmg = run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock))?;
Ok(json!({ "damage": damage_json(dmg) }))
}
@@ -8,19 +8,14 @@ use photocraft_color::{BlendMode, PixelFormat};
use photocraft_compose::pattern::{Placement, Tile, render};
use photocraft_doc::Pattern;
use photocraft_geom::Rect;
use photocraft_paint::retouch::{Footprint, Region, apply_coverage, apply_dab_stroke, over_native, stroke_coverage};
use photocraft_paint::retouch::{Footprint, Region, apply_coverage, apply_dab_stroke, over_native};
use photocraft_paint::{Stroke, StrokePoint};
use photocraft_raster::{Surface, from_rgba_into, to_rgba};
use serde_json::{Value, json};
use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush};
use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush, reject_huge_stroke};
use crate::{Result, Session};
/// A single stroke's accumulated coverage must stay at or under this many pixels (8192², so a
/// stroke corner to corner across a 24–36 MP canvas fits). Larger footprints return an error
/// instead of allocating.
const MAX_STROKE_PIXELS: u64 = 67_108_864;
const STREAM_PHASE_X: u64 = 101;
const STREAM_PHASE_Y: u64 = 102;
@@ -123,45 +118,6 @@ fn stamp_phase(p: &Value, cmd: &str, aligned: bool, first: &StrokePoint) -> Resu
}
}
fn reject_huge_stroke(cmd: &str, stroke: &Stroke) -> Result<()> {
let pad = f64::from(stroke.brush.size.max(1.0)).mul_add(0.5, 4.0);
let mut min_x = f64::INFINITY;
let mut min_y = f64::INFINITY;
let mut max_x = f64::NEG_INFINITY;
let mut max_y = f64::NEG_INFINITY;
for q in &stroke.points {
min_x = min_x.min(q.x);
min_y = min_y.min(q.y);
max_x = max_x.max(q.x);
max_y = max_y.max(q.y);
}
if !min_x.is_finite() || !min_y.is_finite() || !max_x.is_finite() || !max_y.is_finite() {
return Err(bad(cmd, "point coordinates must be finite"));
}
let w = (max_x - min_x + pad * 2.0).ceil().max(1.0);
let h = (max_y - min_y + pad * 2.0).ceil().max(1.0);
if !w.is_finite() || !h.is_finite() || w > 1.0e9 || h > 1.0e9 {
return Err(bad(cmd, format!("stroke too large (at most {MAX_STROKE_PIXELS} px)")));
}
let area = (w as u64).saturating_mul(h as u64);
if area > MAX_STROKE_PIXELS {
return Err(bad(cmd, format!("stroke too large ({w:.0}×{h:.0} px, at most {MAX_STROKE_PIXELS})")));
}
Ok(())
}
fn reject_bounds(cmd: &str, bounds: Rect) -> Result<()> {
if bounds.is_empty() {
return Ok(());
}
let (w, h) = (u64::from(bounds.width()), u64::from(bounds.height()));
let area = w.saturating_mul(h);
if area > MAX_STROKE_PIXELS {
return Err(bad(cmd, format!("stroke too large ({w}×{h} px, at most {MAX_STROKE_PIXELS})")));
}
Ok(())
}
fn placement(phase: (f32, f32), scale: f32, angle: f32) -> Placement {
Placement::new(Rect::EMPTY, false, phase, scale, angle)
}
@@ -194,8 +150,7 @@ fn paint_aligned(
mode: BlendMode,
cmd: &str,
) -> Result<Rect> {
let (bounds, cov) = stroke_coverage(stroke);
reject_bounds(cmd, bounds)?;
let (bounds, cov) = super::coverage(cmd, stroke)?;
if bounds.is_empty() {
return Ok(Rect::EMPTY);
}
@@ -303,9 +258,9 @@ mod tests {
#[test]
fn a_diagonal_across_a_24_mp_canvas_is_not_too_large() {
assert!(reject_huge_stroke("t", &stroke(&[(0.0, 0.0), (6015.0, 3999.0)], 100.0)).is_ok());
assert!(reject_bounds("t", Rect::from_xywh(-60, -60, 6136, 4120)).is_ok());
let across = stroke(&[(0.0, 0.0), (6015.0, 3999.0)], 100.0);
assert!(reject_huge_stroke("t", &across).is_ok());
assert!(super::super::coverage("t", &across).is_ok(), "the rendered extent fits too");
assert!(reject_huge_stroke("t", &stroke(&[(0.0, 0.0), (9000.0, 9000.0)], 100.0)).is_err());
assert!(reject_bounds("t", Rect::from_xywh(0, 0, 9000, 9000)).is_err());
}
}
+6 -4
View File
@@ -71,6 +71,7 @@ fn stroke_bounds(stroke: &Stroke) -> Rect {
fn parse_strokes(s: &Session, p: &Value) -> Result<(Vec<Stroke>, Option<LayerId>)> {
let Some(list) = p.get("strokes") else {
let (stroke, id) = parse_brush(s, p, CMD)?;
reject_huge_stroke(CMD, &stroke)?;
return Ok((vec![stroke], id));
};
let list = list.as_array().ok_or_else(|| bad(CMD, "`strokes` is a list of point lists"))?;
@@ -86,6 +87,7 @@ fn parse_strokes(s: &Session, p: &Value) -> Result<(Vec<Stroke>, Option<LayerId>
o.insert("points".into(), points.clone());
}
let (stroke, layer) = parse_brush(s, &one, CMD)?;
reject_huge_stroke(CMD, &stroke)?;
strokes.push(stroke);
id = layer;
}
@@ -115,12 +117,12 @@ fn plan(s: &Session, p: &Value) -> Result<Plan> {
/// The hole over the plan's window: the strokes' footprints, their enclosed areas and a margin,
/// limited to the selection. Empty when nothing would change.
fn hole(plan: &Plan, sel: Option<&Surface>) -> Vec<bool> {
fn hole(plan: &Plan, sel: Option<&Surface>) -> Result<Vec<bool>> {
let win = plan.window;
let (w, h) = (win.width() as usize, win.height() as usize);
let mut m = vec![false; w * h];
for stroke in &plan.strokes {
let (bounds, cov) = stroke_coverage(stroke);
let (bounds, cov) = super::coverage(CMD, stroke)?;
let bw = bounds.width() as usize;
for (i, c) in cov.iter().enumerate() {
let (x, y) = (bounds.x0 + (i % bw.max(1)) as i32, bounds.y0 + (i / bw.max(1)) as i32);
@@ -141,13 +143,13 @@ fn hole(plan: &Plan, sel: Option<&Surface>) -> Vec<bool> {
*v &= c > 0.0;
}
}
m
Ok(m)
}
/// The filled window and the hole it fills, computed on `doc` (a snapshot). `None` when the
/// layer's own window is fully transparent: nothing to remove and nothing to fill from.
fn run_remove(doc: &mut Document, plan: &Plan, p: &Value, ctx: &crate::jobs::JobCtx, label: &str) -> Result<Option<(Region, Vec<bool>)>> {
let hole = hole(plan, doc.selection.as_ref());
let hole = hole(plan, doc.selection.as_ref())?;
if !hole.iter().any(|m| *m) {
return Err(bad(CMD, "the stroke doesn't cover anything that can change (check the selection)"));
}
+90
View File
@@ -544,6 +544,96 @@ fn history_brush_restores_earlier_pixels() {
}
}
/// #4961 and #6110: every retouch stroke renders its coverage densely over the stroke's bounds
/// and reads a source region over the same box, so a stroke whose box dwarfs the canvas is
/// refused from the points and brush size alone, before anything is cloned or rendered. The
/// document is left as it was, and ordinary strokes still paint at every depth.
#[test]
fn history_brush_refuses_a_stroke_too_large_to_render() {
for depth in DEPTHS {
let mut s = session(40, 20, depth, "rgb");
s.execute("paint.stroke", json!({"points": [[0, 10], [40, 10]], "size": 12, "hardness": 1.0, "color": "#ff0000"})).unwrap();
let before = rgba(&s, 20, 10);
let err = s.execute("paint.historyBrush", json!({"points": [[0, 0], [60000, 60000]], "size": 6, "hardness": 100})).unwrap_err();
assert!(err.to_string().contains("stroke too large"), "depth {depth}: {err}");
assert_eq!(rgba(&s, 20, 10), before, "depth {depth}: a refused stroke leaves the pixels alone");
// The guard is sized for real work: a stroke corner to corner across the canvas still runs.
s.execute("paint.historyBrush", json!({"points": [[0, 0], [40, 20]], "size": 6, "hardness": 100})).unwrap();
assert!(rgba(&s, 20, 10).iter().all(|v| *v > 0.99), "depth {depth}: the Open snapshot is white");
}
}
/// #6110: Pattern Stamp already refused a stroke it could not render; every other retouch stroke
/// reached the same dense conversion unguarded. Each command refuses the oversized stroke without
/// touching the pixels or the history, and an ordinary stroke still succeeds.
#[test]
fn every_retouch_stroke_refuses_a_box_it_cannot_render() {
let huge = json!([[0, 0], [900_000, 900_000]]);
let ok = json!([[2, 2], [30, 16]]);
// Fixtures that are valid for a plain RGB document with one pixel layer.
let cases: [(&str, Value); 4] = [
("paint.cloneStamp", json!({"offset": [4, 0], "size": 8, "hardness": 100})),
("paint.healingBrush", json!({"offset": [4, 0], "size": 8, "hardness": 100})),
("paint.spotHealing", json!({"size": 8, "hardness": 100})),
("paint.historyBrush", json!({"size": 8, "hardness": 100})),
];
for (cmd, base) in cases {
let mut s = session(40, 20, 8, "rgb");
s.execute("paint.stroke", json!({"points": [[0, 10], [40, 10]], "size": 12, "hardness": 1.0, "color": "#ff0000"})).unwrap();
let before = rgba(&s, 20, 10);
let steps = s.active().unwrap().history.past_len();
let with = |points: &Value| {
let mut v = base.clone();
if let Some(o) = v.as_object_mut() {
o.insert("points".into(), points.clone());
}
v
};
let err = s.execute(cmd, with(&huge)).unwrap_err().to_string();
assert!(err.contains("stroke too large"), "{cmd}: {err}");
assert_eq!(rgba(&s, 20, 10), before, "{cmd}: a refused stroke leaves the pixels alone");
assert_eq!(s.active().unwrap().history.past_len(), steps, "{cmd}: and records no history step");
// The allowance still covers ordinary work: this must succeed, not merely avoid the error.
s.execute(cmd, with(&ok)).unwrap_or_else(|e| panic!("{cmd}: an ordinary stroke must work: {e}"));
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{cmd}: and records one step");
}
// Remove takes a list of strokes; each one is charged as it is parsed.
let mut s = session(40, 20, 8, "rgb");
let err = s.execute("paint.remove", json!({"strokes": [[[0, 0], [900_000, 900_000]]], "size": 8})).unwrap_err().to_string();
assert!(err.contains("stroke too large"), "paint.remove: {err}");
}
/// The review on #6110: the estimate from the input points is not the bound. Brush dynamics place
/// dabs beyond those points, so the budget is applied to the extent the renderer actually produced,
/// before the dense buffer is allocated. An injected budget makes that observable without asking
/// for a stroke big enough to exhaust anything.
#[test]
fn the_budget_is_applied_to_the_rendered_extent_not_the_input_points() {
use photocraft_paint::{BrushSettings, Stroke, StrokePoint};
let mut brush = BrushSettings { size: 24.0, hardness: 1.0, ..Default::default() };
brush.scattering.enabled = true;
brush.scattering.scatter.jitter = 6.0;
let stroke = Stroke { brush, points: vec![StrokePoint::new(10.0, 10.0, 1.0), StrokePoint::new(40.0, 10.0, 1.0)] };
// What the renderer really covered, once scattering has placed every dab.
let (bounds, cov) = super::coverage_within("t", &stroke, u64::MAX).unwrap();
let rendered = u64::from(bounds.width()) * u64::from(bounds.height());
assert_eq!(cov.len() as u64, rendered, "the dense buffer is exactly the rendered extent");
// Scattering reaches past the points plus half the tip, which is what the estimate alone sees.
let points_only = (40.0 - 10.0 + 24.0 + 8.0) * (24.0 + 8.0);
assert!(rendered as f64 > points_only, "scattering expanded the stroke: {rendered} vs {points_only}");
// A budget one pixel under what it rendered refuses it; exactly the rendered extent fits.
let err = super::coverage_within("t", &stroke, rendered - 1).unwrap_err().to_string();
assert!(err.contains("stroke too large"), "{err}");
assert!(super::coverage_within("t", &stroke, rendered).is_ok(), "the rendered extent itself fits");
}
#[test]
fn history_brush_reads_a_source_when_its_pixels_were_locked() {
// Given a white layer locked in history state 1, then unlocked and filled red.
+35 -5
View File
@@ -365,7 +365,7 @@ mod tests {
#[test]
fn a_right_angle_rotation_moves_points() {
// 90° clockwise about the centre: the doc centre stays put.
// 90° clockwise about the centre: pixel (x, y) of the 100×80 canvas goes to (79 - y, x).
let mut s = session();
s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap();
s.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "cw"})).unwrap();
@@ -373,8 +373,7 @@ mod tests {
assert_eq!(p.len(), 1);
let pos = p[0]["position"].as_array().unwrap();
let (x, y) = (pos[0].as_f64().unwrap(), pos[1].as_f64().unwrap());
// The new canvas is 80×100, so the centre is (40, 50).
assert!((x - 40.0).abs() < 1e-6 && (y - 50.0).abs() < 1e-6, "{pos:?}");
assert!((x - 39.0).abs() < 1e-6 && (y - 50.0).abs() < 1e-6, "{pos:?}");
}
#[test]
@@ -406,15 +405,46 @@ mod tests {
}
}
#[test]
fn an_arbitrary_rotation_keeps_points_on_their_pixel() {
// The pixel at (3, 3) of the 100×80 document, and where each turn moves it.
for (angle, direction, at) in [(90, "cw", [76.0, 3.0]), (90, "ccw", [3.0, 96.0]), (180, "cw", [96.0, 76.0])] {
let mut s = session();
s.edit("paint", |doc, _| {
let surf = doc.layers[0].surface_mut().unwrap();
let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]);
surf.fill_rect(Rect::new(3, 3, 4, 4), &black);
Ok(())
})
.unwrap();
s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap();
s.execute("view.colorSamplers.add", json!({"x": 0, "y": 0})).unwrap();
s.execute("image.rotation.arbitrary", json!({"angle": angle, "direction": direction})).unwrap();
assert_eq!(s.take_samplers_removed(), 0, "{angle} {direction}: the corner point stays on the canvas");
let p = points(&mut s);
assert_eq!(p.len(), 2, "{angle} {direction}: the corner point stays on the canvas");
assert_eq!(p[0]["position"], json!(at), "{angle} {direction}");
assert_eq!(p[0]["rgb"], json!([0, 0, 0]), "{angle} {direction}");
}
}
#[test]
fn a_rotated_crop_moves_points() {
// The crop frame is centred on the point, so the point lands at the new canvas centre.
// The crop frame is centred on the point's pixel; turned 90° that pixel lands at (10, 9).
let mut s = session();
s.edit("paint", |doc, _| {
let surf = doc.layers[0].surface_mut().unwrap();
let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]);
surf.fill_rect(Rect::new(50, 40, 51, 41), &black);
Ok(())
})
.unwrap();
s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap();
s.execute("image.crop", json!({"x": 40, "y": 30, "width": 20, "height": 20, "angle": 90})).unwrap();
let p = points(&mut s);
assert_eq!(p.len(), 1);
assert_eq!(p[0]["position"], json!([10.0, 10.0]));
assert_eq!(p[0]["position"], json!([10.0, 9.0]));
assert_eq!(p[0]["rgb"], json!([0, 0, 0]));
}
#[test]
+6
View File
@@ -1065,6 +1065,9 @@ fn delete_filter(s: &mut Session, p: &Value) -> Result<Value> {
edit_filters(s, p, "Delete Smart Filter", |sm| {
let i = filter_index("layer.smartFilter.delete", p, sm)?;
sm.smart_filters.remove(i);
if sm.smart_filters.is_empty() {
sm.filter_mask = None;
}
Ok(())
})
}
@@ -1134,6 +1137,9 @@ fn transfer_filters(s: &mut Session, p: &Value) -> Result<Value> {
match index {
Some(i) => {
src.smart_filters.remove(i);
if src.smart_filters.is_empty() {
src.filter_mask = None;
}
}
None => {
src.smart_filters.clear();
+31
View File
@@ -330,6 +330,37 @@ fn selection_becomes_the_filter_mask() {
assert!(!s.is_enabled("layer.smartFilter.deleteFilterMask"));
}
/// #5619: deleting (or dragging away) the last smart filter removes the filter mask with it, so
/// the next filter takes the new selection instead of the old one.
#[test]
fn removing_the_last_filter_removes_its_filter_mask() {
let mut s = session(8);
paint(&mut s);
let original = flat(&s);
let a = convert(&mut s);
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 16, "height": 48})).unwrap();
s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap();
assert!(active_smart(&s).filter_mask.is_some());
s.execute("layer.smartFilter.delete", json!({})).unwrap();
assert!(active_smart(&s).filter_mask.is_none(), "the last filter takes its mask along");
s.execute("select.rect", json!({"x": 20, "y": 0, "width": 20, "height": 48})).unwrap();
s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap();
let px = flat(&s);
let at = |v: &Vec<[f32; 4]>, x: i32, y: i32| v[(y * W + x) as usize];
assert_eq!(at(&px, 6, 20), at(&original, 6, 20), "the old selection is not filtered");
assert_ne!(at(&px, 30, 20), at(&original, 30, 20), "the new selection is filtered");
// Dragging the only filter to another smart object leaves no mask behind either.
s.execute("select.deselect", json!({})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
paint(&mut s);
let b = convert(&mut s);
s.execute("layer.smartFilter.transfer", json!({"from": a, "to": b, "filter": 0})).unwrap();
let doc = &s.active().unwrap().doc;
let LayerContent::Smart(sm) = &doc.layer(LayerId(a)).unwrap().content else { panic!("not smart") };
assert!(sm.smart_filters.is_empty() && sm.filter_mask.is_none());
}
/// Scales `id` to 10 % around the origin and back, returning the composite.
fn shrink_and_grow(s: &mut Session, id: u64) -> Vec<[f32; 4]> {
s.execute("edit.transform", json!({"layer": id, "matrix": [0.1, 0, 0, 0.1, 0, 0]})).unwrap();
+32
View File
@@ -702,6 +702,38 @@ fn fill_layer_pixel_rewrites_refresh_the_effect_maps() {
assert_eq!(after, fresh, "the effect maps track the cache surface, not the Fill spec alone");
}
#[test]
fn growing_the_canvas_re_renders_a_cached_fill_layer() {
// A PSD fill layer keeps its stored pixels as a fill cache covering only the old canvas.
// Canvas Size, an extending Crop and Reveal All must re-render the fill over the new area,
// as Photoshop does, instead of leaving the added bands transparent (#7362).
let grow: [(&str, Value); 2] = [
("image.canvasSize", json!({"width": 100, "anchor": "left"})),
("image.crop", json!({"x": 0, "y": 0, "width": 100, "height": 48, "deleteCroppedPixels": false})),
];
for (cmd, params) in grow {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 48, "background": "transparent"})).unwrap();
s.execute("layer.newFillLayer.solidColor", json!({"color": "#ff0000"})).unwrap();
s.edit("cache", |doc, active| {
let fmt = doc.pixel_format();
let l = doc.layer_mut(active.unwrap()).unwrap();
let photocraft_doc::LayerContent::Fill(f) = &l.content else { return Err(EngineError::Other("not a fill layer".into())) };
let fill = f.clone();
let mut surface = photocraft_raster::Surface::new(fmt);
surface.fill_rect(photocraft_geom::Rect::new(0, 0, 64, 48), &[1.0, 0.0, 0.0, 1.0]);
l.fill_cache = Some(photocraft_doc::FillCache { fill, surface });
Ok(())
})
.unwrap();
s.execute(cmd, params).unwrap();
let d = &s.active().unwrap().doc;
assert_eq!(d.size.width, 100, "{cmd} grows the canvas");
let px = photocraft_compose::render(d, d.bounds()).get(90, 20);
assert!(px[3] > 0.99 && px[0] > 0.99 && px[1] < 0.01, "{cmd}: the fill covers the added area, got {px:?}");
}
}
#[test]
fn group_effect_maps_follow_child_visibility_and_opacity() {
// A styled group's maps come from its children's composite: hiding a child or changing its
+1 -1
View File
@@ -59,7 +59,7 @@ fn duration_param(cmd: &str, p: &Value) -> Result<Option<usize>> {
}
/// The optional `fps` param, rejected unless it's a finite number in `(0, MAX_FPS]` (#1009).
fn fps_param(cmd: &str, p: &Value) -> Result<Option<f32>> {
pub(crate) fn fps_param(cmd: &str, p: &Value) -> Result<Option<f32>> {
let Some(v) = p.get("fps").filter(|v| !v.is_null()) else { return Ok(None) };
v.as_f64()
.filter(|f| f.is_finite() && *f > 0.0 && *f <= f64::from(MAX_FPS))
+54
View File
@@ -378,6 +378,9 @@ fn apply_transform(
// With a selection only the selected pixels move, and so only the same region of a linked
// mask (#205). Groups, type, shapes and smart objects move whole.
let mask_sel = doc_sel.filter(|_| !moves_whole(l));
// The masks (and so a fill's frame) move, but a fill layer's cached render isn't warped:
// drop it, the fill re-renders from its model (as `transform_layer_geometry` does).
l.fill_cache = None;
match &mut l.content {
LayerContent::Group(g) => {
for c in g.children.iter_mut() {
@@ -992,6 +995,57 @@ mod tests {
assert!(!active_bounds(&s).is_empty());
}
/// A gradient fill layer whose mask (a selection when it was made) frames the gradient over
/// 10..40, with the cached render a PSD import gives it: exactly the pixels the fill renders.
fn cached_gradient_fill() -> Session {
let mut s = session();
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
s.execute("layer.newFillLayer.gradient", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s.edit("cache", |doc, active| {
let (fmt, canvas) = (doc.pixel_format(), doc.bounds());
let l = doc.layer_mut(active.unwrap()).unwrap();
let LayerContent::Fill(f) = &l.content else { panic!("a fill layer") };
let buf = photocraft_compose::render_fill_content(l, f, canvas, &[]);
let mut surface = Surface::new(fmt);
let vals: Vec<f32> = buf.px.iter().flat_map(|p| photocraft_raster::from_rgba(&fmt, *p)).collect();
surface.write_region(canvas, &vals);
l.fill_cache = Some(photocraft_doc::FillCache { fill: f.clone(), surface });
Ok(())
})
.unwrap();
s
}
/// How far the composite is from the composite with the fill re-rendered from its model
/// (cache dropped): the largest channel difference.
fn off_from_fresh(s: &Session) -> f32 {
let st = s.active().unwrap();
let mut fresh: Document = (*st.doc).clone();
fresh.layer_mut(st.active_layer.unwrap()).unwrap().fill_cache = None;
let (a, b) = (photocraft_compose::render(&st.doc, st.doc.bounds()).px, photocraft_compose::render(&fresh, fresh.bounds()).px);
a.iter().zip(&b).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs())).fold(0.0, f32::max)
}
#[test]
fn transforming_a_fill_layer_drops_its_stale_cached_render() {
let mut s = cached_gradient_fill();
let off = off_from_fresh(&s);
assert!(off < 0.01, "the cache is the fill's own render: {off}");
// The mask (and so the gradient's frame) moves 50 px right and doubles in height.
s.execute("edit.transform", json!({"matrix": [1, 0, 0, 2, 50, 0]})).unwrap();
let off = off_from_fresh(&s);
assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}");
}
#[test]
fn warping_a_fill_layer_drops_its_stale_cached_render() {
let mut s = cached_gradient_fill();
s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap();
let off = off_from_fresh(&s);
assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}");
}
#[test]
fn type_moves_with_the_move_command() {
let mut s = session();
+34 -5
View File
@@ -34,14 +34,14 @@ fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
}
fn f32p(p: &Value, k: &str) -> Option<f32> {
p.get(k).and_then(Value::as_f64).map(|v| v as f32)
p.get(k).and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite())
}
fn color(v: &Value) -> Option<Color> {
match v {
Value::Array(a) if a.len() >= 3 => {
let c: Vec<f32> = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();
Some(Color::rgba(c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0)))
c.iter().take(4).all(|v| v.is_finite()).then(|| Color::rgba(c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0)))
}
Value::String(s) => {
let s = s.trim_start_matches('#');
@@ -504,8 +504,9 @@ pub fn style_paragraphs(t: &mut TextLayer, a: usize, b: usize, f: &dyn Fn(&mut P
t.paragraphs = out.into_iter().map(|(len, style)| ParagraphRun { len, style }).collect();
}
/// Replaces bytes `a..b` with `new`, keeping styles: inserted text takes the style of the
/// character before it (or after it at the start).
/// Replaces bytes `a..b` with `new`, keeping styles: replacing a selection keeps the style of its
/// first character (as Photoshop does, so retyping a smaller second line stays small); inserting
/// at a caret takes the style of the character before it (or after it at the start).
pub fn replace_text(t: &mut TextLayer, a: usize, b: usize, new: &str) {
fn adjust<S: Clone + PartialEq>(runs: Vec<(usize, S)>, a: usize, b: usize, ins: usize, trailing_paragraph: bool) -> Vec<(usize, S)> {
let mut out: Vec<(usize, S)> = Vec::new();
@@ -521,7 +522,15 @@ pub fn replace_text(t: &mut TextLayer, a: usize, b: usize, new: &str) {
*acc += r.0;
Some((s, s + r.0))
})
.position(|(s, e)| if a == 0 { e > 0 || s == 0 } else { a > s && a <= e })
.position(|(s, e)| {
if a == 0 {
e > 0 || s == 0
} else if a < b {
a >= s && a < e
} else {
a > s && a <= e
}
})
.unwrap_or(0)
};
for (i, (len, st)) in runs.into_iter().enumerate() {
@@ -770,6 +779,7 @@ fn info(s: &Session, p: &Value) -> Result<Value> {
/// paragraph `box`, `orientation`, character and paragraph keys, starting from the default type
/// styles in the foreground colour. Shared with the Type Mask tools' `type.createSelection`.
pub(crate) fn new_text_layer(s: &Session, p: &Value, cmd: &str) -> Result<TextLayer> {
crate::commands::check_f32_values(cmd, p)?;
let orientation = match p.get("orientation") {
None => Orientation::Horizontal,
Some(Value::String(value)) if value == "horizontal" => Orientation::Horizontal,
@@ -1546,6 +1556,25 @@ mod tests {
assert_eq!(t.runs[0].style.size_pt, 40.0);
}
/// Replacing a selected smaller second line (by typing or pasting) keeps its size, not the
/// first line's, whose line break precedes the selection.
#[test]
fn replacing_a_selection_keeps_its_first_characters_style() {
let mut s = session();
let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "BIG\nsmall", "size": 40})).unwrap()["layer"].as_u64().unwrap();
s.execute("type.edit", json!({"layer": id, "runs": [{"start": 4, "end": 9, "size": 12}]})).unwrap();
s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 9, "text": "AIR"}})).unwrap();
let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| (r.len, r.style.size_pt)).collect::<Vec<_>>();
assert_eq!(text_layer(&s, id).text, "BIG\nAIR");
assert_eq!(sizes(&s), [(4, 40.0), (3, 12.0)]);
// A mixed selection takes its first character's style.
s.execute("type.edit", json!({"layer": id, "replace": {"start": 2, "end": 6, "text": "xy"}})).unwrap();
assert_eq!(sizes(&s), [(4, 40.0), (1, 12.0)]);
// Inserting at a caret still follows the character before it.
s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 4, "text": "!"}})).unwrap();
assert_eq!(sizes(&s), [(5, 40.0), (1, 12.0)]);
}
fn kerning_of(s: &Session, id: u64) -> Vec<(Kerning, f32)> {
let t = text_layer(s, id);
let mut out = Vec::new();
+19 -3
View File
@@ -1091,9 +1091,25 @@ fn path_rename(s: &mut Session, p: &Value) -> Result<Value> {
fn path_to_selection(s: &mut Session, p: &Value) -> Result<Value> {
let path = resolve_path(s, p.get("name").and_then(Value::as_str))?;
let feather = f64p(p, "feather").unwrap_or(0.0) as f32;
let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true);
let mode = SelectionMode::parse(p.get("mode").and_then(Value::as_str).unwrap_or("replace"));
// Validate before rasterizing or touching selection history. An unchecked feather value
// could silently become zero (negative/string), or expand into an excessive blur.
let feather = match p.get("feather") {
None => 0.0,
Some(v) => v
.as_f64()
.filter(|n| n.is_finite() && (0.0..=1000.0).contains(n))
.ok_or_else(|| bad("path.toSelection", "`feather` must be a finite number within 0..1000"))? as f32,
};
let aa = match p.get("antiAlias") {
None => true,
Some(Value::Bool(v)) => *v,
_ => return Err(bad("path.toSelection", "`antiAlias` must be a boolean")),
};
let mode = match p.get("mode") {
None => SelectionMode::Replace,
Some(Value::String(v)) if matches!(v.as_str(), "replace" | "add" | "subtract" | "intersect") => SelectionMode::parse(v),
_ => return Err(bad("path.toSelection", "`mode` must be replace, add, subtract or intersect")),
};
let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds();
let mut mask = vector::fill_rasterizer(&path, vector::DEFAULT_TOLERANCE).render(area);
if !aa {
+57
View File
@@ -335,6 +335,63 @@ fn path_to_selection_matches_analytic_shape() {
assert!(m[100 * 200 + 160] > 0.2 && m[100 * 200 + 160] < 0.8);
}
#[test]
fn path_make_selection_rejects_invalid_options_without_changing_history() {
let mut s = session(80, 80, 8);
s.execute("path.set", json!({"path": {"subpaths": [{"knots": [[12, 12], [60, 12], [60, 60], [12, 60]]}]}})).unwrap();
s.execute("select.rect", json!({"x": 20, "y": 20, "width": 12, "height": 12})).unwrap();
let before = doc(&s).clone();
let history = s.active().unwrap().history.past_len();
for opts in [
json!({"feather": -1}),
json!({"feather": 1001}),
json!({"feather": 1e100}),
json!({"feather": "4"}),
json!({"feather": true}),
json!({"antiAlias": "false"}),
json!({"antiAlias": 1}),
json!({"mode": "union"}),
json!({"mode": 42}),
] {
assert!(s.execute("path.toSelection", opts.clone()).is_err(), "accepted invalid Make Selection options: {opts}");
assert_eq!(*doc(&s), before, "invalid Make Selection modified the document: {opts}");
assert_eq!(s.active().unwrap().history.past_len(), history, "invalid Make Selection changed history: {opts}");
}
}
#[test]
fn open_pen_paths_make_the_same_selection_as_closed_paths() {
// The pen's unfinished work path should be implicitly closed when rasterized into a selection.
let mut s = session(80, 80, 8);
let knots = json!([[12, 12], [52, 12], [52, 52], [12, 52]]);
for (aa, feather) in [(false, 0.0), (true, 0.0), (false, 3.0), (true, 3.0)] {
let mut masks = Vec::new();
for closed in [false, true] {
s.execute("path.set", json!({"path": {"subpaths": [{"closed": closed, "knots": knots}]}})).unwrap();
s.execute("path.toSelection", json!({"antiAlias": aa, "feather": feather, "mode": "replace"})).unwrap();
masks.push(selection_mask(&s));
}
assert_eq!(masks[0], masks[1], "open and closed paths differ (antiAlias={aa}, feather={feather})");
assert!(masks[0][32 * 80 + 32] > 0.99);
assert_eq!(masks[0][4 * 80 + 4], 0.0);
if feather > 0.0 {
assert!(masks[0].iter().any(|v| *v > 0.0 && *v < 1.0), "feather did not soften the selection");
}
}
// All boolean operations should use the same selection semantics for an open Pen path.
for mode in ["replace", "add", "subtract", "intersect"] {
s.execute("select.rect", json!({"x": 30, "y": 30, "width": 34, "height": 25})).unwrap();
s.execute("path.set", json!({"path": {"subpaths": [{"closed": false, "knots": knots}]}})).unwrap();
s.execute("path.toSelection", json!({"mode": mode, "antiAlias": false})).unwrap();
let mask = selection_mask(&s);
let at = |x: usize, y: usize| mask[y * 80 + x];
assert_eq!(at(20, 20), if matches!(mode, "replace" | "add") { 1.0 } else { 0.0 }, "{mode}: path-only");
assert_eq!(at(60, 40), if matches!(mode, "add" | "subtract") { 1.0 } else { 0.0 }, "{mode}: previous-only");
assert_eq!(at(40, 40), if mode == "subtract" { 0.0 } else { 1.0 }, "{mode}: overlap");
}
}
#[test]
fn selection_to_work_path_roundtrip_iou() {
let mut s = session(240, 180, 8);
+6 -4
View File
@@ -301,7 +301,7 @@ fn new_from_file(s: &mut Session, p: &Value) -> Result<Value> {
let fmt = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format();
let Footage { frames, fps: footage_fps } = load_frames(&path, fmt)?;
// An explicit `fps` wins, then the rate the footage implies, then 30.
let fps = p.get("fps").and_then(Value::as_f64).map(|f| f as f32).or(footage_fps).unwrap_or(30.0);
let fps = crate::timeline_cmds::fps_param("layer.videoLayers.newVideoLayerFromFile", p)?.or(footage_fps).unwrap_or(30.0);
let n = frames.len();
let id = s.edit("New Video Layer from File", |doc, active| {
store(doc);
@@ -341,10 +341,10 @@ fn replace_footage(s: &mut Session, p: &Value) -> Result<Value> {
}
fn interpret_footage(s: &mut Session, p: &Value) -> Result<Value> {
let fps = p.get("fps").and_then(Value::as_f64);
let fps = crate::timeline_cmds::fps_param("layer.videoLayers.interpretFootage", p)?;
edit_video(s, "Interpret Footage", move |v, _| {
if let Some(f) = fps {
v.fps = f as f32;
v.fps = f;
}
Ok(())
})
@@ -426,7 +426,9 @@ pub fn render_video_with(
if frames > crate::timeline_cmds::MAX_DURATION {
return Err(EngineError::Other(format!("the timeline is {frames} frames; Render Video is limited to {} frames", crate::timeline_cmds::MAX_DURATION)));
}
let fps = base.timeline.as_ref().map_or(30.0, |t| t.fps).max(1.0);
// Only the GIF delay reads the rate (frames come from the duration); rates under 1 fps are
// valid timelines, so only an unusable loaded rate falls back to 30.
let fps = base.timeline.as_ref().map(|t| t.fps).filter(|f| f.is_finite() && *f > 0.0).unwrap_or(30.0);
let stem = base.name.rsplit_once('.').map_or(base.name.as_str(), |(a, _)| a).to_string();
let fmt = base.pixel_format();
let bounds = base.bounds();
+59
View File
@@ -151,6 +151,39 @@ fn a_fully_transparent_animated_gif_frame_encodes() {
assert!(f.indices.iter().all(|&i| Some(i) == f.transparent));
}
/// The GIF frame delays (centiseconds, from each Graphic Control Extension) of a Render Video.
fn rendered_gif_delays(s: &Session) -> Vec<u16> {
let mut gif = Vec::new();
render_video_with(
s,
&json!({"format": "gif"}),
|_, bytes| {
gif = bytes.to_vec();
Ok(())
},
|_, _| true,
)
.unwrap();
gif.windows(6).filter(|w| w[..3] == [0x21, 0xF9, 0x04]).map(|w| u16::from_le_bytes([w[4], w[5]])).collect()
}
#[test]
fn animated_gif_delay_follows_timelines_under_one_fps() {
// 0.5 fps is a valid timeline rate; its frames last 2 s, not the 1 s a 1 fps floor gave.
let mut s = session();
s.execute("timeline.create", json!({"duration": 2, "fps": 0.5})).unwrap();
assert_eq!(rendered_gif_delays(&s), [200, 200]);
// A loaded timeline with an unusable rate falls back to 30 fps (3 cs), as with no timeline.
let mut doc = (*s.active().unwrap().doc).clone();
doc.timeline = Some(Timeline::new(2, f32::NAN));
{
let st = s.active_mut().unwrap();
st.doc = std::sync::Arc::new(doc);
st.revision += 1;
}
assert_eq!(rendered_gif_delays(&s), [3, 3]);
}
#[test]
fn inspect_reports_video_layer() {
let dir = tmpdir("vinsp");
@@ -330,6 +363,32 @@ fn a_still_gif_is_one_frame_at_the_default_rate() {
assert_eq!(s.active().unwrap().doc.layer(id).unwrap().video.as_ref().unwrap().fps, 10.0);
}
/// Interpret Footage and New Video Layer from File reject an fps that isn't a finite number in
/// `(0, MAX_FPS]` and keep the layer as it was (#5657). 1e39 used to become an infinite rate the
/// next `.pcraft` save refused.
#[test]
fn an_invalid_frame_rate_is_an_error_and_changes_nothing() {
let mut s = session();
let id = LayerId(s.execute("layer.videoLayers.newBlankVideoLayer", json!({})).unwrap()["layer"].as_u64().unwrap());
let fps = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().video.as_ref().unwrap().fps;
assert_eq!(fps(&s), 30.0);
for bad in [json!(0), json!(-1), json!(1e39), json!("x")] {
assert!(s.execute("layer.videoLayers.interpretFootage", json!({"fps": bad})).is_err(), "fps {bad}");
assert_eq!(fps(&s), 30.0, "fps {bad}");
}
s.execute("layer.videoLayers.interpretFootage", json!({"fps": 24})).unwrap();
assert_eq!(fps(&s), 24.0);
let dir = tmpdir("gifin-badfps");
let path = format!("{dir}/anim.gif");
write_gif(&path, 8, 8, &[([255, 0, 0], 10), ([0, 255, 0], 10)]);
let layers = s.active().unwrap().doc.layer_count();
for bad in [json!(0), json!(-1), json!(1e39), json!("x")] {
assert!(s.execute("layer.videoLayers.newVideoLayerFromFile", json!({"path": path, "fps": bad})).is_err(), "fps {bad}");
assert_eq!(s.active().unwrap().doc.layer_count(), layers, "fps {bad}");
}
}
#[test]
fn video_frames_to_layers_takes_every_gif_frame() {
let dir = tmpdir("gifin-ftl");
+3
View File
@@ -121,6 +121,9 @@ fn warp_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, w: &Warp,
// A selection limits the linked mask exactly as it limits the pixels (#4175, as Free Transform
// and Perspective Warp do, #3083); a layer that moves whole takes its whole mask along.
let mask_sel = doc_sel.filter(|_| !crate::transform_cmds::moves_whole(l));
// The masks (and so a fill's frame) move, but a fill layer's cached render isn't warped:
// drop it, the fill re-renders from its model.
l.fill_cache = None;
match &mut l.content {
LayerContent::Group(g) => {
for c in g.children.iter_mut() {
+50 -15
View File
@@ -70,6 +70,9 @@ pub enum WebMetadata {
None,
Copyright,
CopyrightAndContact,
/// All the XMP, none of the photo's EXIF (camera, date taken, GPS).
AllExceptCameraInfo,
/// All the XMP and the photo's EXIF.
All,
}
@@ -203,8 +206,9 @@ impl WebSettings {
"none" => WebMetadata::None,
"copyright" => WebMetadata::Copyright,
"copyrightAndContact" | "contact" => WebMetadata::CopyrightAndContact,
"all" | "allExceptCameraInfo" => WebMetadata::All,
m => return Err(bad(cmd, format!("unknown metadata `{m}` (none|copyright|copyrightAndContact|all)"))),
"allExceptCameraInfo" => WebMetadata::AllExceptCameraInfo,
"all" => WebMetadata::All,
m => return Err(bad(cmd, format!("unknown metadata `{m}` (none|copyright|copyrightAndContact|allExceptCameraInfo|all)"))),
};
}
if let Some(table) = p.get("colorTable") {
@@ -262,6 +266,7 @@ impl WebSettings {
WebMetadata::None => "none",
WebMetadata::Copyright => "copyright",
WebMetadata::CopyrightAndContact => "copyrightAndContact",
WebMetadata::AllExceptCameraInfo => "allExceptCameraInfo",
WebMetadata::All => "all",
};
let matte = self.matte.map_or("none".to_string(), |c| format!("#{:02x}{:02x}{:02x}", to8(c[0]), to8(c[1]), to8(c[2])));
@@ -387,7 +392,7 @@ pub fn web_xmp(doc: &Document, m: WebMetadata) -> Option<String> {
let xmp = doc.metadata.xmp.as_deref()?;
match m {
WebMetadata::None => None,
WebMetadata::All => Some(xmp.to_string()),
WebMetadata::All | WebMetadata::AllExceptCameraInfo => Some(xmp.to_string()),
WebMetadata::Copyright | WebMetadata::CopyrightAndContact => {
let info = crate::file_cmds::read_file_info(Some(xmp));
let mut keep = serde_json::Map::new();
@@ -405,10 +410,33 @@ pub fn web_xmp(doc: &Document, m: WebMetadata) -> Option<String> {
}
}
/// The photo's EXIF to embed for the metadata choice: only "All" carries it (#7436).
pub fn web_exif(doc: &Document, m: WebMetadata) -> Option<&[u8]> {
doc.metadata.exif.as_deref().map(Vec::as_slice).filter(|_| m == WebMetadata::All)
}
/// The response's warnings: EXIF that a JPEG couldn't hold (one segment, about 64 KB).
fn web_warnings(st: &WebSettings, exif: Option<&[u8]>, dpi: f32) -> Vec<String> {
exif.filter(|x| st.format == WebFormat::Jpeg && !photocraft_codecs::web::jpeg_exif_fits(x, Some(dpi)))
.map(|x| photocraft_codecs::FidelityWarning::MetadataTooLarge { what: "EXIF", bytes: x.len() }.to_string())
.into_iter()
.collect()
}
/// Optimises `rect` of `px` (straight RGBA, `bw` wide) with `st`. `preview` also returns what
/// the file looks like (the dialog's panes); exports skip it.
#[allow(clippy::too_many_arguments)]
pub fn optimize(px: &[[f32; 4]], bw: usize, rect: Rect, st: &WebSettings, icc: Option<&[u8]>, xmp: Option<&str>, dpi: f32, preview: bool) -> Result<Optimized> {
pub fn optimize(
px: &[[f32; 4]],
bw: usize,
rect: Rect,
st: &WebSettings,
icc: Option<&[u8]>,
exif: Option<&[u8]>,
xmp: Option<&str>,
dpi: f32,
preview: bool,
) -> Result<Optimized> {
if bw == 0 || rect.x0 < 0 || rect.y0 < 0 || rect.is_empty() || rect.x1 as usize > bw || (rect.y1 as usize).checked_mul(bw).is_none_or(|end| end > px.len())
{
return Err(other("slice is outside the pixel buffer"));
@@ -460,8 +488,9 @@ pub fn optimize(px: &[[f32; 4]], bw: usize, rect: Rect, st: &WebSettings, icc: O
}
// Save for Web's 0–100 quality → encoder 1–100.
let q = st.quality.max(1);
let bytes = photocraft_codecs::web::encode_jpeg_rgb8(ww, hh, &rgb, q, st.progressive, st.optimized, icc.filter(|_| st.embed_icc), Some(dpi), xmp)
.map_err(e)?;
let bytes =
photocraft_codecs::web::encode_jpeg_rgb8(ww, hh, &rgb, q, st.progressive, st.optimized, icc.filter(|_| st.embed_icc), Some(dpi), exif, xmp)
.map_err(e)?;
if preview {
// The preview shows the compression artefacts.
look = match photocraft_codecs::decode(&bytes) {
@@ -873,7 +902,9 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u
let bw = wdoc.size.width as usize;
let icc = wdoc.icc_profile.as_deref().map(|v| v.as_slice());
let xmp = web_xmp(&doc, st.metadata);
let exif = web_exif(&doc, st.metadata);
let dpi = wdoc.resolution_dpi;
let warnings = web_warnings(&st, exif, dpi);
let all = slices::resolve(&doc);
let pick = p.get("slices").and_then(Value::as_str).unwrap_or("all");
let numbers: Option<Vec<u64>> = p.get("numbers").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect());
@@ -895,18 +926,18 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u
}
// Estimate only (the dialog's annotations): the whole image, or each chosen slice.
if single.is_none() && dir.is_none() {
let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?;
let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?;
return Ok(
json!({"format": o.ext, "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "colorTable": o.color_table.iter().map(|c| rgb_hex(*c)).collect::<Vec<_>>(), "transparentIndex": o.transparent_index}),
);
}
if let Some(path) = single.filter(|_| dir.is_none() && (all.len() == 1 || p.get("slices").is_none())) {
let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?;
let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?;
write(path, &o.bytes)?;
remember_web_settings(s, cmd, &last_web);
s.file_menu.last_web = Some(last_web);
crate::automate_cmds::fire_event(s, "export");
return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors}));
return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "warnings": warnings}));
}
let dir =
dir.map(str::to_string).or_else(|| single.and_then(|f| std::path::Path::new(f).parent().map(|d| d.to_string_lossy().into_owned()))).unwrap_or_default();
@@ -961,7 +992,7 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u
cells.push((piece, bg, text));
continue;
}
let o = optimize(&buf.px, bw, piece, &st, icc, xmp.as_deref(), dpi, false)?;
let o = optimize(&buf.px, bw, piece, &st, icc, exif, xmp.as_deref(), dpi, false)?;
let stem = if split { format!("{}_{:02}", slice_file(&r.name), k + 1) } else { slice_file(&r.name) };
let name = unique(&stem, o.ext);
let rel = if images.is_empty() { name.clone() } else { format!("{images}/{name}") };
@@ -997,7 +1028,9 @@ fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u
remember_web_settings(s, cmd, &last_web);
s.file_menu.last_web = Some(last_web);
crate::automate_cmds::fire_event(s, "export");
Ok(json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height}))
Ok(
json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height, "warnings": warnings}),
)
}
// ---------- Export Preferences / Quick Export ----------
@@ -1108,19 +1141,21 @@ fn quick_export(s: &mut Session, p: &Value) -> Result<Value> {
let (wdoc, _, _) = web_document(&doc, &json!({}), &st)?;
let buf = photocraft_compose::flatten(&wdoc);
let xmp = web_xmp(&doc, st.metadata);
let exif = web_exif(&doc, st.metadata);
let opt = optimize(
&buf.px,
wdoc.size.width as usize,
wdoc.bounds(),
&st,
wdoc.icc_profile.as_deref().map(|v| v.as_slice()),
exif,
xmp.as_deref(),
wdoc.resolution_dpi,
false,
)?;
write_file(&path, &opt.bytes)?;
crate::automate_cmds::fire_event(s, "export");
Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len()}))
Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len(), "warnings": web_warnings(&st, exif, wdoc.resolution_dpi)}))
}
// ---------- Generate › Image Assets ----------
@@ -1430,7 +1465,7 @@ pub fn generate_assets(doc: &Document, dir: &str) -> (Vec<String>, Vec<Value>) {
return Ok(reported);
}
let buf = photocraft_compose::flatten(&wdoc);
let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, wdoc.resolution_dpi, false)?;
let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, None, wdoc.resolution_dpi, false)?;
let (out, reported) = asset_output_path(dir, &rel)?;
write_file(&out, &o.bytes)?;
written.insert(key);
@@ -1504,7 +1539,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save for Web (Legacy)…",
&["File", "Export"],
Some("Cmd+Alt+Shift+S"),
r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60,"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|all"="copyright","convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes}"##,
r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60,"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|allExceptCameraInfo|all"="copyright" (EXIF only with all),"convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes, warnings}"##,
has_doc,
save_for_web
),
@@ -1522,7 +1557,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Quick Export",
&[],
None,
r##"{"path":str? (required unless Export Preferences › Location is "sameFolder" and the document is saved)} → {path, format, bytes}"##,
r##"{"path":str? (required unless Export Preferences › Location is "sameFolder" and the document is saved)} → {path, format, bytes, warnings}"##,
native_doc,
quick_export
),
@@ -7,13 +7,13 @@ fn color_replacement_preserves_pixel_membership_and_transparency() {
for dither in ["none", "diffusion", "pattern", "noise"] {
let p = json!({"format": format, "colorTable": ["#ff0000", "#0000ff"], "dither": dither, "matte": "none"});
let original = WebSettings::from_params(&p, "test").unwrap();
let before = optimize(&px, 4, Rect::new(0, 0, 4, 1), &original, None, None, 72.0, true).unwrap();
let before = optimize(&px, 4, Rect::new(0, 0, 4, 1), &original, None, None, None, 72.0, true).unwrap();
let mut edited = p.clone();
// Replace red with blue: re-quantization would now send all opaque pixels to blue.
edited["colorTableEdits"] = json!({"0": "#0000ff", "1": "#00ff00"});
let settings = WebSettings::from_params(&edited, "test").unwrap();
assert_eq!(WebSettings::from_params(&settings.to_params(), "test").unwrap(), settings);
let after = optimize(&px, 4, Rect::new(0, 0, 4, 1), &settings, None, None, 72.0, true).unwrap();
let after = optimize(&px, 4, Rect::new(0, 0, 4, 1), &settings, None, None, None, 72.0, true).unwrap();
for (old, new) in before.preview.as_chunks::<4>().0.iter().zip(after.preview.as_chunks::<4>().0) {
if old[3] == 0 {
assert_eq!(new[3], 0);
@@ -81,8 +81,8 @@ fn malformed_tables_and_out_of_bounds_slices_return_errors() {
}
let settings = WebSettings::default();
for (bw, rect) in [(0, Rect::new(0, 0, 1, 1)), (1, Rect::new(-1, 0, 1, 1)), (1, Rect::new(0, 0, 2, 1)), (1, Rect::new(0, 0, 1, i32::MAX))] {
assert!(optimize(&[[0.0; 4]], bw, rect, &settings, None, None, 72.0, false).is_err());
assert!(optimize(&[[0.0; 4]], bw, rect, &settings, None, None, None, 72.0, false).is_err());
}
let settings = WebSettings::from_params(&json!({"format": "gif", "colorTable": vec!["#000000"; 256]}), "test").unwrap();
assert!(optimize(&[[0.0; 4]], 1, Rect::new(0, 0, 1, 1), &settings, None, None, 72.0, true).is_err());
assert!(optimize(&[[0.0; 4]], 1, Rect::new(0, 0, 1, 1), &settings, None, None, None, 72.0, true).is_err());
}
+168 -8
View File
@@ -476,11 +476,8 @@ fn same_file_sees_through_other_names_for_one_file() {
assert!(crate::file_cmds::same_file(&a, &format!("{dir}/./a.png")));
assert!(!crate::file_cmds::same_file(&a, &c));
assert!(!crate::file_cmds::same_file(&a, &b), "a missing file is not the same file");
#[cfg(unix)]
{
std::fs::hard_link(&a, &b).unwrap();
assert!(crate::file_cmds::same_file(&a, &b), "a hard link is the same file");
}
std::fs::hard_link(&a, &b).unwrap();
assert!(crate::file_cmds::same_file(&a, &b), "a hard link is the same file");
#[cfg(windows)]
assert!(crate::file_cmds::same_file(&a, &format!("{dir}/A.PNG")), "NTFS names ignore case");
}
@@ -738,7 +735,7 @@ fn previews_show_the_optimised_pixels() {
let buf = photocraft_compose::flatten(&wd);
for f in ["jpeg", "gif", "png8", "png24", "wbmp"] {
let st = WebSettings::from_params(&json!({"format": f, "quality": 90, "transparency": false}), "x").unwrap();
let o = optimize(&buf.px, 64, wd.bounds(), &st, None, None, 72.0, true).unwrap();
let o = optimize(&buf.px, 64, wd.bounds(), &st, None, None, None, 72.0, true).unwrap();
assert_eq!(o.preview.len(), 64 * 48 * 4, "{f}");
// Red square centre stays red (WBMP: dark).
let i = (16 * 64 + 16) * 4;
@@ -748,7 +745,7 @@ fn previews_show_the_optimised_pixels() {
} else {
assert!(px[0] > 200 && px[1] < 60 && px[2] < 60, "{f}: {px:?}");
}
let none = optimize(&buf.px, 64, wd.bounds(), &st, None, None, 72.0, false).unwrap();
let none = optimize(&buf.px, 64, wd.bounds(), &st, None, None, None, 72.0, false).unwrap();
assert!(none.preview.is_empty());
assert_eq!(none.bytes, o.bytes);
}
@@ -759,7 +756,7 @@ fn jpeg_preview_at_odd_sizes() {
for (w, h, q) in [(640usize, 431usize, 90), (640, 430, 60), (333, 222, 30)] {
let px: Vec<[f32; 4]> = (0..w * h).map(|i| [((i % w) as f32 / w as f32), 0.3, ((i / w) as f32 / h as f32), 1.0]).collect();
let st = WebSettings::from_params(&json!({"format": "jpeg", "quality": q}), "x").unwrap();
let o = optimize(&px, w, Rect::new(0, 0, w as i32, h as i32), &st, None, None, 72.0, true).unwrap();
let o = optimize(&px, w, Rect::new(0, 0, w as i32, h as i32), &st, None, None, None, 72.0, true).unwrap();
for &(x, y) in &[(10usize, 10usize), (w - 10, h / 2), (w / 2, h - 5)] {
let i = (y * w + x) * 4;
let want = [(x as f32 / w as f32 * 255.0) as i32, 76, (y as f32 / h as f32 * 255.0) as i32];
@@ -817,3 +814,166 @@ fn overlapping_slices_keep_the_later_slice_in_html() {
#[path = "color_table_tests.rs"]
mod color_table_tests;
/// A little-endian camera EXIF: IFD0 with Make, Orientation 6, 300 ppi and pointers to an Exif
/// IFD (DateTimeOriginal) and a GPS IFD (GPSLatitudeRef); IFD0 links to an IFD1 thumbnail.
fn camera_exif() -> Vec<u8> {
let entry = |v: &mut Vec<u8>, tag: u16, ty: u16, count: u32, value: u32| {
v.extend_from_slice(&tag.to_le_bytes());
v.extend_from_slice(&ty.to_le_bytes());
v.extend_from_slice(&count.to_le_bytes());
v.extend_from_slice(&value.to_le_bytes());
};
let (ifd0, data0) = (8u32, 8 + 2 + 7 * 12 + 4);
let (make, xres, yres) = (data0, data0 + 10, data0 + 18);
let exif_ifd = data0 + 26;
let date = exif_ifd + 2 + 12 + 4;
let gps_ifd = date + 20;
let ifd1 = gps_ifd + 2 + 12 + 4;
let mut v = b"II*\0".to_vec();
v.extend_from_slice(&ifd0.to_le_bytes());
v.extend_from_slice(&7u16.to_le_bytes());
entry(&mut v, 0x010F, 2, 9, make);
entry(&mut v, 0x0112, 3, 1, 6);
entry(&mut v, 282, 5, 1, xres);
entry(&mut v, 283, 5, 1, yres);
entry(&mut v, 296, 3, 1, 2);
entry(&mut v, 0x8769, 4, 1, exif_ifd);
entry(&mut v, 0x8825, 4, 1, gps_ifd);
v.extend_from_slice(&ifd1.to_le_bytes());
v.extend_from_slice(b"TestMake\0\0");
for _ in 0..2 {
v.extend_from_slice(&300u32.to_le_bytes());
v.extend_from_slice(&1u32.to_le_bytes());
}
v.extend_from_slice(&1u16.to_le_bytes());
entry(&mut v, 0x9003, 2, 20, date);
v.extend_from_slice(&0u32.to_le_bytes());
v.extend_from_slice(b"2024:05:01 10:30:00\0");
v.extend_from_slice(&1u16.to_le_bytes());
entry(&mut v, 0x0001, 2, 2, u32::from_le_bytes(*b"N\0\0\0"));
v.extend_from_slice(&0u32.to_le_bytes());
v.extend_from_slice(&1u16.to_le_bytes());
entry(&mut v, 0x0103, 3, 1, 6);
v.extend_from_slice(&0u32.to_le_bytes());
assert_eq!(v.len(), ifd1 as usize + 18);
v
}
/// The payload (after `Exif\0\0`) of the file's EXIF APP1 segment, read from the markers.
fn exif_app1(bytes: &[u8]) -> Option<Vec<u8>> {
let mut i = 2;
while i + 4 <= bytes.len() && bytes[i] == 0xFF && bytes[i + 1] != 0xDA {
let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize;
let body = &bytes[i + 4..i + 2 + len];
if bytes[i + 1] == 0xE1 && body.starts_with(b"Exif\0\0") {
return Some(body[6..].to_vec());
}
i += 2 + len;
}
None
}
/// IFD0's entries (tag → inline value) and its link to the next IFD, little-endian only.
fn ifd0(tiff: &[u8]) -> (std::collections::HashMap<u16, u32>, u32) {
let u16_at = |o: usize| u16::from_le_bytes([tiff[o], tiff[o + 1]]);
let u32_at = |o: usize| u32::from_le_bytes([tiff[o], tiff[o + 1], tiff[o + 2], tiff[o + 3]]);
assert_eq!(&tiff[..4], b"II*\0");
let at = u32_at(4) as usize;
let n = u16_at(at) as usize;
let tags = (0..n)
.map(|k| {
let e = at + 2 + k * 12;
let value = if u16_at(e + 2) == 3 { u32::from(u16_at(e + 8)) } else { u32_at(e + 8) };
(u16_at(e), value)
})
.collect();
(tags, u32_at(at + 2 + n * 12))
}
fn photo_session(exif: Vec<u8>) -> Session {
let mut s = session(8);
s.execute("file.fileInfo", json!({"copyright": "© Example"})).unwrap();
s.edit("exif", |doc, _| {
doc.metadata.exif = Some(std::sync::Arc::new(exif));
Ok(())
})
.unwrap();
s
}
/// #7436: Save for Web's "All" writes the photo's EXIF, as Save a Copy does: upright
/// (Orientation 1), without the source's thumbnail and at the exported resolution. Every other
/// choice, "All Except Camera Info" included, leaves the camera data (and GPS) out.
#[test]
fn save_for_web_all_writes_the_photos_exif() {
let dir = tmp("exif");
let mut s = photo_session(camera_exif());
let export = |s: &mut Session, metadata: &str| {
let path = format!("{dir}/{metadata}.jpg");
let r = s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "metadata": metadata, "path": path})).unwrap();
(std::fs::read(&path).unwrap(), r)
};
let (all, r) = export(&mut s, "all");
let exif = exif_app1(&all).expect("an EXIF APP1 segment");
let camera = photocraft_algo::exif::read(&exif);
assert_eq!(camera.make.as_deref(), Some("TestMake"));
assert_eq!(camera.date_taken.as_deref(), Some("2024:05:01 10:30:00"));
let (tags, next) = ifd0(&exif);
assert_eq!(tags.get(&0x0112), Some(&1), "the exported pixels are already upright");
assert!(tags.contains_key(&0x8825), "GPS kept");
assert_eq!(next, 0, "the source's thumbnail is not linked");
assert_eq!(photocraft_codecs::exif_resolution(&exif), Some((72.0, 72.0)), "the document's resolution, not the source's 300");
assert!(decode(&format!("{dir}/all.jpg")).meta.xmp.unwrap_or_default().contains("Example"));
for m in ["none", "copyright", "copyrightAndContact", "allExceptCameraInfo"] {
let (bytes, r) = export(&mut s, m);
assert_eq!(exif_app1(&bytes), None, "{m}");
assert_eq!(r["warnings"], json!([]), "{m}");
}
assert_eq!(r["warnings"], json!([]), "it fits");
let xmp = decode(&format!("{dir}/allExceptCameraInfo.jpg")).meta.xmp.unwrap_or_default();
assert!(xmp.contains("Example"), "all the XMP");
assert_eq!(WebSettings::from_params(&json!({"metadata": "allExceptCameraInfo"}), "x").unwrap().to_params()["metadata"], "allExceptCameraInfo");
}
#[test]
fn quick_export_all_writes_the_photos_exif() {
let dir = tmp("quick_exif");
let mut s = photo_session(camera_exif());
let export = |s: &mut Session, metadata: &str| {
s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg", "metadata": metadata})).unwrap();
let path = format!("{dir}/{metadata}.jpg");
let r = s.execute("file.export.quickExport", json!({"path": path})).unwrap();
(std::fs::read(&path).unwrap(), r)
};
let (all, r) = export(&mut s, "all");
assert_eq!(photocraft_algo::exif::read(&exif_app1(&all).expect("EXIF")).make.as_deref(), Some("TestMake"));
assert_eq!(r["warnings"], json!([]));
assert_eq!(exif_app1(&export(&mut s, "copyright").0), None);
assert_eq!(exif_app1(&export(&mut s, "none").0), None);
s.execute("prefs.reset", json!({"path": "export"})).unwrap();
}
/// EXIF too large for its one segment is left out and said so; a truncated one doesn't panic.
#[test]
fn web_exif_that_does_not_fit_is_reported_and_bad_exif_is_harmless() {
let dir = tmp("exif_bad");
let mut big = camera_exif();
big.resize(70_000, 0);
let mut s = photo_session(big);
let path = format!("{dir}/big.jpg");
let r = s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "metadata": "all", "path": path})).unwrap();
assert_eq!(exif_app1(&std::fs::read(&path).unwrap()), None);
assert!(r["warnings"][0].as_str().is_some_and(|w| w.contains("EXIF (70000 bytes)")), "{r}");
s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg", "metadata": "all"})).unwrap();
let r = s.execute("file.export.quickExport", json!({"path": format!("{dir}/quick.jpg")})).unwrap();
assert!(r["warnings"][0].as_str().is_some_and(|w| w.contains("EXIF")), "{r}");
s.execute("prefs.reset", json!({"path": "export"})).unwrap();
for cut in [3, 9, 40, 100] {
let mut s = photo_session(camera_exif()[..cut].to_vec());
let path = format!("{dir}/cut{cut}.jpg");
s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "metadata": "all", "path": path})).unwrap();
assert_eq!(decode(&path).dimensions(), (64, 48));
}
}
@@ -0,0 +1,154 @@
//! #6424: rejecting an overflowing f32 parameter must leave a saveable document and history.
use photocraft_engine::{EngineError, Session};
use serde_json::{Value, json};
fn fresh(mode: &str, depth: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 16, "height": 12, "mode": mode, "depth": depth})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s
}
fn saved(s: &Session) -> Vec<u8> {
photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap()
}
fn rejected(cases: Vec<(&str, Value)>) {
let mut failures = Vec::new();
for (id, p) in cases {
let mut s = fresh("rgb", 8);
let before = saved(&s);
let undo = s.active().unwrap().history.undo_label().map(str::to_owned);
let result = s.execute(id, p.clone());
let save = photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default());
if !matches!(result, Err(EngineError::BadParams { .. })) {
failures.push(format!("{id} {p}: result={result:?}, save error={:?}", save.as_ref().err()));
continue;
}
assert_eq!(save.unwrap(), before, "rejected {id} must not change the document");
assert_eq!(s.active().unwrap().history.undo_label(), undo.as_deref(), "rejected {id} must not add history");
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
#[test]
fn overflowing_layer_styles_are_rejected_before_mutation() {
let mut cases = Vec::new();
for value in [1e39, -1e39] {
for (kind, key) in [
("dropShadow", "angle"),
("innerShadow", "angle"),
("outerGlow", "size"),
("innerGlow", "size"),
("stroke", "size"),
("satin", "angle"),
("bevelEmboss", "depth"),
("gradientOverlay", "angle"),
("patternOverlay", "phaseX"),
] {
let id = match kind {
"dropShadow" => "layer.layerStyle.dropShadow",
"innerShadow" => "layer.layerStyle.innerShadow",
"outerGlow" => "layer.layerStyle.outerGlow",
"innerGlow" => "layer.layerStyle.innerGlow",
"stroke" => "layer.layerStyle.stroke",
"satin" => "layer.layerStyle.satin",
"bevelEmboss" => "layer.layerStyle.bevelEmboss",
"gradientOverlay" => "layer.layerStyle.gradientOverlay",
_ => "layer.layerStyle.patternOverlay",
};
let params = json!({key: value});
cases.push((id, params.clone()));
cases.push(("layer.layerStyle.replace", json!({"effects": [{"kind": kind, "params": params}]})));
}
cases.push(("layer.layerStyle.colorOverlay", json!({"color": [value, 0, 0]})));
}
rejected(cases);
}
#[test]
fn overflowing_document_colors_are_rejected_before_mutation() {
let mut cases = Vec::new();
for id in ["layer.newFillLayer.solidColor", "channel.new", "channel.newSpot", "layer.new.artboard", "count.newGroup"] {
for value in [1e39, -1e39] {
for component in 0..4 {
let mut color = [0.5; 4];
color[component] = value;
cases.push((id, json!({"color": color})));
}
}
}
rejected(cases);
}
#[test]
fn overflowing_type_positions_and_colors_are_rejected_before_mutation() {
rejected(vec![
("type.create", json!({"text": "hello", "x": 1e39})),
("type.create", json!({"text": "hello", "y": -1e39})),
("type.create", json!({"text": "hello", "color": [1e39, 0, 0]})),
]);
}
#[test]
fn valid_color_and_style_edits_still_save_and_undo_at_each_depth() {
for mode in ["rgb", "gray", "cmyk", "lab"] {
for depth in [8, 16, 32] {
let mut s = fresh(mode, depth);
let before = saved(&s);
s.execute("layer.layerStyle.dropShadow", json!({"angle": -45, "color": [0.1, 0.3, 0.8]})).unwrap();
let edited = saved(&s);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(saved(&s), before);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(saved(&s), edited);
s.execute("layer.newFillLayer.solidColor", json!({"color": "#4080c0"})).unwrap();
let bytes = saved(&s);
photocraft_format::load_from_bytes(&bytes).unwrap();
}
}
}
#[test]
fn effect_snapshots_cannot_bypass_numeric_validation() {
let mut fx = serde_json::to_value(photocraft_engine::layer_style::effect_from_params("dropShadow", &json!({})).unwrap()).unwrap();
fx["DropShadow"]["angle"] = json!(1e39);
rejected(vec![(
"layer.layerStyle.replace",
json!({"effects": [
{"kind": "colorOverlay", "params": {"color": "#00ff00"}},
{"kind": "dropShadow", "fx": fx, "params": {}}
]}),
)]);
}
#[test]
fn direct_effect_helpers_do_not_introduce_infinity() {
let original = photocraft_engine::layer_style::effect_from_params("dropShadow", &json!({})).unwrap();
for p in [json!({"angle": 1e39}), json!({"color": [0, -1e39, 0]})] {
assert!(photocraft_engine::layer_style::effect_from_params("dropShadow", &p).is_none());
let mut edited = original.clone();
photocraft_engine::layer_style::overlay_effect(&mut edited, &p);
assert_eq!(edited, original);
}
}
#[test]
fn bad_background_color_does_not_partially_change_tool_colors() {
let mut s = fresh("rgb", 32);
let before = (s.tools.foreground, s.tools.background);
let result = s.execute("tools.setColors", json!({"foreground": "#40a0c0", "background": [0, 1e39, 0]}));
assert!(matches!(result, Err(EngineError::BadParams { .. })));
assert_eq!((s.tools.foreground, s.tools.background), before);
}
#[test]
fn finite_hdr_colors_are_preserved_without_unit_clamping() {
let mut s = fresh("rgb", 32);
let id = s.execute("layer.newFillLayer.solidColor", json!({"color": [4.0, -0.5, 0.25]})).unwrap()["layer"].as_u64().unwrap();
let bytes = saved(&s);
let reopened = photocraft_format::load_from_bytes(&bytes).unwrap();
let layer = reopened.layer(photocraft_doc::LayerId(id)).unwrap();
let photocraft_doc::LayerContent::Fill(photocraft_doc::Fill::Solid(c)) = &layer.content else { panic!("expected a solid fill") };
assert_eq!(c.to_rgb(), [4.0, -0.5, 0.25]);
}
+12 -1
View File
@@ -16,7 +16,7 @@ photocraft-raster = { workspace = true }
photocraft-doc = { workspace = true }
photocraft-codecs = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true, features = ["unbounded_depth"] }
serde_json = { workspace = true, features = ["unbounded_depth", "float_roundtrip"] }
thiserror = { workspace = true }
flate2 = { workspace = true }
# Same IEEE CRC-32 the ZIP container needs; already in Cargo.lock through flate2.
@@ -34,5 +34,16 @@ rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
[target.'cfg(target_vendor = "apple")'.dependencies]
libc = "0.2"
# Replacing a file keeps its ACL (#7073). `fcopyfile(COPYFILE_ACL)` is an `unsafe fn` and
# `fclonefileat(CLONE_ACL)` is APFS-only; exacl is a safe wrapper over acl_get_file/acl_set_file.
[target.'cfg(target_os = "macos")'.dependencies]
exacl = "0.13"
# `ReplaceFileW` is how Windows replaces a file without dropping its DACL, named streams
# (Zone.Identifier, the Mark of the Web) and creation time (#7094, #7096). winsafe's `kernel`
# feature is a dependency-free safe wrapper; the workspace forbids writing the FFI call here.
[target.'cfg(windows)'.dependencies]
winsafe = { version = "0.0.29", features = ["kernel"] }
[dev-dependencies]
proptest = { workspace = true }
+33 -10
View File
@@ -25,8 +25,15 @@
//! this module is never reached there; on `wasm32` every call returns the `std` "unsupported"
//! error.
//!
//! Replacing a file also carries its metadata across — permission bits, extended attributes,
//! the "downloaded from the internet" mark and the access-control list — so that saving a
//! document does not quietly undo a security decision someone made about the file. That part is
//! [`meta`], and it is best effort: it never fails a save and never touches the bytes.
//!
//! [`atomic_write_with`] takes an [`AtomicFs`] so tests can inject failures at each step.
pub mod meta;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
@@ -54,9 +61,16 @@ pub trait AtomicFs {
fn remove(&self, path: &Path) -> io::Result<()>;
/// Flush a directory entry change (Unix); a no-op elsewhere.
fn sync_dir(&self, dir: &Path) -> io::Result<()>;
/// Copy the destination's permissions onto the temporary file, so replacing a file keeps its
/// mode. Best effort.
fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()>;
/// Copy the metadata a replacement should keep — mode, extended attributes, ACL — from the
/// file about to be replaced onto the temporary file. Best effort; see [`meta`].
fn copy_metadata(&self, from: &Path, to: &Path) -> io::Result<()>;
/// Replace the **existing** file `to` with `from`. Everywhere but Windows this is
/// [`rename`](Self::rename); on Windows it keeps the destination's DACL, named streams and
/// creation time ([`meta::replace_existing`]). The default is `rename`, which is what the
/// failure-injecting test file systems want.
fn replace_existing(&self, from: &Path, to: &Path) -> io::Result<()> {
self.rename(from, to)
}
}
/// The real file system.
@@ -97,9 +111,11 @@ impl AtomicFs for RealFs {
Ok(())
}
}
fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()> {
let perms = std::fs::metadata(from)?.permissions();
std::fs::set_permissions(to, perms)
fn copy_metadata(&self, from: &Path, to: &Path) -> io::Result<()> {
meta::copy_metadata(from, to)
}
fn replace_existing(&self, from: &Path, to: &Path) -> io::Result<()> {
meta::replace_existing(from, to)
}
fn is_readonly(&self, path: &Path) -> bool {
std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.permissions().readonly())
@@ -206,12 +222,19 @@ pub fn atomic_write_with_progress(fs: &dyn AtomicFs, retry: RenameRetry, path: &
}
let tmp = tmp.ok_or_else(|| io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display())))?;
// Keep the existing file's mode (e.g. 0600) instead of the process default.
if target.exists() {
let _ = fs.copy_permissions(&target, &tmp);
// Keep what the file being replaced carried: its mode (e.g. 0600) instead of the process
// default, its extended attributes, and its ACL. Best effort, and before the swap, so the
// file the user ends up with never passes through a more permissive state.
let replacing = target.exists();
if replacing {
let _ = fs.copy_metadata(&target, &tmp);
}
if let Err(e) = retry_rename(retry, || fs.rename(&tmp, &target)) {
// Replacing an existing file goes through `replace_existing`, which on Windows is the one
// call that can keep the destination's DACL and named streams; creating a new one is a
// plain rename, with nothing to preserve.
let swap = || if replacing { fs.replace_existing(&tmp, &target) } else { fs.rename(&tmp, &target) };
if let Err(e) = retry_rename(retry, swap) {
let _ = fs.remove(&tmp);
return Err(rename_error(e, path));
}
+273
View File
@@ -0,0 +1,273 @@
//! What a replacement keeps from the file it replaces.
//!
//! Saving writes a new file and renames it over the old one, so the user gets a file with the
//! right bytes and none of the old file's history: everything the operating system and other
//! programs had attached to the file that was just unlinked is gone. Some of it is a security
//! decision — *this came from the internet*, *only these people may read it* — so a save that
//! drops it quietly weakens the user's protections (#6603, #7073, #7094, #7095, #7096).
//!
//! | | macOS | Linux | Windows |
//! |---|---|---|---|
//! | permission bits | [`copy_metadata`] | [`copy_metadata`] | [`copy_metadata`] (read-only flag) |
//! | extended attributes (Finder tags, `user.*`) | `copy_xattrs` | `copy_xattrs` | — |
//! | "downloaded from the internet" | `com.apple.quarantine`, an xattr | — | `Zone.Identifier`, a named stream kept by [`replace_existing`] |
//! | access-control list | `copy_acl` (`exacl`) | not carried over (see below) | DACL, kept by [`replace_existing`] |
//! | creation time | not carried over (#6603) | — | kept by [`replace_existing`] |
//!
//! Everything here except [`replace_existing`] is **best effort and never touches the file's
//! bytes**: a save that cannot carry a piece of metadata across is still a save, because a
//! document the user can open matters more than a Finder tag. [`replace_existing`] *is* the
//! replacement step, so it holds the atomicity guarantee instead: it never leaves the
//! destination missing, and it falls back to a plain rename rather than fail a save.
//!
//! Not carried over, and why: Linux POSIX ACLs live in `system.posix_acl_access`, which
//! `listxattr` does not report, so copying the listed attributes misses them; they would need
//! their own step. macOS creation time needs `setattrlist`, which has no safe wrapper here.
use std::io;
use std::path::Path;
#[cfg(unix)]
use std::os::fd::BorrowedFd;
/// Largest attribute-name list [`copy_xattrs`] will read. Names are short; a file with a
/// megabyte of them is not something a save should spend memory on.
#[cfg(unix)]
const MAX_XATTR_NAMES: usize = 1 << 20;
/// Largest single attribute value [`copy_xattrs`] will carry over. Finder tags and `user.*`
/// attributes are tens of bytes; a resource fork can be large, and past this it is not worth
/// holding a copy of it in memory during a save.
#[cfg(unix)]
const MAX_XATTR_VALUE: usize = 16 << 20;
/// First read size for an attribute list or value; grown on `ERANGE`.
#[cfg(unix)]
const XATTR_CHUNK: usize = 4 << 10;
/// Copy, best effort, everything [`crate::atomic::atomic_write`] should carry from the file it
/// is about to replace (`from`) onto the temporary file that will replace it (`to`).
///
/// Errors are the caller's to ignore: each piece is attempted on its own, and the first failure
/// is returned only so a caller that wants to log one can.
pub fn copy_metadata(from: &Path, to: &Path) -> io::Result<()> {
// The permission bits go on last. Writing an attribute needs the destination open for
// writing, and replacing a read-only (0444) file would copy that mode onto the temporary
// file and then be unable to touch it again.
#[cfg(unix)]
let attributes = copy_xattrs_at(from, to);
#[cfg(not(unix))]
let attributes = Ok(());
#[cfg(target_os = "macos")]
let acl = copy_acl(from, to);
#[cfg(not(target_os = "macos"))]
let acl = Ok(());
// A save over a 0600 file must not widen it to whatever the process default is.
let permissions = std::fs::metadata(from).and_then(|m| std::fs::set_permissions(to, m.permissions()));
attributes.and(acl).and(permissions)
}
/// [`copy_metadata`]'s extended-attribute step, by path: open both files and hand the
/// descriptors to [`copy_xattrs`].
#[cfg(unix)]
fn copy_xattrs_at(from: &Path, to: &Path) -> io::Result<()> {
use std::os::fd::AsFd;
let old = std::fs::File::open(from)?;
// Writing an attribute needs write access to the file, not only to its directory.
let new = std::fs::OpenOptions::new().write(true).open(to)?;
copy_xattrs(old.as_fd(), new.as_fd())
}
/// Copy every extended attribute of `from` onto `to`, best effort, through the two open files
/// rather than their paths.
///
/// Descriptors, not paths, because the automation write path holds capability-checked handles
/// and must never reach back out to an ambient path to finish a write (#7095). The same reason
/// makes this the right shape for [`copy_metadata`] too.
///
/// An attribute that cannot be read or cannot be set is skipped: `com.apple.provenance` and
/// `com.apple.rootless` on macOS and `security.*` on Linux belong to the system and refuse to
/// be written by an ordinary process, and failing a document save over one would be absurd.
/// `Err` means the attribute *list* could not be read, so nothing was copied.
#[cfg(unix)]
pub fn copy_xattrs(from: BorrowedFd<'_>, to: BorrowedFd<'_>) -> io::Result<()> {
use rustix::fs::{XattrFlags, fsetxattr};
for name in list_xattrs(from)?.split(|b| *b == 0) {
if name.is_empty() || skip_xattr(name) {
continue;
}
let Some(value) = read_xattr(from, name) else { continue };
let _ = fsetxattr(to, name, &value, XattrFlags::empty());
}
Ok(())
}
/// Attributes that describe how the *old* file's bytes are stored rather than anything about
/// the document, and so must never be pinned onto a file holding different bytes.
#[cfg(unix)]
fn skip_xattr(name: &[u8]) -> bool {
// `com.apple.decmpfs` marks a file whose data lives compressed inside the attribute itself.
// The kernel hides it from a plain `listxattr` and refuses to set it, but a file claiming
// compressed storage it does not have would read as garbage, so never try.
name == b"com.apple.decmpfs"
}
/// The NUL-separated attribute names of `fd`.
#[cfg(unix)]
fn list_xattrs(fd: BorrowedFd<'_>) -> io::Result<Vec<u8>> {
let mut buf = vec![0u8; XATTR_CHUNK];
loop {
match rustix::fs::flistxattr(fd, buf.as_mut_slice()) {
Ok(len) => {
buf.truncate(len.min(buf.len()));
return Ok(buf);
}
Err(e) if e == rustix::io::Errno::RANGE && buf.len() < MAX_XATTR_NAMES => {
buf.resize(buf.len().saturating_mul(4).min(MAX_XATTR_NAMES), 0);
}
Err(e) => return Err(e.into()),
}
}
}
/// The value of one attribute, or `None` if it cannot be read or is larger than
/// [`MAX_XATTR_VALUE`]. A missing value is normal: another process may remove an attribute
/// between the listing and the read.
#[cfg(unix)]
fn read_xattr(fd: BorrowedFd<'_>, name: &[u8]) -> Option<Vec<u8>> {
let mut buf = vec![0u8; XATTR_CHUNK];
loop {
match rustix::fs::fgetxattr(fd, name, buf.as_mut_slice()) {
Ok(len) => {
buf.truncate(len.min(buf.len()));
return Some(buf);
}
Err(e) if e == rustix::io::Errno::RANGE && buf.len() < MAX_XATTR_VALUE => {
buf.resize(buf.len().saturating_mul(4).min(MAX_XATTR_VALUE), 0);
}
Err(_) => return None,
}
}
}
/// Copy an explicit macOS access-control list (`chmod +a`) from `from` onto `to` (#7073).
///
/// `fcopyfile(COPYFILE_ACL)` is the obvious call and is an `unsafe fn`, which this workspace
/// forbids; `fclonefileat` with `CLONE_ACL` is safe but only works on APFS and would mean
/// writing every save as a clone-then-truncate. `exacl` is a small, safe wrapper over
/// `acl_get_file`/`acl_set_file` that works on every file system that has ACLs at all.
///
/// An old file with no ACL leaves `to` alone: the new file may have picked up the folder's
/// inherited entries, and taking access away is a worse surprise than leaving it as the folder
/// says it should be.
#[cfg(target_os = "macos")]
fn copy_acl(from: &Path, to: &Path) -> io::Result<()> {
let entries = exacl::getfacl(from, None)?;
if entries.is_empty() {
return Ok(());
}
exacl::setfacl(&[to], &entries, None)
}
/// Replace the **existing** file `to` with `from`, keeping what the destination owns rather than
/// its bytes.
///
/// Everywhere but Windows this is exactly [`std::fs::rename`], and the metadata is carried by
/// [`copy_metadata`] onto `from` beforehand. On Windows it is `ReplaceFileW`, which preserves
/// the replaced file's DACL (#7096), its named streams — `Zone.Identifier`, the Mark of the Web
/// (#7094) — its creation time, object identifier, compression and encryption, in the one call
/// Microsoft documents for the save-through-a-temporary-file pattern. None of those have a safe
/// path-based API to copy by hand.
pub fn replace_existing(from: &Path, to: &Path) -> io::Result<()> {
#[cfg(windows)]
{
windows_replace(from, to)
}
#[cfg(not(windows))]
{
std::fs::rename(from, to)
}
}
/// `ReplaceFileW`, with the plain rename as the fallback. See [`replace_existing`].
///
/// **A backup name is not optional.** `ReplaceFile` without one deletes the replaced file before
/// the final rename, and documents `ERROR_UNABLE_TO_MOVE_REPLACEMENT`: "the replaced file no
/// longer exists and the replacement file exists under its original name" — the user's document
/// gone, its replacement left under a hidden temporary name. With a backup name the same failure
/// leaves both files where they were. So this always passes one, and deletes it on the way out.
///
/// The failures and what each leaves behind (from the `ReplaceFileW` reference):
///
/// - `ERROR_UNABLE_TO_MOVE_REPLACEMENT_2` (1177) is the only one that moves anything: the
/// replacement keeps its name but has already inherited the destination's streams and
/// attributes, and the destination's old content is at the backup name. Finishing the rename
/// by hand completes the save *with* its metadata; if even that fails, the backup goes back to
/// the destination so the user's file is where they left it.
/// - Every other error leaves the replaced and replacement files under their own names, so a
/// plain rename still saves the document — without the metadata, which is where this started.
#[cfg(windows)]
fn windows_replace(from: &Path, to: &Path) -> io::Result<()> {
use winsafe::co::REPLACEFILE;
/// `ERROR_UNABLE_TO_MOVE_REPLACEMENT_2`: the destination now lives under the backup name.
const MOVE_REPLACEMENT_2: i32 = 1177;
let backup = backup_path(to);
let paths = (to.to_str(), from.to_str(), backup.as_deref().and_then(Path::to_str));
// `ReplaceFileW` takes `&str`; a path that is not valid Unicode, or one past MAX_PATH, is
// the plain rename's job.
let (Some(replaced), Some(replacement), Some(backup_str)) = paths else {
return std::fs::rename(from, to);
};
let flags = REPLACEFILE::IGNORE_MERGE_ERRORS | REPLACEFILE::IGNORE_ACL_ERRORS;
match winsafe::ReplaceFile(replaced, replacement, Some(backup_str), flags) {
Ok(()) => {
remove_backup(backup.as_deref());
Ok(())
}
Err(e) if e.raw() as i32 == MOVE_REPLACEMENT_2 => match std::fs::rename(from, to) {
Ok(()) => {
remove_backup(backup.as_deref());
Ok(())
}
Err(rename_failed) => {
if let Some(backup) = backup.as_deref() {
let _ = std::fs::rename(backup, to);
}
Err(rename_failed)
}
},
Err(_) => {
remove_backup(backup.as_deref());
std::fs::rename(from, to)
}
}
}
/// A unique name beside `to` for `ReplaceFile` to park the replaced file under. It shares the
/// temporary-file suffix, so the save's own cleanup and the tests' leftover check cover it.
#[cfg(windows)]
fn backup_path(to: &Path) -> Option<std::path::PathBuf> {
let name = to.file_name()?.to_string_lossy().into_owned();
let dir = match to.parent() {
Some(d) if !d.as_os_str().is_empty() => d,
_ => Path::new("."),
};
Some(dir.join(super::temp_name(&name)))
}
#[cfg(windows)]
fn remove_backup(backup: Option<&Path>) {
if let Some(backup) = backup {
let _ = std::fs::remove_file(backup);
}
}
#[cfg(test)]
mod tests;
+309
View File
@@ -0,0 +1,309 @@
//! What a save keeps from the file it replaces.
//!
//! The Unix tests run for real. The Windows ones exercise `ReplaceFileW` through
//! [`crate::atomic::atomic_write`] and can only run on Windows, so they are `#[cfg(windows)]`
//! and are covered by the Windows CI job, not by a developer on a Mac.
use crate::atomic::atomic_write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
static N: AtomicU64 = AtomicU64::new(0);
let d = std::env::temp_dir().join(format!("pc-meta-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
Self(d)
}
fn join(&self, name: &str) -> PathBuf {
self.0.join(name)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// No temporary or backup file is left beside the saved document.
fn assert_no_temp(dir: &Path) {
let leftovers: Vec<_> =
std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".tmp")).collect();
assert!(leftovers.is_empty(), "temporary files left behind: {leftovers:?}");
}
// ---------------------------------------------------------------- extended attributes (Unix)
#[cfg(unix)]
mod xattrs {
use super::*;
/// macOS wants a reverse-DNS name; Linux only lets an unprivileged process write `user.*`.
#[cfg(target_os = "macos")]
const TAG: &str = "com.apple.metadata:_kMDItemUserTags";
#[cfg(not(target_os = "macos"))]
const TAG: &str = "user.photocraft.test";
fn set(path: &Path, name: &str, value: &[u8]) -> bool {
rustix::fs::setxattr(path, name, value, rustix::fs::XattrFlags::empty()).is_ok()
}
fn get(path: &Path, name: &str) -> Option<Vec<u8>> {
let mut buf = vec![0u8; 1 << 20];
let len = rustix::fs::getxattr(path, name, buf.as_mut_slice()).ok()?;
buf.truncate(len);
Some(buf)
}
/// #6603: the attributes of the replaced file — a Finder tag, a `user.*` attribute — are on
/// the file the user is left with.
#[test]
fn replacing_a_file_keeps_its_extended_attributes() {
let d = TempDir::new("xattr");
let p = d.join("doc.psd");
atomic_write(&p, b"first").unwrap();
if !set(&p, TAG, b"tagged") {
// tmpfs and some CI file systems have no xattr support; nothing to assert.
return;
}
atomic_write(&p, b"second, longer").unwrap();
assert_eq!(std::fs::read(&p).unwrap(), b"second, longer");
assert_eq!(get(&p, TAG).as_deref(), Some(&b"tagged"[..]), "the replaced file's attribute was dropped");
assert_no_temp(&d.0);
}
/// A large value still comes across (and is not silently truncated).
#[test]
fn a_large_attribute_value_survives() {
let d = TempDir::new("xattr-big");
let p = d.join("doc.psd");
atomic_write(&p, b"first").unwrap();
// Comfortably past the first read buffer, so the grow-on-ERANGE path runs.
let value = vec![0xABu8; 64 << 10];
if !set(&p, TAG, &value) {
return;
}
atomic_write(&p, b"second").unwrap();
assert_eq!(get(&p, TAG), Some(value));
}
/// A read-only file is refused outright (#6600), so a save never reaches the metadata copy and
/// the file keeps everything it had. The writable cases above cover the copy itself.
#[test]
fn a_read_only_file_keeps_its_attributes_and_its_mode() {
use std::os::unix::fs::PermissionsExt;
let d = TempDir::new("xattr-ro");
let p = d.join("doc.psd");
atomic_write(&p, b"first").unwrap();
if !set(&p, TAG, b"tagged") {
return;
}
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o444)).unwrap();
// #6600: a read-only file is refused before anything is written, so the question this test
// asks — does a replace keep the attributes and the mode — is answered by the save not
// happening. The writable case above covers attributes surviving a replace.
let e = atomic_write(&p, b"second, longer").expect_err("a read-only file is refused");
assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied);
assert_eq!(std::fs::read(&p).unwrap(), b"first", "the original was left alone");
assert_eq!(get(&p, TAG).as_deref(), Some(&b"tagged"[..]), "a read-only file lost its attribute");
assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o444);
}
/// Creating a file that was not there sets no attributes and does not fail.
#[test]
fn creating_a_new_file_needs_no_source() {
let d = TempDir::new("xattr-new");
let p = d.join("fresh.psd");
atomic_write(&p, b"bytes").unwrap();
assert_eq!(std::fs::read(&p).unwrap(), b"bytes");
assert!(get(&p, TAG).is_none());
}
/// The descriptor-based copy is what the automation write path uses (#7095): it works on two
/// open files and never looks at a path.
#[test]
fn copy_xattrs_works_on_descriptors() {
use std::os::fd::AsFd;
let d = TempDir::new("xattr-fd");
let (from, to) = (d.join("from"), d.join("to"));
std::fs::write(&from, b"a").unwrap();
std::fs::write(&to, b"b").unwrap();
if !set(&from, TAG, b"carried") {
return;
}
let old = std::fs::File::open(&from).unwrap();
let new = std::fs::OpenOptions::new().write(true).open(&to).unwrap();
super::super::copy_xattrs(old.as_fd(), new.as_fd()).unwrap();
assert_eq!(get(&to, TAG).as_deref(), Some(&b"carried"[..]));
assert_eq!(std::fs::read(&to).unwrap(), b"b", "copying attributes must not touch the bytes");
}
}
// --------------------------------------------------------------------------- mode (Unix)
/// The mode was already kept before any of this; it still is.
#[cfg(unix)]
#[test]
fn replacing_a_file_keeps_its_mode() {
use std::os::unix::fs::PermissionsExt;
let d = TempDir::new("mode");
let p = d.join("doc.psd");
atomic_write(&p, b"first").unwrap();
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600)).unwrap();
atomic_write(&p, b"second").unwrap();
assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600);
}
// ----------------------------------------------------------------------------- ACL (macOS)
#[cfg(target_os = "macos")]
mod acl {
use super::*;
/// #7073: an ACL entry added with `chmod +a` is still there after a save.
#[test]
fn replacing_a_file_keeps_its_acl() {
let d = TempDir::new("acl");
let p = d.join("doc.psd");
atomic_write(&p, b"first").unwrap();
// The same thing `chmod +a` does: one explicit entry for the user running the test, so
// no second account has to exist.
let Ok(user) = std::env::var("USER") else { return };
let entries = [exacl::AclEntry::allow_user(&user, exacl::Perm::READ | exacl::Perm::WRITE, None)];
if exacl::setfacl(&[&p], &entries, None).is_err() {
// A file system without ACL support (a RAM disk, some CI volumes).
return;
}
let before = exacl::getfacl(&p, None).unwrap();
assert!(!before.is_empty(), "the test could not set an ACL to begin with");
atomic_write(&p, b"second, longer").unwrap();
assert_eq!(std::fs::read(&p).unwrap(), b"second, longer");
assert_eq!(exacl::getfacl(&p, None).unwrap(), before, "the replaced file's ACL was dropped");
assert_no_temp(&d.0);
}
/// A file with no ACL keeps having no ACL, rather than gaining an empty one.
#[test]
fn a_file_without_an_acl_is_left_alone() {
let d = TempDir::new("acl-none");
let p = d.join("doc.psd");
atomic_write(&p, b"first").unwrap();
let before = exacl::getfacl(&p, None).unwrap();
atomic_write(&p, b"second").unwrap();
assert_eq!(exacl::getfacl(&p, None).unwrap(), before);
}
}
// --------------------------------------------------------------- named streams and ACL (Windows)
/// Unverified on a Mac: these run only on Windows (CI's Windows job).
#[cfg(windows)]
mod windows {
use super::*;
/// Open a named stream of `path`, e.g. `Zone.Identifier`.
fn stream(path: &Path, name: &str) -> PathBuf {
let mut s = path.as_os_str().to_os_string();
s.push(":");
s.push(name);
PathBuf::from(s)
}
/// #7094: a file marked as downloaded from the internet is still marked after a save, so the
/// shell and other applications keep warning about it.
#[test]
fn replacing_a_file_keeps_its_mark_of_the_web() {
let d = TempDir::new("motw");
let p = d.join("doc.psd");
atomic_write(&p, b"first").unwrap();
let motw = b"[ZoneTransfer]\r\nZoneId=3\r\n";
std::fs::write(stream(&p, "Zone.Identifier"), motw).unwrap();
atomic_write(&p, b"second, longer").unwrap();
assert_eq!(std::fs::read(&p).unwrap(), b"second, longer");
assert_eq!(std::fs::read(stream(&p, "Zone.Identifier")).unwrap(), motw, "the Mark of the Web was dropped");
assert_no_temp(&d.0);
}
/// Any other named stream rides along too, because `ReplaceFileW` keeps the lot.
#[test]
fn replacing_a_file_keeps_other_named_streams() {
let d = TempDir::new("ads");
let p = d.join("doc.psd");
atomic_write(&p, b"first").unwrap();
std::fs::write(stream(&p, "photocraft.test"), b"side data").unwrap();
atomic_write(&p, b"second").unwrap();
assert_eq!(std::fs::read(stream(&p, "photocraft.test")).unwrap(), b"side data");
}
/// #7096: an explicit ACL entry survives, instead of the file falling back to whatever the
/// folder hands down. Compared as the string `icacls` prints, which is what a user checks.
#[test]
fn replacing_a_file_keeps_its_explicit_acl() {
let d = TempDir::new("dacl");
let p = d.join("doc.psd");
atomic_write(&p, b"first").unwrap();
// Grant the current user an entry that inheritance would not have produced.
let user = std::env::var("USERNAME").unwrap_or_default();
if user.is_empty() {
return;
}
let granted = std::process::Command::new("icacls").arg(&p).arg("/grant").arg(format!("{user}:(RX)")).output();
if !granted.map(|o| o.status.success()).unwrap_or(false) {
return;
}
let before = std::process::Command::new("icacls").arg(&p).output().unwrap().stdout;
atomic_write(&p, b"second, longer").unwrap();
let after = std::process::Command::new("icacls").arg(&p).output().unwrap().stdout;
assert_eq!(String::from_utf8_lossy(&after), String::from_utf8_lossy(&before), "the explicit ACL was dropped");
assert_no_temp(&d.0);
}
/// `ReplaceFileW` also keeps the creation time, which the rename used to reset (#6603).
#[test]
fn replacing_a_file_keeps_its_creation_time() {
let d = TempDir::new("born");
let p = d.join("doc.psd");
atomic_write(&p, b"first").unwrap();
let before = std::fs::metadata(&p).unwrap().created().unwrap();
std::thread::sleep(std::time::Duration::from_millis(50));
atomic_write(&p, b"second").unwrap();
assert_eq!(std::fs::metadata(&p).unwrap().created().unwrap(), before);
}
/// Creating a file where there was none still works: there is nothing to replace, so the
/// write never reaches `ReplaceFileW`.
#[test]
fn creating_a_new_file_still_works() {
let d = TempDir::new("new");
let p = d.join("fresh.psd");
atomic_write(&p, b"bytes").unwrap();
assert_eq!(std::fs::read(&p).unwrap(), b"bytes");
assert_no_temp(&d.0);
}
}
+4 -4
View File
@@ -69,8 +69,8 @@ impl AtomicFs for Faulty {
fn sync_dir(&self, dir: &Path) -> io::Result<()> {
RealFs.sync_dir(dir)
}
fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()> {
RealFs.copy_permissions(from, to)
fn copy_metadata(&self, from: &Path, to: &Path) -> io::Result<()> {
RealFs.copy_metadata(from, to)
}
}
@@ -201,8 +201,8 @@ impl AtomicFs for ReadOnlyTarget {
fn sync_dir(&self, dir: &Path) -> io::Result<()> {
RealFs.sync_dir(dir)
}
fn copy_permissions(&self, from: &Path, to: &Path) -> io::Result<()> {
RealFs.copy_permissions(from, to)
fn copy_metadata(&self, from: &Path, to: &Path) -> io::Result<()> {
RealFs.copy_metadata(from, to)
}
}
+4
View File
@@ -163,6 +163,10 @@ pub(crate) fn read_manifest(src: &dyn ByteSource, opts: &LoadOptions) -> Result<
let layers = take_array(&mut v, "/document/layers");
let mut m: Manifest = serde_json::from_value(v)?;
m.document.layers = layers_from_json(layers)?;
// A number past f32's range decodes as infinity, which no save could write back (#6862).
if let Err(crate::finite::Problem::NonFinite { path }) = crate::finite::check(&m) {
return Err(FormatError::corrupt(format!("`{path}` is out of range")));
}
Ok(m)
}
+18
View File
@@ -94,6 +94,24 @@ fn bad_manifest_json() {
assert!(matches!(load_from_bytes(&b), Err(FormatError::Json(_))));
}
/// A number past f32's range would load as infinity, and every later save would then fail
/// (#6862): it is refused when the file is opened, naming the value.
#[test]
fn out_of_range_number_refused_on_open() {
let b = rebuild(&sample(), |n, d| {
Some(if n == "manifest.json" {
let mut v: serde_json::Value = serde_json::from_slice(&d).unwrap();
v["document"]["layers"][0]["opacity"] = serde_json::json!(1e39);
serde_json::to_vec(&v).unwrap()
} else {
d
})
});
let Err(e) = load_from_bytes(&b) else { panic!("a manifest with opacity 1e39 opened") };
assert!(matches!(e, FormatError::Corrupt(_)), "{e}");
assert!(e.to_string().contains("document.layers[0].opacity"), "{e}");
}
/// Hostile nesting fails with an error instead of overflowing the stack; nesting as deep as the
/// deepest groups a bundle may hold (three JSON levels each) parses, and is then rejected for
/// lacking a format version.
+27
View File
@@ -0,0 +1,27 @@
//! `.pcraft` is lossless for f64: every coordinate reloads bit-for-bit.
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Document, Layer, LayerContent, Size};
#[test]
fn f64_coordinates_reload_bit_exact() {
let x = 11.183221215612905_f64;
let y = 0.1 + 0.2;
let mut doc = Document::new("Floats", Size::new(2, 2), ColorMode::Rgb, SampleType::U8);
doc.layers.push(Layer::new(
"Shape",
LayerContent::Shape(photocraft_doc::ShapeLayer {
path: photocraft_doc::Path::new(vec![photocraft_doc::Subpath::polygon(&[(x, y), (40.0, 10.0), (25.0, 40.0)])]),
..Default::default()
}),
));
doc.guides.horizontal.push(x);
doc.guides.vertical.push(y);
doc.ruler_origin = [x, y];
let bytes = photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap();
let back = photocraft_format::load_from_bytes(&bytes).unwrap();
assert_eq!(back.guides.horizontal[0].to_bits(), x.to_bits());
assert_eq!(back.guides.vertical[0].to_bits(), y.to_bits());
assert_eq!(back.ruler_origin.map(f64::to_bits), [x, y].map(f64::to_bits));
assert_eq!(back, doc);
}
Loaded 100 of 201 files, more files were not shown because too many files have changed in this diff. Show more