mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge main into feat/history-snapshot-options
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> # Conflicts: # crates/ui-egui/src/i18n/cs.tsv # crates/ui-egui/src/i18n/de.tsv # crates/ui-egui/src/i18n/es.tsv # crates/ui-egui/src/i18n/ko.tsv # crates/ui-egui/src/i18n/vi.tsv # crates/ui-egui/src/i18n/zh-hans.tsv # crates/ui-egui/src/i18n/zh-hant.tsv
This commit is contained in:
commit
d4e2ce674a
60 files changed
+4912
-139
No files matched your search
@@ -26,8 +26,9 @@ USAGE:
|
||||
photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>]
|
||||
Open a file, run engine commands in order, save the result. Each --params
|
||||
applies to the preceding --cmd. Prints each command's JSON result.
|
||||
photocraft-cli batch --actions <actions.json> [--action <name>] --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>]
|
||||
Apply an action list to every image in a directory. Steps are [id, params] pairs,
|
||||
photocraft-cli batch --actions <actions.json|set.atn> [--action <name>] --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>]
|
||||
Apply an action list to every image in a directory. A Photoshop Actions file (.atn) is a
|
||||
set: its action --action names plays, as below. JSON steps are [id, params] pairs,
|
||||
{\"command\": id, \"params\": {…}} objects or bare ids, as a recorded action or droplet stores them
|
||||
(a list, or wrapped in {\"actions\": …}, {\"steps\": …} or a droplet). An Actions set (the Actions
|
||||
panel's actions.json, {\"actions\": [{\"name\", \"steps\"}…]}) plays the action --action names (needed
|
||||
@@ -392,6 +393,38 @@ pub fn load_actions(text: &str, name: Option<&str>) -> Result<(Steps, Vec<Action
|
||||
Ok((play, set))
|
||||
}
|
||||
|
||||
/// [`load_actions`] for a file on disk: a Photoshop Actions file (`.atn`, by extension or by
|
||||
/// its version word) is converted first; the played action's steps with no PhotoCraft
|
||||
/// equivalent come back as warnings (they fail at playback, as in Photoshop when a step can't run).
|
||||
pub fn load_actions_file(path: &str, name: Option<&str>) -> Result<(Steps, Vec<Action>, Vec<String>), String> {
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let is_atn = Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("atn")) || bytes.starts_with(&[0, 0, 0, 16]);
|
||||
if !is_atn {
|
||||
let text = String::from_utf8(bytes).map_err(|e| format!("{path}: {e}"))?;
|
||||
let (steps, set) = load_actions(&text, name)?;
|
||||
return Ok((steps, set, Vec::new()));
|
||||
}
|
||||
let imp = photocraft_engine::atn_cmds::import(&bytes).map_err(|e| format!("{path}: {e}"))?;
|
||||
let names = || imp.actions.iter().map(|a| format!("`{}`", a.name)).collect::<Vec<_>>().join(", ");
|
||||
let action = match (name, imp.actions.as_slice()) {
|
||||
(Some(n), _) => {
|
||||
imp.actions.iter().find(|a| a.name == n).ok_or_else(|| format!("no action named `{n}` in the set `{}` (it holds {})", imp.set, names()))?
|
||||
}
|
||||
(None, [only]) => only,
|
||||
(None, []) => return Err(format!("{path}: the set holds no actions")),
|
||||
(None, _) => return Err(format!("the set `{}` holds {} actions: pick one with --action <name> ({})", imp.set, imp.actions.len(), names())),
|
||||
};
|
||||
let warnings = imp
|
||||
.unsupported
|
||||
.iter()
|
||||
.filter(|u| u.action == action.name)
|
||||
.map(|u| format!("`{}` step {}: Photoshop's \"{}\" ({}) has no PhotoCraft equivalent yet", u.action, u.step + 1, u.name, u.event))
|
||||
.chain(imp.warnings.iter().cloned())
|
||||
.collect();
|
||||
let play = vec![("actions.play".to_string(), json!({"action": action.name}))];
|
||||
Ok((play, imp.actions, warnings))
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` name the same existing folder, however they are spelt (relative, with a
|
||||
/// trailing separator, through a symbolic link).
|
||||
fn same_dir(a: &Path, b: &Path) -> bool {
|
||||
@@ -410,8 +443,10 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
let actions_path = a.get("--actions").ok_or("batch needs --actions <file>")?;
|
||||
let in_dir = PathBuf::from(a.get("--in").ok_or("batch needs --in <dir>")?);
|
||||
let out_dir = PathBuf::from(a.get("--out").ok_or("batch needs --out <dir>")?);
|
||||
let text = std::fs::read_to_string(actions_path).map_err(|e| format!("{actions_path}: {e}"))?;
|
||||
let (actions, set) = load_actions(&text, a.get("--action"))?;
|
||||
let (actions, set, warnings) = load_actions_file(actions_path, a.get("--action"))?;
|
||||
for w in &warnings {
|
||||
let _ = writeln!(err, "warning: {w}");
|
||||
}
|
||||
let opts = export_opts(a)?;
|
||||
// Results are saved as `<out>/<stem>.<ext>`, so an `--out` that is the `--in` folder would
|
||||
// replace the originals (#492).
|
||||
|
||||
@@ -684,3 +684,33 @@ fn a_non_unicode_argument_is_a_usage_error_not_a_panic() {
|
||||
assert!(!err.contains("panicked"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `batch --actions set.atn`: a Photoshop Actions file plays like an Actions set, and its steps
|
||||
/// PhotoCraft can't play are warned about up front.
|
||||
#[test]
|
||||
fn batch_plays_a_photoshop_actions_file() {
|
||||
use photocraft_engine::actions_cmds::Action;
|
||||
let d = tmp("atn");
|
||||
let input = d.join("in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
write_png(&input.join("a.png"), 8, 4, 3);
|
||||
let invert = Action::new("Negative", vec![("image.adjustments.invert".into(), json!({})), ("select.all".into(), json!({}))]);
|
||||
let odd = Action::new("Odd", vec![(photocraft_engine::atn_cmds::PHOTOSHOP_STEP.into(), json!({"event": "syntheticFill", "name": "Generative Fill"}))]);
|
||||
let (bytes, skipped) = photocraft_engine::atn_cmds::export("Set", &[&invert, &odd], &[], false).unwrap();
|
||||
assert!(skipped.is_empty());
|
||||
let atn = d.join("Set.atn");
|
||||
std::fs::write(&atn, bytes).unwrap();
|
||||
let out_dir = d.join("out");
|
||||
// Two actions: the set needs --action.
|
||||
let o = bin().args(["batch", "--actions"]).arg(&atn).arg("--in").arg(&input).arg("--out").arg(&out_dir).output().unwrap();
|
||||
assert!(!o.status.success());
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains("--action"), "{}", String::from_utf8_lossy(&o.stderr));
|
||||
let (_, err) = ok(bin().args(["batch", "--actions"]).arg(&atn).args(["--action", "Negative", "--in"]).arg(&input).arg("--out").arg(&out_dir));
|
||||
assert!(out_dir.join("a.png").exists());
|
||||
assert!(!err.contains("warning"), "{err}");
|
||||
// The unsupported step is warned about, and fails the file as Photoshop would stop on it.
|
||||
let o = bin().args(["batch", "--actions"]).arg(&atn).args(["--action", "Odd", "--in"]).arg(&input).arg("--out").arg(d.join("out2")).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(err.contains("Generative Fill"), "{err}");
|
||||
assert!(!o.status.success());
|
||||
}
|
||||
+167
-29
@@ -766,47 +766,84 @@ pub fn feather(m: &[f32], w: usize, h: usize, radius: f32) -> Vec<f32> {
|
||||
}
|
||||
|
||||
/// Anti-aliased polygon (even-odd) coverage over `area`: exact horizontal
|
||||
/// coverage, 4 sub-rows per pixel row (or 1 when not anti-aliased).
|
||||
/// coverage, 4 sub-rows per pixel row (or 1 when not anti-aliased). Bands of
|
||||
/// rows are filled in parallel, and each sub-row tests only the edges that
|
||||
/// cross it (an active edge list over the edges sorted by their top).
|
||||
pub fn polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec<f32> {
|
||||
let (w, h) = (area.width() as usize, area.height() as usize);
|
||||
let mut m = vec![0.0f32; w * h];
|
||||
if points.len() < 3 {
|
||||
if points.len() < 3 || w == 0 {
|
||||
return m;
|
||||
}
|
||||
let sub = if anti_alias { 4 } else { 1 };
|
||||
let mut xs: Vec<f32> = Vec::new();
|
||||
for py in 0..h {
|
||||
for s in 0..sub {
|
||||
let y = area.y0 as f32 + py as f32 + (s as f32 + 0.5) / sub as f32;
|
||||
xs.clear();
|
||||
for i in 0..points.len() {
|
||||
let (a, b) = (points[i], points[(i + 1) % points.len()]);
|
||||
if (a.1 <= y && b.1 > y) || (b.1 <= y && a.1 > y) {
|
||||
xs.push(a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0));
|
||||
}
|
||||
let sample_y = |py: usize, s: usize| area.y0 as f32 + py as f32 + (s as f32 + 0.5) / sub as f32;
|
||||
// A sub-row at y crosses the edge a→b iff top <= y < bottom; horizontal and NaN edges
|
||||
// never cross one.
|
||||
struct Edge {
|
||||
top: f32,
|
||||
bottom: f32,
|
||||
a: (f32, f32),
|
||||
b: (f32, f32),
|
||||
}
|
||||
let mut edges: Vec<Edge> = points
|
||||
.iter()
|
||||
.zip(points.iter().cycle().skip(1))
|
||||
.filter_map(|(&a, &b)| {
|
||||
if a.1 < b.1 {
|
||||
Some(Edge { top: a.1, bottom: b.1, a, b })
|
||||
} else if b.1 < a.1 {
|
||||
Some(Edge { top: b.1, bottom: a.1, a, b })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
xs.sort_by(|a, b| a.total_cmp(b));
|
||||
for span in xs.as_chunks::<2>().0 {
|
||||
let (x0, x1) = ((span[0] - area.x0 as f32).max(0.0), (span[1] - area.x0 as f32).min(w as f32));
|
||||
if x1 <= x0 {
|
||||
})
|
||||
.collect();
|
||||
edges.sort_by(|p, q| p.top.total_cmp(&q.top));
|
||||
const BAND: usize = 64;
|
||||
par_rows(&mut m, w, BAND, |bi, rows| {
|
||||
let py0 = bi * BAND;
|
||||
let (first, last) = (sample_y(py0, 0), sample_y(py0 + rows.len() / w - 1, sub - 1));
|
||||
let reach = edges.partition_point(|e| e.top <= last);
|
||||
let band_edges = edges.get(..reach).unwrap_or_default();
|
||||
let mut pending = band_edges.iter().filter(|e| e.bottom > first).peekable();
|
||||
let mut active: Vec<&Edge> = Vec::new();
|
||||
let mut xs: Vec<f32> = Vec::new();
|
||||
for (r, row) in rows.chunks_exact_mut(w).enumerate() {
|
||||
for s in 0..sub {
|
||||
// Sub-row ys never decrease, so an edge whose bottom is passed stays out.
|
||||
let y = sample_y(py0 + r, s);
|
||||
while let Some(e) = pending.next_if(|e| e.top <= y) {
|
||||
active.push(e);
|
||||
}
|
||||
active.retain(|e| e.bottom > y);
|
||||
if active.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (c0, c1) = (x0.floor() as usize, (x1.ceil() as usize).min(w));
|
||||
for cx in c0..c1 {
|
||||
let cov = if anti_alias {
|
||||
((cx + 1) as f32).min(x1) - (cx as f32).max(x0)
|
||||
} else {
|
||||
let c = cx as f32 + 0.5;
|
||||
if c >= x0 && c < x1 { 1.0 } else { 0.0 }
|
||||
};
|
||||
m[py * w + cx] += cov.max(0.0) / sub as f32;
|
||||
xs.clear();
|
||||
xs.extend(active.iter().map(|&&Edge { a, b, .. }| a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0)));
|
||||
xs.sort_by(|a, b| a.total_cmp(b));
|
||||
for span in xs.as_chunks::<2>().0 {
|
||||
let (x0, x1) = ((span[0] - area.x0 as f32).max(0.0), (span[1] - area.x0 as f32).min(w as f32));
|
||||
if x1 <= x0 {
|
||||
continue;
|
||||
}
|
||||
let (c0, c1) = (x0.floor() as usize, (x1.ceil() as usize).min(w));
|
||||
for (cx, v) in row.iter_mut().enumerate().take(c1).skip(c0) {
|
||||
let cov = if anti_alias {
|
||||
((cx + 1) as f32).min(x1) - (cx as f32).max(x0)
|
||||
} else {
|
||||
let c = cx as f32 + 0.5;
|
||||
if c >= x0 && c < x1 { 1.0 } else { 0.0 }
|
||||
};
|
||||
*v += cov.max(0.0) / sub as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for v in &mut m {
|
||||
*v = v.min(1.0);
|
||||
}
|
||||
for v in rows {
|
||||
*v = v.min(1.0);
|
||||
}
|
||||
});
|
||||
m
|
||||
}
|
||||
|
||||
@@ -1161,6 +1198,107 @@ mod tests {
|
||||
assert!(polygon(&[(0.0, 0.0), (1.0, 1.0)], a, true).iter().all(|v| *v == 0.0));
|
||||
}
|
||||
|
||||
/// The previous polygon fill (every edge tested on every sub-row), kept as the oracle.
|
||||
fn old_polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec<f32> {
|
||||
let (w, h) = (area.width() as usize, area.height() as usize);
|
||||
let mut m = vec![0.0f32; w * h];
|
||||
if points.len() < 3 {
|
||||
return m;
|
||||
}
|
||||
let sub = if anti_alias { 4 } else { 1 };
|
||||
let mut xs: Vec<f32> = Vec::new();
|
||||
for py in 0..h {
|
||||
for s in 0..sub {
|
||||
let y = area.y0 as f32 + py as f32 + (s as f32 + 0.5) / sub as f32;
|
||||
xs.clear();
|
||||
for i in 0..points.len() {
|
||||
let (a, b) = (points[i], points[(i + 1) % points.len()]);
|
||||
if (a.1 <= y && b.1 > y) || (b.1 <= y && a.1 > y) {
|
||||
xs.push(a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0));
|
||||
}
|
||||
}
|
||||
xs.sort_by(|a, b| a.total_cmp(b));
|
||||
for span in xs.as_chunks::<2>().0 {
|
||||
let (x0, x1) = ((span[0] - area.x0 as f32).max(0.0), (span[1] - area.x0 as f32).min(w as f32));
|
||||
if x1 <= x0 {
|
||||
continue;
|
||||
}
|
||||
let (c0, c1) = (x0.floor() as usize, (x1.ceil() as usize).min(w));
|
||||
for cx in c0..c1 {
|
||||
let cov = if anti_alias {
|
||||
((cx + 1) as f32).min(x1) - (cx as f32).max(x0)
|
||||
} else {
|
||||
let c = cx as f32 + 0.5;
|
||||
if c >= x0 && c < x1 { 1.0 } else { 0.0 }
|
||||
};
|
||||
m[py * w + cx] += cov.max(0.0) / sub as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for v in &mut m {
|
||||
*v = v.min(1.0);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polygon_matches_the_every_edge_fill_bit_for_bit() {
|
||||
let mut seed = 0x2545_f491_u32;
|
||||
let mut rnd = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
seed as f32 / u32::MAX as f32
|
||||
};
|
||||
// Taller than one 64-row band, offset, and a 1-pixel-wide area.
|
||||
let areas = [Rect::new(0, 0, 90, 150), Rect::new(-13, 7, 60, 211), Rect::new(5, -40, 6, 30)];
|
||||
let mut cases: Vec<Vec<(f32, f32)>> = vec![
|
||||
// Self-intersecting star, horizontal edges, repeated points, collinear runs.
|
||||
(0..11)
|
||||
.map(|i| {
|
||||
let t = i as f32 * 4.0 * std::f32::consts::PI / 11.0;
|
||||
(40.0 + 35.0 * t.cos(), 80.0 + 70.0 * t.sin())
|
||||
})
|
||||
.collect(),
|
||||
vec![(10.0, 10.0), (50.0, 10.0), (50.0, 10.0), (50.0, 60.0), (30.0, 60.0), (30.0, 30.0), (10.0, 30.0)],
|
||||
vec![(0.0, 0.0), (20.0, 0.0), (40.0, 0.0), (40.0, 0.0), (0.0, 0.0)],
|
||||
// Vertices on the sub-row centres and the pixel edges.
|
||||
vec![(3.125, 2.375), (70.5, 2.375), (70.875, 140.625), (3.0, 140.0), (35.0, 64.0), (35.0, 64.125)],
|
||||
// Entirely outside, and straddling every side.
|
||||
vec![(-500.0, -500.0), (-400.0, -500.0), (-450.0, -300.0)],
|
||||
vec![(-80.0, -60.0), (300.0, 20.0), (60.0, 400.0)],
|
||||
// Non-finite coordinates and a negative zero.
|
||||
vec![(10.0, 10.0), (f32::NAN, 40.0), (60.0, 70.0), (20.0, f32::INFINITY), (-0.0, -0.0), (0.0, 0.0)],
|
||||
];
|
||||
for n in [3, 7, 40, 400] {
|
||||
for spread in [1.0, 2.0] {
|
||||
cases.push((0..n).map(|_| (rnd() * 100.0 * spread - 50.0 * (spread - 1.0), rnd() * 220.0 * spread - 60.0 * spread)).collect());
|
||||
// Lasso-like: a random walk snapped to quarter pixels.
|
||||
let (mut x, mut y) = (45.0f32, 75.0f32);
|
||||
cases.push(
|
||||
(0..n)
|
||||
.map(|_| {
|
||||
x = ((x + (rnd() - 0.5) * 12.0 * spread) * 4.0).round() / 4.0;
|
||||
y = ((y + (rnd() - 0.5) * 12.0 * spread) * 4.0).round() / 4.0;
|
||||
(x, y)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
for pts in &cases {
|
||||
for &area in &areas {
|
||||
for aa in [true, false] {
|
||||
let (new, old) = (polygon(pts, area, aa), old_polygon(pts, area, aa));
|
||||
assert_eq!(new.len(), old.len());
|
||||
let diff = new.iter().zip(&old).position(|(a, b)| a.to_bits() != b.to_bits());
|
||||
assert!(diff.is_none(), "{pts:?} {area:?} aa={aa}: first difference at {diff:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combine_modes() {
|
||||
let a = Rect::new(0, 0, 4, 1);
|
||||
|
||||
@@ -363,12 +363,12 @@ fn preference_uses_ambient_filesystem(path: &str) -> bool {
|
||||
|
||||
fn command_uses_ambient_path(id: &str, params: &Value) -> bool {
|
||||
match id {
|
||||
"brush.presets.importAbr" | "gradient.presets.importGrd" | "plugin.install" | "swatches.import" => {
|
||||
"actions.load" | "brush.presets.importAbr" | "gradient.presets.importGrd" | "plugin.install" | "swatches.import" => {
|
||||
// `data` wins over `path` in these commands; any `path` without it reads the filesystem.
|
||||
params.get("data").is_none() && params.get("path").is_some()
|
||||
}
|
||||
// With a `path` the file is written there; without one the bytes come back as `data`.
|
||||
"swatches.export" => params.get("path").is_some(),
|
||||
"actions.save" | "swatches.export" => params.get("path").is_some(),
|
||||
"plugin.reload" => true,
|
||||
_ => false,
|
||||
}
|
||||
@@ -765,6 +765,8 @@ mod tests {
|
||||
("plugin.install", serde_json::json!({"path": " "})),
|
||||
("swatches.import", serde_json::json!({"path": "/outside/set.aco"})),
|
||||
("swatches.export", serde_json::json!({"path": "/outside/set.ase"})),
|
||||
("actions.load", serde_json::json!({"path": "/outside/set.atn"})),
|
||||
("actions.save", serde_json::json!({"path": "/outside/set.atn"})),
|
||||
] {
|
||||
assert!(authorize_engine_command(id, ¶ms).is_err(), "{id}: {params}");
|
||||
}
|
||||
@@ -774,6 +776,8 @@ mod tests {
|
||||
("plugin.install", serde_json::json!({"data": "QUJD"})),
|
||||
("swatches.import", serde_json::json!({"data": "QUJD"})),
|
||||
("swatches.export", serde_json::json!({"format": "ase"})),
|
||||
("actions.load", serde_json::json!({"data": "QUJD"})),
|
||||
("actions.save", serde_json::json!({"set": "S"})),
|
||||
] {
|
||||
assert!(authorize_engine_command(id, ¶ms).is_ok(), "{id}: {params}");
|
||||
}
|
||||
|
||||
@@ -331,6 +331,7 @@ async fn agent_play_refuses_a_recorded_file_open() {
|
||||
name: "Open".into(),
|
||||
steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
let (c, server) = connect_headless(headless).await;
|
||||
let played = run(&c, "actions.play", json!({"action": "Open"})).await;
|
||||
|
||||
@@ -36,11 +36,26 @@ pub struct Action {
|
||||
/// Indices of steps excluded from playback (unchecked in the Actions panel).
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
pub disabled: BTreeSet<usize>,
|
||||
/// Indices of steps whose dialog Photoshop shows during playback (the panel's dialog
|
||||
/// toggle column). Headless playback runs them with their recorded params; the flag is
|
||||
/// kept so Save Actions writes it back.
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
pub dialogs: BTreeSet<usize>,
|
||||
/// The action set the action belongs to: the folder Photoshop shows in the Actions panel,
|
||||
/// filled by Load Actions (`actions.load`) and written by Save Actions (`actions.save`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub set: Option<String>,
|
||||
}
|
||||
|
||||
impl Action {
|
||||
pub fn new(name: impl Into<String>, steps: Vec<(String, Value)>) -> Self {
|
||||
Self { name: name.into(), steps, disabled: BTreeSet::new() }
|
||||
Self { name: name.into(), steps, disabled: BTreeSet::new(), dialogs: BTreeSet::new(), set: None }
|
||||
}
|
||||
|
||||
/// Apply `f` to every per-step index set (`disabled`, `dialogs`) after steps moved.
|
||||
fn remap_steps(&mut self, f: impl Fn(usize) -> Option<usize>) {
|
||||
self.disabled = self.disabled.iter().filter_map(|&i| f(i)).collect();
|
||||
self.dialogs = self.dialogs.iter().filter_map(|&i| f(i)).collect();
|
||||
}
|
||||
|
||||
pub fn step_enabled(&self, step: usize) -> bool {
|
||||
@@ -166,7 +181,7 @@ fn num(v: &Value) -> Option<i64> {
|
||||
v.as_i64().or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64))
|
||||
}
|
||||
|
||||
fn resolve(list: &[Action], p: &Value, cmd: &str) -> Result<usize> {
|
||||
pub(crate) fn resolve(list: &[Action], p: &Value, cmd: &str) -> Result<usize> {
|
||||
let Some(v) = p.get("action") else {
|
||||
return Err(bad(cmd, "needs \"action\" (a name or an index)"));
|
||||
};
|
||||
@@ -210,7 +225,7 @@ fn from_step(p: &Value, len: usize) -> Result<usize> {
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let actions: Vec<Value> = s.actions.list.iter().map(|a| json!({"name": a.name, "steps": a.steps.len()})).collect();
|
||||
let actions: Vec<Value> = s.actions.list.iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect();
|
||||
let recording = s.actions.recording.and_then(|(_, i)| s.actions.list.get(i).map(|a| a.name.clone()));
|
||||
Ok(json!({"actions": actions, "recording": recording}))
|
||||
}
|
||||
@@ -219,7 +234,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let idx = resolve(&s.actions.list, p, "actions.get")?;
|
||||
let action = &s.actions.list[idx];
|
||||
let steps: Vec<Value> = action.steps.iter().map(|(id, params)| json!([id, params])).collect();
|
||||
Ok(json!({"name": action.name, "steps": steps, "disabled": action.disabled}))
|
||||
Ok(json!({"name": action.name, "steps": steps, "disabled": action.disabled, "dialogs": action.dialogs, "set": action.set}))
|
||||
}
|
||||
|
||||
fn record(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -386,7 +401,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let action = &mut s.actions.list[idx];
|
||||
let moved = action.steps.remove(step);
|
||||
action.steps.insert(to, moved);
|
||||
action.disabled = action.disabled.iter().map(|&i| moved_index(i, step, to)).collect();
|
||||
action.remap_steps(|i| Some(moved_index(i, step, to)));
|
||||
let result = json!({"action": action.name, "step": to});
|
||||
s.actions.touch();
|
||||
Ok(result)
|
||||
@@ -434,7 +449,15 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let action = &mut s.actions.list[idx];
|
||||
action.steps.remove(step);
|
||||
action.disabled = action.disabled.iter().filter(|&&i| i != step).map(|&i| if i > step { i - 1 } else { i }).collect();
|
||||
action.remap_steps(|i| {
|
||||
if i == step {
|
||||
None
|
||||
} else if i > step {
|
||||
Some(i - 1)
|
||||
} else {
|
||||
Some(i)
|
||||
}
|
||||
});
|
||||
let result = json!({"action": action.name, "deletedStep": step, "steps": action.steps.len()});
|
||||
s.actions.touch();
|
||||
return Ok(result);
|
||||
@@ -546,7 +569,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
label: "List Actions",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: "{} → {actions:[{name, steps:count}], recording:name|null}",
|
||||
params: "{} → {actions:[{name, steps:count, set:name|null}], recording:name|null}",
|
||||
enabled: always,
|
||||
run: list,
|
||||
journal: false,
|
||||
@@ -556,7 +579,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
label: "Get Action",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"action":name|index} → {name, steps:[[id, params]…], disabled:[step…]} (steps is the shape file.automate.batch and droplets take; disabled lists the 0-based steps playback skips)"##,
|
||||
params: r##"{"action":name|index} → {name, steps:[[id, params]…], disabled:[step…], dialogs:[step…], set:name|null} (steps is the shape file.automate.batch and droplets take; disabled lists the 0-based steps playback skips; dialogs the steps whose dialog Photoshop would show; set the action set from Load Actions)"##,
|
||||
enabled: always,
|
||||
run: get,
|
||||
journal: false,
|
||||
@@ -679,11 +702,17 @@ mod tests {
|
||||
#[test]
|
||||
fn rename_keeps_calls_and_function_key_and_rejects_bad_names() {
|
||||
let mut s = Session::new();
|
||||
s.actions.list.push(Action { name: "Action 1".into(), steps: vec![("layer.new.layer".into(), json!({}))], disabled: Default::default() });
|
||||
s.actions.list.push(Action {
|
||||
name: "Action 1".into(),
|
||||
steps: vec![("layer.new.layer".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
s.actions.list.push(Action {
|
||||
name: "Caller".into(),
|
||||
steps: vec![("actions.play".into(), json!({"action": "Action 1"}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
s.edit_prefs(|p| p.shortcuts.insert(format!("{PLAY_SHORTCUT_PREFIX}Action 1"), "F2".into()));
|
||||
assert_eq!(s.execute("actions.rename", json!({"action": 0, "name": "Sepia"})).unwrap()["action"], "Sepia");
|
||||
@@ -950,7 +979,12 @@ mod tests {
|
||||
#[test]
|
||||
fn play_refuses_recursion() {
|
||||
let mut s = Session::new();
|
||||
s.actions.list.push(Action { name: "Loop".into(), steps: vec![("actions.play".into(), json!({"action": "Loop"}))], disabled: Default::default() });
|
||||
s.actions.list.push(Action {
|
||||
name: "Loop".into(),
|
||||
steps: vec![("actions.play".into(), json!({"action": "Loop"}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
let r = s.execute("actions.play", json!({"action": "Loop"})).unwrap();
|
||||
assert_eq!(r["ran"], 0);
|
||||
assert_eq!(r["failed"]["id"], "actions.play");
|
||||
@@ -969,6 +1003,7 @@ mod tests {
|
||||
name: "Open".into(),
|
||||
steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
let r = s.execute("actions.play", json!({"action": "Open"})).unwrap();
|
||||
assert_eq!(r["ran"], 0);
|
||||
@@ -1046,6 +1081,7 @@ mod tests {
|
||||
name: "Child".into(),
|
||||
steps: vec![("layer.new.layer".into(), json!({"name": "Child layer"}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
s.execute("actions.record", json!({"name": "Parent"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Before"})).unwrap();
|
||||
@@ -1075,8 +1111,14 @@ mod tests {
|
||||
name: "A".into(),
|
||||
steps: vec![("actions.play".into(), json!({"action": "B"})), ("file.new".into(), json!({"width": 2,"height": 2}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
s.actions.list.push(Action {
|
||||
name: "B".into(),
|
||||
steps: vec![("actions.play".into(), json!({"action": "A"}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
s.actions.list.push(Action { name: "B".into(), steps: vec![("actions.play".into(), json!({"action": "A"}))], disabled: Default::default() });
|
||||
let r = s.execute("actions.play", json!({"action": "A"})).unwrap();
|
||||
assert!(r["failed"]["error"].as_str().unwrap().contains("recursive"));
|
||||
assert!(s.documents().is_empty());
|
||||
@@ -1092,6 +1134,7 @@ mod tests {
|
||||
name: format!("N{i}"),
|
||||
steps: if i < 16 { vec![("actions.play".into(), json!({"action":format!("N{}", i + 1)}))] } else { vec![] },
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
let r = s.execute("actions.play", json!({"action": "N0"})).unwrap();
|
||||
@@ -1136,7 +1179,7 @@ mod tests {
|
||||
#[test]
|
||||
fn new_names_do_not_collide_with_named_calls() {
|
||||
let mut s = Session::new();
|
||||
s.actions.list.push(Action { name: "Action 2".into(), steps: vec![], disabled: Default::default() });
|
||||
s.actions.list.push(Action { name: "Action 2".into(), steps: vec![], disabled: Default::default(), ..Default::default() });
|
||||
assert_eq!(s.execute("actions.record", json!({})).unwrap()["action"], "Action 3");
|
||||
s.execute("actions.stop", json!({})).unwrap();
|
||||
assert!(s.execute("actions.record", json!({"name":"Action 2"})).is_err());
|
||||
@@ -1148,7 +1191,7 @@ mod tests {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width":4,"height":4})).unwrap();
|
||||
for name in ["A", "B", "C"] {
|
||||
s.actions.list.push(Action { name: name.into(), steps: vec![], disabled: Default::default() });
|
||||
s.actions.list.push(Action { name: name.into(), steps: vec![], disabled: Default::default(), ..Default::default() });
|
||||
}
|
||||
s.execute("actions.record", json!({"action":"B"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name":"before"})).unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,488 @@
|
||||
use super::*;
|
||||
use photocraft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem};
|
||||
use photocraft_psd::descriptor::{Descriptor, Id, ReferenceItem, UnicodeString, Value as D};
|
||||
use serde_json::json;
|
||||
|
||||
fn item(event: &str, label: &str, d: Option<Descriptor>) -> AtnItem {
|
||||
let event = match event.as_bytes() {
|
||||
[a, b, c, dd] => AtnEvent::Code([*a, *b, *c, *dd]),
|
||||
_ => AtnEvent::Name(event.into()),
|
||||
};
|
||||
AtnItem { event, dictionary: label.into(), descriptor: d, ..Default::default() }
|
||||
}
|
||||
|
||||
fn b64(bytes: &[u8]) -> String {
|
||||
photocraft_paint::tile::b64_encode(bytes)
|
||||
}
|
||||
|
||||
/// A set with a mapped filter, an adjustment layer, selection steps, a layer by name, a Stop,
|
||||
/// a Play, a tool selection (no document effect) and an event PhotoCraft has no command for.
|
||||
fn sample() -> AtnFile {
|
||||
let levels = desc("Lvls").with(
|
||||
"Adjs",
|
||||
D::List(vec![D::Descriptor(
|
||||
desc("LvlA")
|
||||
.with("Chnl", channel_ref(None))
|
||||
.with("Inpt", D::List(vec![long(10.0), long(240.0)]))
|
||||
.with("Gmm ", D::Double(1.2))
|
||||
.with("Otpt", D::List(vec![long(0.0), long(250.0)])),
|
||||
)]),
|
||||
);
|
||||
let make_levels = desc("null").with("null", class_ref("AdjL")).with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(levels))));
|
||||
let select_all =
|
||||
desc("null").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: Id::new("fsel") }])).with("T ", enm("Ordn", "Al "));
|
||||
let select_layer = desc("null").with("null", name_ref("Lyr ", "Shadow")).with("MkVs", D::Boolean(false));
|
||||
let tool = desc("null").with("null", class_ref("MvTl"));
|
||||
let play = desc("null").with("null", D::Reference(vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul("Finish") }]));
|
||||
let stop = desc("null").with("Msge", text("Check the result")).with("Cntn", D::Boolean(true));
|
||||
let fancy = desc("null").with("prompt", text("a cat")).with("DocI", long(5.0));
|
||||
let mut blur = item("GsnB", "Gaussian Blur", Some(desc("null").with("Rds ", px(2.5))));
|
||||
blur.with_dialog = true;
|
||||
let mut off = item("Fltn", "Flatten Image", None);
|
||||
off.enabled = false;
|
||||
AtnFile {
|
||||
name: UnicodeString::new_nul("Test Set"),
|
||||
expanded: true,
|
||||
actions: vec![
|
||||
AtnAction {
|
||||
name: UnicodeString::new_nul("Soften"),
|
||||
function_key: 3,
|
||||
items: vec![
|
||||
blur,
|
||||
item("make", "Make", Some(make_levels)),
|
||||
item("setd", "Set", Some(select_all)),
|
||||
item("select", "Select", Some(select_layer)),
|
||||
item("slct", "Select", Some(tool)),
|
||||
item("stop", "Stop", Some(stop)),
|
||||
item("syntheticFill", "Generative Fill", Some(fancy)),
|
||||
item("play", "Play", Some(play)),
|
||||
off,
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
AtnAction { name: UnicodeString::new_nul("Finish"), items: vec![item("Invs", "Inverse", None)], ..Default::default() },
|
||||
],
|
||||
warnings: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_maps_events_keeps_flags_and_plays() {
|
||||
let mut s = Session::new();
|
||||
let bytes = atn::write(&sample()).unwrap();
|
||||
let r = s.execute("actions.load", json!({"data": b64(&bytes)})).unwrap();
|
||||
assert_eq!(r["set"], "Test Set");
|
||||
assert_eq!(r["actions"], json!(["Soften", "Finish"]));
|
||||
assert_eq!(r["steps"], 10);
|
||||
assert_eq!(r["functionKeys"], json!([{"action": "Soften", "key": "F3"}]));
|
||||
assert_eq!(s.prefs().shortcuts.get("actions.play:Soften").map(String::as_str), Some("F3"));
|
||||
let unsupported: Vec<(String, String)> =
|
||||
r["unsupported"].as_array().unwrap().iter().map(|u| (u["event"].as_str().unwrap().into(), u["name"].as_str().unwrap().into())).collect();
|
||||
assert_eq!(unsupported, [("slct".to_string(), "Select".to_string()), ("syntheticFill".to_string(), "Generative Fill".to_string())]);
|
||||
|
||||
let a = &s.actions.list[0];
|
||||
assert_eq!(a.set.as_deref(), Some("Test Set"));
|
||||
let ids: Vec<&str> = a.steps.iter().map(|(id, _)| id.as_str()).collect();
|
||||
assert_eq!(
|
||||
ids,
|
||||
[
|
||||
"filter.blur.gaussianBlur",
|
||||
"layer.newAdjustmentLayer.levels",
|
||||
"select.all",
|
||||
"layer.select",
|
||||
PHOTOSHOP_STEP,
|
||||
STOP_MESSAGE,
|
||||
PHOTOSHOP_STEP,
|
||||
"actions.play",
|
||||
"layer.flattenImage"
|
||||
]
|
||||
);
|
||||
assert_eq!(a.steps[0].1, json!({"radius": 2.5}));
|
||||
assert_eq!(a.steps[1].1, json!({"inBlack": 10, "inWhite": 240, "gamma": 1.2, "outBlack": 0, "outWhite": 250}));
|
||||
assert_eq!(a.steps[3].1, json!({"layer": "Shadow"}));
|
||||
assert_eq!(a.steps[5].1, json!({"message": "Check the result", "allowContinue": true}));
|
||||
assert_eq!(a.steps[6].1["event"], "syntheticFill");
|
||||
assert_eq!(a.steps[7].1, json!({"action": "Finish"}));
|
||||
assert_eq!(a.dialogs.iter().copied().collect::<Vec<_>>(), [0], "the dialog toggle is kept");
|
||||
assert_eq!(a.disabled.iter().copied().collect::<Vec<_>>(), [4, 8], "tool selections are switched off, as is the step the file had off");
|
||||
assert_eq!(s.actions.list[1].steps, [("select.inverse".to_string(), json!({}))]);
|
||||
|
||||
// Playback: the mapped steps run, the layer is found by name, and the kept Photoshop step
|
||||
// stops the action with its name.
|
||||
s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Shadow"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Top"})).unwrap();
|
||||
let played = s.execute("actions.play", json!({"action": "Soften"})).unwrap();
|
||||
assert_eq!(played["ran"], 5, "{played}");
|
||||
assert_eq!(played["failed"]["step"], 6);
|
||||
assert!(played["failed"]["error"].as_str().unwrap().contains("Generative Fill"), "{played}");
|
||||
let d = s.active().unwrap();
|
||||
assert_eq!(d.doc.layer(d.active_layer.unwrap()).unwrap().name, "Shadow");
|
||||
assert!(d.doc.walk().iter().any(|(_, _, l)| l.name.starts_with("Levels")));
|
||||
|
||||
// Loading the same set again replaces it; a different set with the same action names
|
||||
// gets unique names and its Play steps follow.
|
||||
s.execute("actions.load", json!({"data": b64(&bytes)})).unwrap();
|
||||
assert_eq!(s.actions.list.len(), 2);
|
||||
let r = s.execute("actions.load", json!({"data": b64(&bytes), "set": "Other"})).unwrap();
|
||||
assert_eq!(r["actions"], json!(["Soften 2", "Finish 2"]));
|
||||
assert_eq!(s.actions.list[2].steps[7].1, json!({"action": "Finish 2"}));
|
||||
assert_eq!(s.actions.list[2].set.as_deref(), Some("Other"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_round_trips_through_photoshop_events() {
|
||||
let mut s = Session::new();
|
||||
let bytes = atn::write(&sample()).unwrap();
|
||||
s.execute("actions.load", json!({"data": b64(&bytes)})).unwrap();
|
||||
let first = s.actions.list.clone();
|
||||
let r = s.execute("actions.save", json!({"set": "Test Set"})).unwrap();
|
||||
assert_eq!(r["actions"], json!(["Soften", "Finish"]));
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
let saved = photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap();
|
||||
let file = atn::parse(&saved).unwrap();
|
||||
assert_eq!(file.name.to_string_lossy(), "Test Set");
|
||||
assert_eq!(file.actions[0].function_key, 3);
|
||||
let events: Vec<String> = file.actions[0].items.iter().map(|i| i.event.id()).collect();
|
||||
assert_eq!(events, ["GsnB", "Mk ", "setd", "slct", "slct", "Stop", "syntheticFill", "Ply ", "Fltn"]);
|
||||
assert!(file.actions[0].items[0].with_dialog);
|
||||
assert!(!file.actions[0].items[8].enabled);
|
||||
// The kept Photoshop step is written back byte for byte.
|
||||
assert_eq!(file.actions[0].items[6].descriptor, sample().actions[0].items[6].descriptor);
|
||||
// Play names the set too, as Photoshop does.
|
||||
assert_eq!(get_ref(file.actions[0].items[7].descriptor.as_ref().unwrap(), "null").unwrap().len(), 2);
|
||||
|
||||
// Loading what was saved gives the same actions.
|
||||
let mut t = Session::new();
|
||||
t.execute("actions.load", json!({"data": b64(&saved)})).unwrap();
|
||||
assert_eq!(t.actions.list, first);
|
||||
|
||||
// A step with no Photoshop equivalent fails unless skipped.
|
||||
s.actions.list.push(Action::new("Ours", vec![("filter.render.clouds".into(), json!({}))]));
|
||||
let e = s.execute("actions.save", json!({"action": "Ours"})).unwrap_err().to_string();
|
||||
assert!(e.contains("filter.render.clouds"), "{e}");
|
||||
let r = s.execute("actions.save", json!({"action": "Ours", "skipUnsupported": true})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([{"action": "Ours", "step": 0, "id": "filter.render.clouds"}]));
|
||||
assert_eq!(r["set"], "Ours");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_mapped_command_exports_and_imports_back() {
|
||||
let cases: Vec<(&str, Value)> = vec![
|
||||
("filter.blur.gaussianBlur", json!({"radius": 3.5})),
|
||||
("filter.sharpen.unsharpMask", json!({"amount": 120, "radius": 1.5, "threshold": 3})),
|
||||
("filter.noise.addNoise", json!({"amount": 12.5, "distribution": "gaussian", "monochromatic": true, "seed": 7})),
|
||||
("filter.noise.median", json!({"radius": 2})),
|
||||
("filter.blur.motionBlur", json!({"angle": 45, "distance": 20})),
|
||||
("filter.other.offset", json!({"horizontal": 10, "vertical": -5, "undefinedAreas": "wrap"})),
|
||||
("filter.blur.blur", json!({})),
|
||||
(
|
||||
"image.adjustments.levels",
|
||||
json!({"inBlack": 5, "inWhite": 250, "gamma": 0.9, "outBlack": 0, "outWhite": 255, "red": {"inBlack": 2, "inWhite": 255, "gamma": 1, "outBlack": 0, "outWhite": 255}}),
|
||||
),
|
||||
("image.adjustments.curves", json!({"points": [[0, 0], [128, 140], [255, 255]], "blue": [[0, 10], [255, 245]]})),
|
||||
(
|
||||
"image.adjustments.hueSaturation",
|
||||
json!({"colorize": false, "hue": 10, "saturation": -20, "lightness": 0, "reds": {"hue": 5, "saturation": 0, "lightness": 0, "range": [315, 345, 15, 45]}}),
|
||||
),
|
||||
("image.adjustments.brightnessContrast", json!({"brightness": 10, "contrast": -5, "legacy": false})),
|
||||
("image.adjustments.threshold", json!({"level": 100})),
|
||||
("image.adjustments.posterize", json!({"levels": 4})),
|
||||
("image.adjustments.invert", json!({})),
|
||||
("image.adjustments.colorBalance", json!({"shadows": [1, 2, 3], "midtones": [0, 0, 0], "highlights": [-5, 0, 5], "preserveLuminosity": true})),
|
||||
("image.adjustments.vibrance", json!({"vibrance": 30, "saturation": 5})),
|
||||
("image.adjustments.exposure", json!({"exposure": 0.5, "offset": 0.01, "gamma": 1.1})),
|
||||
("image.adjustments.photoFilter", json!({"color": "#ec8a00", "density": 25, "preserveLuminosity": true})),
|
||||
(
|
||||
"image.adjustments.blackWhite",
|
||||
json!({"reds": 40, "yellows": 60, "greens": 40, "cyans": 60, "blues": 20, "magentas": 80, "tint": true, "tintColor": "#e4d5b0"}),
|
||||
),
|
||||
("image.adjustments.channelMixer", json!({"red": [100, 0, 0, 0], "green": [0, 90, 10, 0], "blue": [0, 0, 100, 5], "monochrome": false})),
|
||||
("image.adjustments.selectiveColor", json!({"method": "absolute", "reds": [10, 0, -5, 0], "neutrals": [0, 0, 0, 3]})),
|
||||
("image.adjustments.desaturate", json!({})),
|
||||
("image.autoTone", json!({})),
|
||||
("image.imageSize", json!({"width": 800, "height": 600, "resolution": 72, "resample": "bicubicSharper"})),
|
||||
("image.canvasSize", json!({"width": 100, "height": 50, "relative": true, "anchor": "topLeft", "extensionColor": "white"})),
|
||||
("image.imageRotation.90cw", json!({})),
|
||||
("image.rotation.arbitrary", json!({"angle": 12.5, "direction": "ccw"})),
|
||||
("edit.transform.flipHorizontal", json!({})),
|
||||
("image.imageRotation.flipCanvasVertical", json!({})),
|
||||
("image.crop", json!({"x": 10, "y": 20, "width": 100, "height": 50, "deleteCroppedPixels": true})),
|
||||
("image.trim", json!({"basedOn": "transparent", "top": true, "bottom": true, "left": false, "right": true})),
|
||||
("image.mode.grayscale", json!({})),
|
||||
("image.mode.bits16", json!({})),
|
||||
("layer.duplicate", json!({"name": "copy"})),
|
||||
("image.duplicate", json!({"mergedOnly": true})),
|
||||
("layer.new.layer", json!({"name": "Ink", "opacity": 0.5, "mode": "Multiply"})),
|
||||
("layer.new.group", json!({"name": "G"})),
|
||||
("layer.groupLayers", json!({})),
|
||||
("layer.new.layerViaCopy", json!({})),
|
||||
("layer.newFillLayer.solidColor", json!({"color": "#336699"})),
|
||||
("layer.newAdjustmentLayer.hueSaturation", json!({})),
|
||||
("layer.newAdjustmentLayer.threshold", json!({"level": 77})),
|
||||
("file.new", json!({"width": 640, "height": 480, "resolution": 72, "mode": "rgb", "depth": 8, "background": "transparent", "name": "Doc"})),
|
||||
("select.all", json!({})),
|
||||
("select.deselect", json!({})),
|
||||
("select.loadSelection", json!({"channel": "transparency"})),
|
||||
("select.loadSelection", json!({"channel": "Alpha 1"})),
|
||||
("select.rect", json!({"x": 1, "y": 2, "width": 30, "height": 40})),
|
||||
("select.rect", json!({"x": 1, "y": 2, "width": 30, "height": 40, "ellipse": true})),
|
||||
("layer.setProps", json!({"name": "Renamed", "opacity": 0.4, "blend": "Linear Light"})),
|
||||
("layer.setProps", json!({"layer": "Shadow", "visible": false})),
|
||||
("layer.setLabelColor", json!({"color": "red"})),
|
||||
("layer.select", json!({"layer": "Shadow", "mode": "add"})),
|
||||
("layer.selectTop", json!({})),
|
||||
("layer.selectBelow", json!({})),
|
||||
("layer.addBelowToSelection", json!({})),
|
||||
("layer.addAboveToSelection", json!({})),
|
||||
("layer.delete", json!({})),
|
||||
("edit.clear", json!({})),
|
||||
("layer.hideLayers", json!({"layer": "Background"})),
|
||||
("layer.showLayers", json!({})),
|
||||
("layer.translate", json!({"dx": 3, "dy": -4})),
|
||||
("layer.arrange.sendToBack", json!({})),
|
||||
("layer.flattenImage", json!({})),
|
||||
("layer.stampVisible", json!({})),
|
||||
("layer.mergeVisible", json!({})),
|
||||
("layer.matting.defringe", json!({"width": 2})),
|
||||
("layer.align.leftEdges", json!({"to": "canvas"})),
|
||||
("select.inverse", json!({})),
|
||||
("select.modify.feather", json!({"radius": 4})),
|
||||
("select.modify.contract", json!({"radius": 1})),
|
||||
("edit.fill", json!({"contents": "color", "color": "#ff0080", "opacity": 50, "mode": "Multiply", "preserveTransparency": true})),
|
||||
("edit.fill", json!({"contents": "foreground", "opacity": 100, "mode": "Normal"})),
|
||||
("edit.stroke", json!({"width": 3, "location": "outside", "opacity": 100, "mode": "Normal", "color": "#000000", "preserveTransparency": false})),
|
||||
("edit.copyMerged", json!({})),
|
||||
("edit.pasteSpecial.pasteInPlace", json!({})),
|
||||
("edit.paste", json!({})),
|
||||
("edit.purge.histories", json!({})),
|
||||
("tools.defaultColors", json!({})),
|
||||
("edit.convertToProfile", json!({"profile": "display-p3", "intent": "perceptual", "bpc": false})),
|
||||
("edit.assignProfile", json!({"profile": "srgb"})),
|
||||
("file.close", json!({})),
|
||||
("file.save", json!({})),
|
||||
("actions.play", json!({"action": "Other", "set": "S"})),
|
||||
(STOP_MESSAGE, json!({"message": "Hi", "allowContinue": false})),
|
||||
];
|
||||
for (id, params) in &cases {
|
||||
let item = export_item(id, params, "S").unwrap_or_else(|| panic!("{id} does not export"));
|
||||
let e = event_for(&item.event).unwrap_or_else(|| panic!("{id} exported as an unknown event {}", item.event.id()));
|
||||
match (e.from)(item.descriptor.as_ref().unwrap()) {
|
||||
Mapped::Steps(steps) => {
|
||||
assert_eq!(steps.len(), 1, "{id}: {steps:?}");
|
||||
assert_eq!(steps[0].0, *id, "{id} came back as another command");
|
||||
let mut back = steps[0].1.clone();
|
||||
normalise(&mut back);
|
||||
if *id == "actions.play" {
|
||||
back["set"] = json!("S");
|
||||
}
|
||||
assert_eq!(back, *params, "{id}");
|
||||
}
|
||||
Mapped::Unsupported { .. } => panic!("{id} does not import back"),
|
||||
}
|
||||
}
|
||||
// Every command the table claims to export has a case above.
|
||||
let covered: std::collections::BTreeSet<&str> = cases.iter().map(|(id, _)| *id).collect();
|
||||
let mut missing: Vec<&str> = EVENTS.iter().flat_map(|e| e.ids.iter().copied()).filter(|id| !covered.contains(id)).collect();
|
||||
missing.sort_unstable();
|
||||
let allowed = [
|
||||
"edit.transform.flipVertical",
|
||||
"edit.transform.rotate180",
|
||||
"edit.transform.rotate90Ccw",
|
||||
"edit.transform.rotate90Cw",
|
||||
"image.autoColor",
|
||||
"image.autoContrast",
|
||||
"image.imageRotation.180",
|
||||
"image.imageRotation.90ccw",
|
||||
"image.imageRotation.flipCanvasHorizontal",
|
||||
"image.mode.bits32",
|
||||
"image.mode.bits8",
|
||||
"image.mode.cmyk",
|
||||
"image.mode.lab",
|
||||
"image.mode.multichannel",
|
||||
"image.mode.rgb",
|
||||
"layer.align.bottomEdges",
|
||||
"layer.align.horizontalCenters",
|
||||
"layer.align.rightEdges",
|
||||
"layer.align.topEdges",
|
||||
"layer.align.verticalCenters",
|
||||
"layer.arrange.bringForward",
|
||||
"layer.arrange.bringToFront",
|
||||
"layer.arrange.sendBackward",
|
||||
"layer.mergeLayers",
|
||||
"layer.new.layerViaCut",
|
||||
"layer.newAdjustmentLayer.blackWhite",
|
||||
"layer.newAdjustmentLayer.brightnessContrast",
|
||||
"layer.newAdjustmentLayer.channelMixer",
|
||||
"layer.newAdjustmentLayer.colorBalance",
|
||||
"layer.newAdjustmentLayer.curves",
|
||||
"layer.newAdjustmentLayer.exposure",
|
||||
"layer.newAdjustmentLayer.invert",
|
||||
"layer.newAdjustmentLayer.levels",
|
||||
"layer.newAdjustmentLayer.photoFilter",
|
||||
"layer.newAdjustmentLayer.posterize",
|
||||
"layer.newAdjustmentLayer.selectiveColor",
|
||||
"layer.newAdjustmentLayer.vibrance",
|
||||
"layer.rasterize.layer",
|
||||
"layer.renameLayer",
|
||||
"layer.selectAbove",
|
||||
"layer.selectBottom",
|
||||
"layer.setAdjustment",
|
||||
"select.allLayers",
|
||||
"select.deselectLayers",
|
||||
"select.grow",
|
||||
"select.modify.border",
|
||||
"select.modify.expand",
|
||||
"select.modify.smooth",
|
||||
"select.reselect",
|
||||
"select.similar",
|
||||
"tools.swapColors",
|
||||
"edit.cut",
|
||||
"edit.copy",
|
||||
"edit.purge.all",
|
||||
"edit.purge.clipboard",
|
||||
"edit.purge.undo",
|
||||
"file.newFromClipboard",
|
||||
"file.revert",
|
||||
"image.adjustments.equalize",
|
||||
"image.revealAll",
|
||||
"filter.blur.blurMore",
|
||||
"filter.blur.boxBlur",
|
||||
"filter.blur.radialBlur",
|
||||
"filter.blur.smartBlur",
|
||||
"filter.blur.surfaceBlur",
|
||||
"filter.noise.despeckle",
|
||||
"filter.noise.dustAndScratches",
|
||||
"filter.other.highPass",
|
||||
"filter.other.maximum",
|
||||
"filter.other.minimum",
|
||||
"filter.sharpen.sharpen",
|
||||
"filter.sharpen.sharpenEdges",
|
||||
"filter.sharpen.sharpenMore",
|
||||
];
|
||||
let unexpected: Vec<&str> = missing.iter().copied().filter(|id| !allowed.contains(id)).collect();
|
||||
assert!(unexpected.is_empty(), "add round-trip cases for {unexpected:?}");
|
||||
// Every command the table names exists.
|
||||
// (Save is the desktop shell's: recorded by it, replayed by it, written by Batch.)
|
||||
for id in EVENTS.iter().flat_map(|e| e.ids.iter()) {
|
||||
assert!(crate::commands::find(id).is_some() || crate::actions_cmds::shell_save_command(id), "the .atn table names an unknown command `{id}`");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_shapes_become_photoshop_steps_not_errors() {
|
||||
// Percent image size, a Paint Bucket fill, a move in points, an unknown adjustment class.
|
||||
let items = vec![
|
||||
item("ImgS", "Image Size", Some(desc("null").with("Wdth", pct(200.0)))),
|
||||
item("Fl ", "Fill", Some(desc("null").with("From", D::Descriptor(desc("Pnt "))).with("Usng", enm("FlCn", "FrgC")))),
|
||||
item(
|
||||
"move",
|
||||
"Move",
|
||||
Some(desc("null").with("null", target_ref("Lyr ")).with(
|
||||
"T ",
|
||||
D::Descriptor(desc("Ofst").with("Hrzn", D::UnitFloat { unit: *b"#Rlt", value: 3.0 }).with("Vrtc", D::UnitFloat { unit: *b"#Rlt", value: 1.0 })),
|
||||
)),
|
||||
),
|
||||
item(
|
||||
"make",
|
||||
"Make",
|
||||
Some(desc("null").with("null", class_ref("AdjL")).with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(desc("GdMp")))))),
|
||||
),
|
||||
item("GsnB", "Gaussian Blur", None),
|
||||
];
|
||||
let file = AtnFile {
|
||||
name: UnicodeString::new_nul("Odd"),
|
||||
expanded: false,
|
||||
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }],
|
||||
warnings: vec![],
|
||||
};
|
||||
let imp = import(&atn::write(&file).unwrap()).unwrap();
|
||||
let ids: Vec<&str> = imp.actions[0].steps.iter().map(|(id, _)| id.as_str()).collect();
|
||||
assert_eq!(ids, [PHOTOSHOP_STEP, PHOTOSHOP_STEP, PHOTOSHOP_STEP, PHOTOSHOP_STEP, "filter.blur.gaussianBlur"]);
|
||||
assert_eq!(imp.unsupported.len(), 4);
|
||||
assert!(imp.actions[0].disabled.is_empty(), "steps with a document effect stay on so playback reports them");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn step_commands_and_bad_params_fail_gracefully() {
|
||||
let mut s = Session::new();
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"path": ""}),
|
||||
json!({"path": "/nonexistent/set.atn"}),
|
||||
json!({"data": 42}),
|
||||
json!({"data": "%%%"}),
|
||||
json!({"data": b64(b"")}),
|
||||
json!({"data": b64(&[0, 0, 0, 12, 0, 0, 0, 0])}),
|
||||
json!({"data": b64(&atn::write(&sample()).unwrap()[..40])}),
|
||||
json!({"data": b64(&atn::write(&sample()).unwrap()), "set": ""}),
|
||||
json!({"data": b64(&atn::write(&sample()).unwrap()), "set": 3}),
|
||||
json!({"data": b64(&atn::write(&sample()).unwrap()), "replace": "yes"}),
|
||||
] {
|
||||
assert!(s.execute("actions.load", p.clone()).is_err(), "{p}");
|
||||
}
|
||||
assert!(s.actions.list.is_empty());
|
||||
for p in [json!({}), json!({"set": "Nope"}), json!({"action": 3}), json!({"path": 7}), json!({"skipUnsupported": "no"}), json!({"set": ""})] {
|
||||
assert!(s.execute("actions.save", p.clone()).is_err(), "{p}");
|
||||
}
|
||||
s.actions.list.push(Action::new("One", vec![("select.all".into(), json!({}))]));
|
||||
assert!(s.execute("actions.save", json!({"path": ""})).is_err());
|
||||
assert!(s.execute("actions.save", json!({})).unwrap()["data"].is_string());
|
||||
|
||||
assert!(s.execute(STOP_MESSAGE, json!({"message": "halt"})).unwrap_err().to_string().contains("halt"));
|
||||
assert_eq!(s.execute(STOP_MESSAGE, json!({"message": "go on", "allowContinue": true})).unwrap()["continued"], true);
|
||||
assert!(s.execute(STOP_MESSAGE, json!({"message": 5, "allowContinue": "x"})).is_err());
|
||||
for p in [json!({}), json!({"event": 1}), json!({"event": "GsnB", "name": "Gaussian Blur", "descriptor": "not base64"})] {
|
||||
assert!(s.execute(PHOTOSHOP_STEP, p.clone()).is_err(), "{p}");
|
||||
}
|
||||
// A Photoshop step with a damaged descriptor is left out of a save rather than crashing it.
|
||||
s.actions.list.push(Action::new("Broken", vec![(PHOTOSHOP_STEP.into(), json!({"event": "GsnB", "name": "Blur", "descriptor": b64(b"\x00\x00\x00")}))]));
|
||||
assert!(s.execute("actions.save", json!({"action": "Broken"})).is_err());
|
||||
assert_eq!(s.execute("actions.save", json!({"action": "Broken", "skipUnsupported": true})).unwrap()["skipped"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_writes_the_file_and_the_set_of_the_selected_action() {
|
||||
let mut s = Session::new();
|
||||
s.execute("actions.load", json!({"data": b64(&atn::write(&sample()).unwrap())})).unwrap();
|
||||
s.actions.list.push(Action::new("Loose", vec![("select.all".into(), json!({}))]));
|
||||
let dir = std::env::temp_dir().join(format!("pc-atn-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Saved.atn");
|
||||
let r = s.execute("actions.save", json!({"action": "Finish", "path": path.to_string_lossy()})).unwrap();
|
||||
assert_eq!((r["set"].as_str(), r["actions"].as_array().map(Vec::len)), (Some("Test Set"), Some(1)));
|
||||
let file = atn::parse(&std::fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!(file.actions.len(), 1);
|
||||
assert_eq!(file.actions[0].name.to_string_lossy(), "Finish");
|
||||
// Without a set, everything goes out under the default name.
|
||||
let r = s.execute("actions.save", json!({})).unwrap();
|
||||
assert_eq!((r["set"].as_str(), r["actions"].as_array().map(Vec::len)), (Some(DEFAULT_SET), Some(3)));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_param_accepts_a_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "A"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "B"})).unwrap();
|
||||
s.execute("layer.select", json!({"layer": "A"})).unwrap();
|
||||
let d = s.active().unwrap();
|
||||
assert_eq!(d.doc.layer(d.active_layer.unwrap()).unwrap().name, "A");
|
||||
assert!(s.execute("layer.select", json!({"layer": "Nope"})).is_err());
|
||||
assert!(s.execute("layer.select", json!({"layer": true})).is_err());
|
||||
assert!(s.execute("layer.select", json!({"layer": -1})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours_convert_both_ways() {
|
||||
assert_eq!(color_hex(&desc("RGBC").with("Rd ", D::Double(255.0)).with("Grn ", D::Double(127.6)).with("Bl ", D::Double(0.0))).as_deref(), Some("#ff8000"));
|
||||
assert_eq!(color_hex(&desc("HSBC").with("H ", ang(0.0)).with("Strt", D::Double(0.0)).with("Brgh", D::Double(100.0))).as_deref(), Some("#ffffff"));
|
||||
assert_eq!(color_hex(&desc("HSBC").with("H ", ang(120.0)).with("Strt", D::Double(100.0)).with("Brgh", D::Double(100.0))).as_deref(), Some("#00ff00"));
|
||||
assert_eq!(color_hex(&desc("Grsc").with("Gry ", D::Double(100.0))).as_deref(), Some("#000000"));
|
||||
assert_eq!(color_hex(&desc("CMYC")), None);
|
||||
assert_eq!(color_desc("#12ab9F").map(|d| color_hex(&d)), Some(Some("#12ab9f".into())));
|
||||
assert_eq!(color_desc("12ab9f"), None);
|
||||
assert_eq!(color_desc("#12ab9"), None);
|
||||
assert_eq!(color_desc("#ééééé"), None);
|
||||
}
|
||||
@@ -340,8 +340,18 @@ fn a_failed_step_inside_a_called_action_fails_scripts_and_batch() {
|
||||
images(&dir, 1, 8, 4);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 6})).unwrap();
|
||||
s.actions.list.push(Action { name: "Rotate".into(), steps: vec![("image.imageRotation.90cw".into(), json!({}))], disabled: Default::default() });
|
||||
s.actions.list.push(Action { name: "Bad".into(), steps: vec![("layer.delete".into(), json!({"layer": 999_999}))], disabled: Default::default() });
|
||||
s.actions.list.push(Action {
|
||||
name: "Rotate".into(),
|
||||
steps: vec![("image.imageRotation.90cw".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
s.actions.list.push(Action {
|
||||
name: "Bad".into(),
|
||||
steps: vec![("layer.delete".into(), json!({"layer": 999_999}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
// A script stops at the failed call and reports it.
|
||||
let r = s.execute("file.scripts.browse", json!({"steps": [["actions.play", {"action": "Bad"}], ["image.imageRotation.90cw", {}]]})).unwrap();
|
||||
assert_eq!(r["ok"], false, "{r}");
|
||||
@@ -358,6 +368,6 @@ fn a_failed_step_inside_a_called_action_fails_scripts_and_batch() {
|
||||
assert!(r["errors"][0]["error"].as_str().unwrap().contains("no such layer"), "{r}");
|
||||
// An action that batches itself stops as a recursive call instead of overflowing the stack.
|
||||
let inner = json!({"steps": [["actions.play", {"action": "Loop"}]], "input": dir.clone(), "output": format!("{dir}/inner"), "format": "png"});
|
||||
s.actions.list.push(Action { name: "Loop".into(), steps: vec![("file.automate.batch".into(), inner)], disabled: Default::default() });
|
||||
s.actions.list.push(Action { name: "Loop".into(), steps: vec![("file.automate.batch".into(), inner)], disabled: Default::default(), ..Default::default() });
|
||||
batch(&mut s, "Loop");
|
||||
}
|
||||
@@ -172,13 +172,18 @@ impl ColorSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check that each working space resolves to a profile of the right colour space.
|
||||
/// Check that each working space resolves to the right colour space and RGB can be both a
|
||||
/// source and editing destination for the configured rendering intent.
|
||||
pub fn validate_settings(c: &ColorSettings) -> std::result::Result<(), String> {
|
||||
for (space, spec) in [(ColorSpace::Rgb, &c.working_rgb), (ColorSpace::Cmyk, &c.working_cmyk), (ColorSpace::Gray, &c.working_gray)] {
|
||||
let p = resolve_profile(spec, None, space_mode(space)).map_err(|e| e.to_string())?;
|
||||
if p.color_space != space {
|
||||
return Err(format!("working space `{spec}` is {:?}, not {space:?}", p.color_space));
|
||||
}
|
||||
if space == ColorSpace::Rgb {
|
||||
p.pcs_to_device(c.intent()).map_err(|e| format!("working RGB space `{spec}` cannot be a destination for {}: {e}", c.intent().id()))?;
|
||||
p.device_to_pcs(c.intent()).map_err(|e| format!("working RGB space `{spec}` cannot be a source for {}: {e}", c.intent().id()))?;
|
||||
}
|
||||
}
|
||||
let m = c.monitor_profile.as_str();
|
||||
if !(m.is_empty() || m == "auto") {
|
||||
@@ -215,13 +220,16 @@ pub struct ColorState {
|
||||
|
||||
impl ColorState {
|
||||
/// The working profile of a mode from Color Settings (the built-in default when the
|
||||
/// setting does not resolve).
|
||||
/// setting does not resolve or cannot be both an RGB source and editing destination).
|
||||
pub fn working(&self, mode: ColorMode) -> Arc<Profile> {
|
||||
let space = mode_space(mode);
|
||||
self.settings
|
||||
.working_spec(space)
|
||||
.and_then(|spec| resolve_profile(spec, None, Some(mode)).ok())
|
||||
.filter(|p| p.color_space == space)
|
||||
.filter(|p| {
|
||||
p.color_space == space
|
||||
&& (space != ColorSpace::Rgb || (p.pcs_to_device(self.settings.intent()).is_ok() && p.device_to_pcs(self.settings.intent()).is_ok()))
|
||||
})
|
||||
.unwrap_or_else(|| working_profile(mode))
|
||||
}
|
||||
|
||||
|
||||
@@ -254,9 +254,33 @@ fn set_clipped(s: &mut Session, p: &Value, clip: bool) -> Result<Value> {
|
||||
Ok(json!({"layers": ids.iter().map(|id| id.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that
|
||||
/// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays
|
||||
/// in another document). `None` when the param is absent.
|
||||
pub(crate) fn explicit_layer(s: &Session, p: &Value) -> Result<Option<LayerId>> {
|
||||
match p.get("layer") {
|
||||
Some(Value::Number(n)) => {
|
||||
n.as_u64().map(|id| Some(LayerId(id))).ok_or_else(|| EngineError::Other(format!("layer id {n} is not a non-negative integer")))
|
||||
}
|
||||
Some(Value::String(name)) => {
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
d.doc
|
||||
.walk()
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|(_, _, l)| l.name == *name)
|
||||
.map(|(_, _, l)| Some(l.id))
|
||||
.ok_or_else(|| EngineError::Other(format!("no layer named \"{name}\"")))
|
||||
}
|
||||
Some(Value::Null) | None => Ok(None),
|
||||
Some(other) => Err(EngineError::Other(format!("`layer` must be an id or a name, not {other}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer a command targets: [`explicit_layer`], else the active layer.
|
||||
pub(crate) fn layer_param(s: &Session, p: &Value) -> Result<LayerId> {
|
||||
match p.get("layer").and_then(Value::as_u64) {
|
||||
Some(id) => Ok(LayerId(id)),
|
||||
match explicit_layer(s, p)? {
|
||||
Some(id) => Ok(id),
|
||||
None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())),
|
||||
}
|
||||
}
|
||||
@@ -1203,6 +1227,7 @@ fn build() -> Vec<CommandSpec> {
|
||||
v.extend(crate::brush_preset_cmds::specs());
|
||||
v.extend(crate::eraser_cmds::specs());
|
||||
v.extend(crate::preset_import_cmds::specs());
|
||||
v.extend(crate::atn_cmds::specs());
|
||||
v.extend(crate::swatch_cmds::specs());
|
||||
v.extend(crate::retouch_cmds::specs());
|
||||
v.extend(crate::redeye_cmds::specs());
|
||||
|
||||
@@ -233,8 +233,11 @@ mod tests {
|
||||
let (mut s, _) = disc(8);
|
||||
let before = s.active().unwrap().revision;
|
||||
assert!(s.execute(CMD, json!({"layer": 999_999})).is_err());
|
||||
// Wrong types fall back to the defaults (the active layer, layer-only sampling, refined).
|
||||
assert!(s.execute(CMD, json!({"layer": "x", "sampleAllLayers": 3, "refine": "no"})).is_ok());
|
||||
// A `layer` string names a layer; one that isn't there is an error, not the active layer.
|
||||
assert!(s.execute(CMD, json!({"layer": "x"})).is_err());
|
||||
assert_eq!(s.active().unwrap().revision, before);
|
||||
// Wrong types for the options fall back to the defaults (layer-only sampling, refined).
|
||||
assert!(s.execute(CMD, json!({"sampleAllLayers": 3, "refine": "no"})).is_ok());
|
||||
assert!(s.active().unwrap().revision > before);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
//!
|
||||
//! Each one is `edit.fill` with the colour and Preserve Transparency fixed: one "Fill" history
|
||||
//! step, the Channels panel target (alpha channel, Quick Mask) honoured, locked layers refused.
|
||||
//! When targeting a vector shape layer, the fill keys recolor the shape's fill.
|
||||
|
||||
use photocraft_doc::{LayerContent, LayerId};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::commands::CommandSpec;
|
||||
@@ -17,18 +19,56 @@ pub const IDS: [&str; 5] = ["edit.fillForeground", "edit.fillBackground", "edit.
|
||||
|
||||
const PARAMS: &str = r##"{"layer":id?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?}"##;
|
||||
|
||||
fn target_shape_layer(s: &Session, p: &Value) -> Option<LayerId> {
|
||||
if let Some(t) = p.get("target")
|
||||
&& (t.as_str() == Some("mask") || t.as_str() == Some("quickMask") || t.get("channel").is_some())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let st = s.active()?;
|
||||
if st.channel_view.target == crate::channel_cmds::ChannelTarget::LayerMask {
|
||||
return None;
|
||||
}
|
||||
let id = if let Some(v) = p.get("layer") { LayerId(v.as_u64()?) } else { st.active_layer? };
|
||||
let layer = st.doc.layer(id)?;
|
||||
if matches!(layer.content, LayerContent::Shape(_)) { Some(id) } else { None }
|
||||
}
|
||||
|
||||
/// The colour fill keys also recolor a targeted shape layer's fill.
|
||||
fn enabled(s: &Session) -> std::result::Result<(), String> {
|
||||
if target_shape_layer(s, &Value::Null).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
fill_enabled(s)
|
||||
}
|
||||
|
||||
/// Enabled when `edit.fill` is (Fill from History has no shape-layer meaning).
|
||||
fn fill_enabled(s: &Session) -> std::result::Result<(), String> {
|
||||
let edit_fill = crate::commands::find("edit.fill").ok_or_else(|| "Fill is unavailable".to_string())?;
|
||||
(edit_fill.enabled)(s)
|
||||
}
|
||||
|
||||
/// Run `edit.fill` with `color` (the foreground or background colour) and Preserve Transparency.
|
||||
/// Run `edit.fill` with `color` (the foreground or background colour) and Preserve Transparency,
|
||||
/// or recolor the vector shape fill when targeting a vector shape layer.
|
||||
fn fill(s: &mut Session, p: &Value, cmd: &str, background: bool, preserve: bool) -> Result<Value> {
|
||||
let mut q: Map<String, Value> = match p {
|
||||
Value::Object(m) => m.clone(),
|
||||
Value::Null => Map::new(),
|
||||
_ => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "expected an object".into() }),
|
||||
};
|
||||
|
||||
if let Some(id) = target_shape_layer(s, p) {
|
||||
let c = if background { s.tools.background } else { s.tools.foreground };
|
||||
let q_u8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
let hex = if c[3] < 1.0 {
|
||||
format!("#{:02x}{:02x}{:02x}{:02x}", q_u8(c[0]), q_u8(c[1]), q_u8(c[2]), q_u8(c[3]))
|
||||
} else {
|
||||
format!("#{:02x}{:02x}{:02x}", q_u8(c[0]), q_u8(c[1]), q_u8(c[2]))
|
||||
};
|
||||
let shape_edit = crate::commands::find("shape.edit").ok_or_else(|| EngineError::Other("shape.edit is unavailable".into()))?;
|
||||
return (shape_edit.run)(s, &json!({ "layer": id.0, "fill": hex }));
|
||||
}
|
||||
|
||||
// The colour and transparency handling are what the key means; don't let params override them.
|
||||
for k in ["color", "contents", "pattern", "preserveTransparency", "opacity"] {
|
||||
q.remove(k);
|
||||
@@ -104,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
menu: &[],
|
||||
shortcut: Some("Cmd+Alt+Backspace"),
|
||||
params: r##"{"state":n? (default: the History Brush's source, the oldest state still held),"layer":id?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?,"preserveTransparency":bool?}"##,
|
||||
enabled,
|
||||
enabled: fill_enabled,
|
||||
run: fill_history,
|
||||
journal: true,
|
||||
},
|
||||
@@ -260,4 +300,40 @@ mod tests {
|
||||
assert_eq!(sc("edit.fillForegroundPreserve"), Some("Alt+Shift+Backspace"));
|
||||
assert_eq!(sc("edit.fillBackgroundPreserve"), Some("Cmd+Shift+Backspace"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_keys_recolor_shape_layer() {
|
||||
let mut s = session();
|
||||
s.execute("shape.create", json!({"kind": "rect", "rect": [1, 1, 5, 5], "fill": "#000000"})).unwrap();
|
||||
let info = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(info["fill"], "#000000");
|
||||
|
||||
// Alt+Backspace fills with foreground (#ff0000)
|
||||
s.execute("edit.fillForeground", json!({})).unwrap();
|
||||
let info_fg = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(info_fg["fill"], "#ff0000");
|
||||
|
||||
// Cmd+Backspace fills with background (#0000ff)
|
||||
s.execute("edit.fillBackground", json!({})).unwrap();
|
||||
let info_bg = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(info_bg["fill"], "#0000ff");
|
||||
|
||||
// Undo restores previous fill (#ff0000)
|
||||
assert!(s.undo());
|
||||
let info_undone = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(info_undone["fill"], "#ff0000");
|
||||
|
||||
// Alt+Shift+Backspace also recolors shape
|
||||
s.execute("tools.setColors", json!({"foreground": "#00ff00"})).unwrap();
|
||||
s.execute("edit.fillForegroundPreserve", json!({})).unwrap();
|
||||
let info_shift = s.execute("shape.info", json!({})).unwrap();
|
||||
assert_eq!(info_shift["fill"], "#00ff00");
|
||||
|
||||
// Locked shape layer errors gracefully without crashing
|
||||
s.execute("layer.lockLayers", json!({"pixels": true})).unwrap();
|
||||
for id in &IDS[..4] {
|
||||
let err = s.execute(id, json!({})).unwrap_err().to_string();
|
||||
assert!(err.contains("locked"), "{id}: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,7 +115,7 @@ fn range_order(layers: &[Layer], include_collapsed: bool, out: &mut Vec<LayerId>
|
||||
|
||||
/// `layer.select`: `{"layer": id, "mode": "replace|toggle|range|add"}`.
|
||||
pub fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = LayerId(p.get("layer").and_then(Value::as_u64).ok_or_else(|| bad("layer.select", "missing `layer`"))?);
|
||||
let id = crate::commands::explicit_layer(s, p)?.ok_or_else(|| bad("layer.select", "missing `layer`"))?;
|
||||
let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace");
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
if st.doc.layer(id).is_none() {
|
||||
@@ -293,8 +293,8 @@ pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if dx == 0 && dy == 0 {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let roots = match p.get("layer").and_then(Value::as_u64) {
|
||||
Some(id) => vec![LayerId(id)],
|
||||
let roots = match crate::commands::explicit_layer(s, p)? {
|
||||
Some(id) => vec![id],
|
||||
None => selected(s),
|
||||
};
|
||||
if roots.is_empty() {
|
||||
@@ -1188,8 +1188,8 @@ pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> {
|
||||
/// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves
|
||||
/// into a new group placed where the top-most of them was. Bottom-to-top order is preserved.
|
||||
pub fn group_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = match p.get("layer").and_then(Value::as_u64) {
|
||||
Some(id) => vec![LayerId(id)],
|
||||
let ids = match crate::commands::explicit_layer(s, p)? {
|
||||
Some(id) => vec![id],
|
||||
None => selected(s),
|
||||
};
|
||||
if ids.is_empty() {
|
||||
|
||||
@@ -837,10 +837,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";
|
||||
let id = match p.get("layer").and_then(Value::as_u64) {
|
||||
Some(id) => photocraft_doc::LayerId(id),
|
||||
None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into()))?,
|
||||
};
|
||||
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 {
|
||||
return Err(bad(CMD, format!("at most {MAX_EFFECTS} effects")));
|
||||
@@ -891,10 +888,7 @@ fn set_effect(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
|
||||
let (fx, pattern) = crate::pattern_cmds::resolve_effect(s, fx)?;
|
||||
let label = format!("Layer Style: {}", fx.label());
|
||||
let add = b(p, "add", false);
|
||||
let id = match p.get("layer").and_then(Value::as_u64) {
|
||||
Some(id) => photocraft_doc::LayerId(id),
|
||||
None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into()))?,
|
||||
};
|
||||
let id = crate::commands::layer_param(s, p)?;
|
||||
s.edit(&label, |doc, _| {
|
||||
if let Some(pat) = &pattern {
|
||||
crate::pattern_cmds::ensure_in_doc(doc, pat);
|
||||
|
||||
@@ -14,6 +14,7 @@ pub mod align_cmds;
|
||||
mod allocation;
|
||||
pub mod analysis_cmds;
|
||||
pub mod artboard_cmds;
|
||||
pub mod atn_cmds;
|
||||
pub mod automate_cmds;
|
||||
pub mod background_cmds;
|
||||
pub mod brush_cmds;
|
||||
|
||||
+26
-11
@@ -1612,7 +1612,9 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Set one dotted path, routing `colorSettings.*` to the colour state.
|
||||
fn set_pref(&mut self, path: &str, value: Value) -> std::result::Result<(), String> {
|
||||
/// Batches defer colour validation until their complete candidate is staged. Returns
|
||||
/// whether colour settings were touched, including whole-section/root-object updates.
|
||||
fn set_pref(&mut self, path: &str, value: Value, validate_color: bool) -> std::result::Result<bool, String> {
|
||||
if let Some(rest) = path.strip_prefix("colorSettings") {
|
||||
let mut cur = serde_json::to_value(&self.color.settings).map_err(|e| e.to_string())?;
|
||||
let rest = rest.trim_start_matches('.');
|
||||
@@ -1621,19 +1623,23 @@ impl Session {
|
||||
} else {
|
||||
set_path(&mut cur, rest, value)?;
|
||||
}
|
||||
self.color.settings = serde_json::from_value(cur).map_err(|e| format!("invalid value for `{path}`: {e}"))?;
|
||||
crate::color_cmds::validate_settings(&self.color.settings)?;
|
||||
let next = serde_json::from_value(cur).map_err(|e| format!("invalid value for `{path}`: {e}"))?;
|
||||
if validate_color {
|
||||
crate::color_cmds::validate_settings(&next)?;
|
||||
}
|
||||
self.color.settings = next;
|
||||
self.prefs.edit(|_| ());
|
||||
return Ok(());
|
||||
return Ok(true);
|
||||
}
|
||||
let mut next = self.prefs().clone();
|
||||
let mut color_changed = false;
|
||||
if path.is_empty() || SECTIONS.iter().any(|(id, _)| *id == path) || matches!(path, "shortcuts" | "menus" | "toolbar") {
|
||||
// Whole section (or everything): merge the object key by key so each value is checked.
|
||||
let obj = value.as_object().ok_or_else(|| format!("`{path}` needs an object"))?;
|
||||
for (k, v) in obj {
|
||||
let p = if path.is_empty() { k.clone() } else { format!("{path}.{k}") };
|
||||
if path.is_empty() && k == "colorSettings" {
|
||||
self.set_pref("colorSettings", v.clone())?;
|
||||
color_changed |= self.set_pref("colorSettings", v.clone(), validate_color)?;
|
||||
continue;
|
||||
}
|
||||
if v.is_object() && !p.starts_with("shortcuts") && !p.ends_with(".colors") && next.get(&p).is_some_and(|c| c.is_object()) {
|
||||
@@ -1702,7 +1708,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
self.prefs.edit(|p| *p = next);
|
||||
Ok(())
|
||||
Ok(color_changed)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1736,13 +1742,22 @@ fn prefs_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// All or nothing: validate against a scratch copy first.
|
||||
let (saved_prefs, saved_color) = (s.prefs().clone(), s.color.settings.clone());
|
||||
let mut color_changed = false;
|
||||
for (path, v) in &changes {
|
||||
if let Err(e) = s.set_pref(path, v.clone()) {
|
||||
s.prefs.edit(|p| *p = saved_prefs);
|
||||
s.color.settings = saved_color;
|
||||
return Err(bad(cmd, e));
|
||||
match s.set_pref(path, v.clone(), false) {
|
||||
Ok(touched) => color_changed |= touched,
|
||||
Err(e) => {
|
||||
s.prefs.edit(|p| *p = saved_prefs);
|
||||
s.color.settings = saved_color;
|
||||
return Err(bad(cmd, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
if color_changed && let Err(e) = crate::color_cmds::validate_settings(&s.color.settings) {
|
||||
s.prefs.edit(|p| *p = saved_prefs);
|
||||
s.color.settings = saved_color;
|
||||
return Err(bad(cmd, e));
|
||||
}
|
||||
// `colorSettings.blendTextGamma` lives in the compositor too, as `edit.colorSettings` sets it.
|
||||
photocraft_compose::psblend::set_text_gamma(s.color.settings.blend_text_gamma);
|
||||
s.apply_prefs();
|
||||
@@ -1761,7 +1776,7 @@ fn prefs_reset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let defaults = serde_json::to_value(crate::color_cmds::ColorSettings::default()).map_err(|e| bad("prefs.reset", e.to_string()))?;
|
||||
let key = path.strip_prefix("colorSettings.").unwrap_or(path);
|
||||
let def = get_path(&defaults, key).cloned().ok_or_else(|| bad("prefs.reset", format!("unknown preference `{path}`")))?;
|
||||
s.set_pref(path, def).map_err(|e| bad("prefs.reset", e))?;
|
||||
s.set_pref(path, def, true).map_err(|e| bad("prefs.reset", e))?;
|
||||
}
|
||||
None => {
|
||||
s.color.settings = Default::default();
|
||||
|
||||
@@ -29,18 +29,22 @@ pub fn moves_whole(layer: &Layer) -> bool {
|
||||
/// content within the selection, or all of it for a layer that [`moves_whole`] (#2630).
|
||||
/// Content scans are cached per tile: snapping asks for every layer's bounds per Move drag.
|
||||
pub fn transform_bounds(doc: &Document, layer: &Layer) -> Rect {
|
||||
let content = match &layer.content {
|
||||
LayerContent::Group(g) => g.children.iter().map(|l| transform_bounds(doc, l)).fold(Rect::EMPTY, |a, b| a.union(&b)),
|
||||
_ => layer.surface().map_or(Rect::EMPTY, photocraft_compose::bounds::content_bounds),
|
||||
};
|
||||
let content =
|
||||
if content.is_empty() { layer.mask.as_ref().map_or(Rect::EMPTY, |m| photocraft_compose::bounds::content_bounds(&m.surface)) } else { content };
|
||||
let content = whole_layer_bounds(layer);
|
||||
match &doc.selection {
|
||||
Some(sel) if !moves_whole(layer) => content.intersect(&sel.content_bounds()),
|
||||
_ => content,
|
||||
}
|
||||
}
|
||||
|
||||
/// A group moves all its descendants, so its frame must not clip raster children to the selection.
|
||||
fn whole_layer_bounds(layer: &Layer) -> Rect {
|
||||
let content = match &layer.content {
|
||||
LayerContent::Group(g) => g.children.iter().map(whole_layer_bounds).fold(Rect::EMPTY, |a, b| a.union(&b)),
|
||||
_ => layer.surface().map_or(Rect::EMPTY, photocraft_compose::bounds::content_bounds),
|
||||
};
|
||||
if content.is_empty() { layer.mask.as_ref().map_or(Rect::EMPTY, |m| photocraft_compose::bounds::content_bounds(&m.surface)) } else { content }
|
||||
}
|
||||
|
||||
/// Warp a surface whose pixels outside the content read as `default` (masks, selections):
|
||||
/// warp the content with alpha, then flatten back onto the default value.
|
||||
pub(crate) fn warp_gray(s: &Surface, h: &Homography, interp: Interp) -> Result<Surface> {
|
||||
@@ -422,10 +426,7 @@ fn with_panel_target(s: &Session, p: &Value) -> Value {
|
||||
fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let p = &with_panel_target(s, p);
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let id = match p.get("layer").and_then(Value::as_u64) {
|
||||
Some(v) => Some(LayerId(v)),
|
||||
None => st.active_layer,
|
||||
};
|
||||
let id = crate::commands::explicit_layer(s, p)?.or(st.active_layer);
|
||||
let lone = lone_target(&st.doc, id, p)?;
|
||||
let id = match (id, lone.is_some() && crate::channel_cmds::is_channel_target(p)) {
|
||||
(_, true) => None,
|
||||
@@ -526,8 +527,12 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn session() -> Session {
|
||||
session_depth(8)
|
||||
}
|
||||
|
||||
fn session_depth(depth: u32) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.edit("paint", |doc, active| {
|
||||
let l = doc.layer_mut(active.unwrap()).unwrap();
|
||||
@@ -689,7 +694,11 @@ mod tests {
|
||||
|
||||
/// `session()` plus a reveal-all mask with `hide` painted black (linked unless `linked` is false).
|
||||
fn masked(hide: &[Rect], linked: bool) -> Session {
|
||||
let mut s = session();
|
||||
masked_depth(hide, linked, 8)
|
||||
}
|
||||
|
||||
fn masked_depth(hide: &[Rect], linked: bool, depth: u32) -> Session {
|
||||
let mut s = session_depth(depth);
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
s.edit("mask", |doc, active| {
|
||||
let m = doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap();
|
||||
@@ -887,6 +896,66 @@ mod tests {
|
||||
assert_eq!(transform_bounds(&st.doc, st.doc.layer(st.active_layer.unwrap()).unwrap()), Rect::new(10, 10, 15, 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_transform_ignores_selections_inside_its_children() {
|
||||
group_transform_with_selection(Rect::new(10, 10, 15, 15));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_transform_ignores_selections_outside_its_children() {
|
||||
group_transform_with_selection(Rect::new(70, 70, 80, 80));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_transform_presets_rotate_about_the_whole_group() {
|
||||
for depth in [8, 16, 32] {
|
||||
for x in [10, 70] {
|
||||
let mut s = masked_depth(&[Rect::new(10, 10, 15, 20)], true, depth);
|
||||
let child = s.active().unwrap().active_layer.unwrap();
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
s.execute("select.rect", json!({"x": x, "y": 10, "width": 5, "height": 5})).unwrap();
|
||||
s.execute("edit.transform.rotate180", json!({})).unwrap();
|
||||
let layer = s.active().unwrap().doc.layer(child).unwrap();
|
||||
assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 30, 20), "rotate about the group's centre, not the selection's");
|
||||
let mask = &layer.mask.as_ref().unwrap().surface;
|
||||
assert_eq!(mask.sample_channel(27, 15, 0), 0.0);
|
||||
assert_eq!(mask.sample_channel(12, 15, 0), 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn group_transform_with_selection(selection: Rect) {
|
||||
for depth in [8, 16, 32] {
|
||||
for nested in [false, true] {
|
||||
let mut s = masked_depth(&[Rect::new(10, 10, 15, 20)], true, depth);
|
||||
let child = s.active().unwrap().active_layer.unwrap();
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
if nested {
|
||||
s.execute("layer.groupLayers", json!({})).unwrap();
|
||||
}
|
||||
s.execute("select.rect", json!({"x": selection.x0, "y": selection.y0, "width": selection.width(), "height": selection.height()})).unwrap();
|
||||
let steps = s.active().unwrap().history.entries().len();
|
||||
let result = s.execute("edit.transform", json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]], "interpolation": "nearest"})).unwrap();
|
||||
assert_eq!(result["rect"], json!([10.0, 10.0, 30.0, 20.0]), "frame must include the whole group (nested={nested})");
|
||||
let st = s.active().unwrap();
|
||||
let layer = st.doc.layer(child).unwrap();
|
||||
assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 50, 30));
|
||||
let mask = &layer.mask.as_ref().unwrap().surface;
|
||||
assert_eq!(mask.sample_channel(19, 20, 0), 0.0, "the linked mask scales with its complete layer");
|
||||
assert_eq!(mask.sample_channel(21, 20, 0), 1.0);
|
||||
assert_eq!(st.history.entries().len(), steps + 1);
|
||||
assert!(s.undo());
|
||||
let st = s.active().unwrap();
|
||||
let layer = st.doc.layer(child).unwrap();
|
||||
assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 30, 20));
|
||||
assert_eq!(layer.mask.as_ref().unwrap().surface.sample_channel(19, 15, 0), 1.0);
|
||||
assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), selection);
|
||||
assert!(s.redo());
|
||||
assert_eq!(s.active().unwrap().doc.layer(child).unwrap().surface().unwrap().content_bounds(), Rect::new(10, 10, 50, 30));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feathered_selection_identity_transform_preserves_pixels() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
//! Working RGB must support reading and editing for the configured intent.
|
||||
|
||||
use photocraft_cms::{
|
||||
Builtin, Curve, Intent, Profile, ProfileClass,
|
||||
pipeline::Stage,
|
||||
profile::{Lut, LutKind},
|
||||
};
|
||||
use photocraft_color::{Color, ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, Layer};
|
||||
use photocraft_engine::Session;
|
||||
use photocraft_geom::Size;
|
||||
use serde_json::json;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Repository-built, serialized profiles test capabilities without proprietary ICC fixtures
|
||||
/// or an invented inverse. The synthetic BToA table is not an appearance oracle.
|
||||
fn directional_profile(source: bool, destination: bool) -> Profile {
|
||||
let mut p = Builtin::DisplayP3.profile().clone();
|
||||
p.class = ProfileClass::Input;
|
||||
p.description = "Synthetic directional RGB".into();
|
||||
let curves = p.trc.take().unwrap().to_vec();
|
||||
let matrix = p.matrix.take().unwrap();
|
||||
let matrix = Stage::Matrix { rows: 3, cols: 3, m: matrix.iter().flatten().map(|v| v * 32768.0 / 65535.0).collect(), offset: vec![0.0; 3] };
|
||||
let a2b = Lut { kind: LutKind::Ab, inputs: 3, outputs: 3, stages: vec![Stage::Curves(curves), matrix, Stage::Curves(vec![Curve::Identity; 3])] };
|
||||
let b2a = Lut { kind: LutKind::Ab, inputs: 3, outputs: 3, stages: vec![Stage::Curves(vec![Curve::Identity; 3])] };
|
||||
p.a2b = if source { [Some(a2b.clone()), Some(a2b.clone()), Some(a2b)] } else { Default::default() };
|
||||
p.b2a = if destination { [Some(b2a.clone()), Some(b2a.clone()), Some(b2a)] } else { Default::default() };
|
||||
p
|
||||
}
|
||||
|
||||
struct ProfileFile {
|
||||
path: std::path::PathBuf,
|
||||
profile: Profile,
|
||||
}
|
||||
|
||||
impl ProfileFile {
|
||||
fn new(profile: Profile) -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let path = std::env::temp_dir().join(format!("photocraft-working-rgb-{}-{}.icc", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let bytes = profile.with_encoded_bytes().to_bytes();
|
||||
let profile = Profile::parse(&bytes).unwrap();
|
||||
std::fs::write(&path, &*bytes).unwrap();
|
||||
Self { path, profile }
|
||||
}
|
||||
fn spec(&self) -> &str {
|
||||
self.path.to_str().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ProfileFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn reject_one_way_setting(source: bool, destination: bool, missing_direction: &str) {
|
||||
let file = ProfileFile::new(directional_profile(source, destination));
|
||||
for intent in Intent::ALL {
|
||||
assert_eq!(file.profile.device_to_pcs(intent).is_ok(), source);
|
||||
assert_eq!(file.profile.pcs_to_device(intent).is_ok(), destination);
|
||||
let mut s = Session::new();
|
||||
let before = s.color.settings.clone();
|
||||
let error = s.execute("edit.colorSettings", json!({"workingRgb": file.spec(), "intent": intent.id(), "bpc": false})).unwrap_err();
|
||||
assert!(error.to_string().contains(missing_direction), "{error}");
|
||||
assert_eq!(s.color.settings, before, "reject the full settings update before any mutation");
|
||||
assert!(s.execute("prefs.set", json!({"path": "colorSettings.workingRgb", "value": file.spec()})).is_err());
|
||||
assert_eq!(s.color.settings, before, "individual preference setter also rejects atomically");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_only_rgb_working_space_is_rejected_atomically() {
|
||||
reject_one_way_setting(true, false, "destination");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destination_only_rgb_working_space_is_rejected_atomically() {
|
||||
reject_one_way_setting(false, true, "source");
|
||||
}
|
||||
|
||||
fn legacy_session(file: &ProfileFile, intent: Intent) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.load_prefs_json(&json!({"colorSettings": {"workingRgb": file.spec(), "intent": intent.id()}}).to_string()).unwrap();
|
||||
assert_eq!(s.color.settings.working_rgb, file.spec(), "legacy preferences still load");
|
||||
s
|
||||
}
|
||||
|
||||
fn display_and_copy(s: &mut Session, depth: SampleType) {
|
||||
let target = s.active().unwrap().doc.clone();
|
||||
let display = s.color.display_transform(&target).expect("the destination document must also be a readable display source");
|
||||
let mut displayed = [0.0; 3];
|
||||
display.eval(&[0.35, 0.65, 0.45], &mut displayed);
|
||||
assert!(displayed.iter().all(|v| v.is_finite()));
|
||||
let mut source = Document::new("Copy source", Size::new(8, 6), ColorMode::Rgb, SampleType::F32);
|
||||
source.icc_profile = Some(Builtin::AdobeRgbCompat.profile().to_bytes());
|
||||
let mut layer = Layer::raster("Incoming", source.pixel_format());
|
||||
layer.surface_mut().unwrap().fill_rect(source.bounds(), &[0.35, 0.65, 0.45, 0.75]);
|
||||
source.layers.push(layer);
|
||||
s.add_document(source, None);
|
||||
let source_before = s.documents()[1].doc.clone();
|
||||
s.execute("layer.copyToDocument", json!({"document": 0})).expect("an untagged or new document must accept a converted layer");
|
||||
assert_eq!(s.documents()[0].doc.depth, depth);
|
||||
assert_eq!(s.documents()[0].doc.layers.len(), target.layers.len() + 1);
|
||||
assert!(s.documents()[1].doc.as_ref() == source_before.as_ref());
|
||||
assert!(s.undo());
|
||||
assert!(s.active().unwrap().doc.as_ref() == target.as_ref());
|
||||
}
|
||||
|
||||
fn legacy_untagged_workflow(source: bool, destination: bool) {
|
||||
let file = ProfileFile::new(directional_profile(source, destination));
|
||||
for intent in Intent::ALL {
|
||||
for depth in SampleType::ALL {
|
||||
let mut s = legacy_session(&file, intent);
|
||||
let doc = Document::with_background("Untagged image", Size::new(8, 6), ColorMode::Rgb, depth, Color::rgba(0.35, 0.65, 0.45, 0.75));
|
||||
assert!(doc.icc_profile.is_none());
|
||||
s.open_document(doc, None);
|
||||
display_and_copy(&mut s, depth);
|
||||
assert_eq!(s.color.working(ColorMode::Rgb).content_hash(), Builtin::Srgb.profile().content_hash());
|
||||
assert!(s.documents()[0].doc.icc_profile.is_none(), "the default working fallback keeps untagged documents untagged");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_source_only_working_rgb_keeps_untagged_display_and_copy_usable() {
|
||||
legacy_untagged_workflow(true, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_destination_only_working_rgb_keeps_untagged_display_and_copy_usable() {
|
||||
legacy_untagged_workflow(false, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_one_way_working_spaces_keep_new_document_controls_usable() {
|
||||
for (source, destination) in [(true, false), (false, true)] {
|
||||
let file = ProfileFile::new(directional_profile(source, destination));
|
||||
for intent in Intent::ALL {
|
||||
for depth in SampleType::ALL {
|
||||
let mut s = legacy_session(&file, intent);
|
||||
let bits = match depth {
|
||||
SampleType::U8 => 8,
|
||||
SampleType::U16 => 16,
|
||||
SampleType::F32 => 32,
|
||||
};
|
||||
s.execute("file.new", json!({"width": 8, "height": 6, "depth": bits, "background": "transparent"})).unwrap();
|
||||
display_and_copy(&mut s, depth);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_input_matrix_and_lut_working_profiles_use_the_configured_intent() {
|
||||
let mut matrix = Builtin::DisplayP3.profile().clone();
|
||||
matrix.class = ProfileClass::Input;
|
||||
let mut colorimetric_lut = directional_profile(true, true);
|
||||
colorimetric_lut.b2a[0] = None;
|
||||
colorimetric_lut.b2a[2] = None;
|
||||
for (profile, colorimetric_only) in [(matrix, false), (directional_profile(true, true), false), (colorimetric_lut, true)] {
|
||||
let file = ProfileFile::new(profile);
|
||||
for intent in Intent::ALL {
|
||||
let supported = !colorimetric_only || matches!(intent, Intent::RelativeColorimetric | Intent::AbsoluteColorimetric);
|
||||
let mut s = Session::new();
|
||||
let before = s.color.settings.clone();
|
||||
let result = s.execute("edit.colorSettings", json!({"workingRgb": file.spec(), "intent": intent.id()}));
|
||||
assert_eq!(result.is_ok(), supported, "{intent:?}/colorimetric_only={colorimetric_only}");
|
||||
if !supported {
|
||||
assert_eq!(s.color.settings, before);
|
||||
}
|
||||
let s = legacy_session(&file, intent);
|
||||
let expected = if supported { &file.profile } else { Builtin::Srgb.profile() };
|
||||
assert_eq!(s.color.working(ColorMode::Rgb).content_hash(), expected.content_hash());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn intent_lut(intent: Intent) -> ProfileFile {
|
||||
let mut profile = directional_profile(true, true);
|
||||
let i = match intent {
|
||||
Intent::Perceptual => 0,
|
||||
Intent::RelativeColorimetric | Intent::AbsoluteColorimetric => 1,
|
||||
Intent::Saturation => 2,
|
||||
};
|
||||
for (index, lut) in profile.b2a.iter_mut().enumerate() {
|
||||
if index != i {
|
||||
*lut = None;
|
||||
}
|
||||
}
|
||||
ProfileFile::new(profile)
|
||||
}
|
||||
|
||||
fn colorimetric_session(file: &ProfileFile) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": file.spec(), "intent": "relative"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_cross_field_profile_and_intent_changes_validate_the_final_batch() {
|
||||
let file = intent_lut(Intent::RelativeColorimetric);
|
||||
let cases = [
|
||||
("edit.colorSettings", json!({"workingRgb": "display-p3", "intent": "perceptual"})),
|
||||
("prefs.set", json!({"values": {"colorSettings.intent": "perceptual", "colorSettings.workingRgb": "display-p3"}})),
|
||||
(
|
||||
"prefs.set",
|
||||
json!({"path": "colorSettings", "value": {"workingRgb": file.spec(), "intent": "perceptual"}, "values": {"colorSettings.workingRgb": "display-p3"}}),
|
||||
),
|
||||
(
|
||||
"prefs.set",
|
||||
json!({"path": "", "value": {"colorSettings": {"workingRgb": file.spec(), "intent": "perceptual"}}, "values": {"colorSettings.workingRgb": "display-p3"}}),
|
||||
),
|
||||
];
|
||||
for (command, params) in cases {
|
||||
let mut s = colorimetric_session(&file);
|
||||
s.execute(command, params.clone()).unwrap_or_else(|e| panic!("final valid batch must succeed: {command}/{params}: {e}"));
|
||||
assert_eq!(s.color.settings.working_rgb, "display-p3");
|
||||
assert_eq!(s.color.settings.intent, "perceptual");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_batches_restore_colour_and_unrelated_preferences_for_both_apis() {
|
||||
let working = intent_lut(Intent::RelativeColorimetric);
|
||||
let invalid = ProfileFile::new(directional_profile(true, false));
|
||||
let cases = [
|
||||
("edit.colorSettings", json!({"workingRgb": invalid.spec(), "intent": "perceptual", "bpc": false})),
|
||||
(
|
||||
"prefs.set",
|
||||
json!({"values": {"colorSettings.bpc": false, "colorSettings.intent": "perceptual", "colorSettings.workingRgb": invalid.spec(), "performance.historyStates": 17}}),
|
||||
),
|
||||
(
|
||||
"prefs.set",
|
||||
json!({"values": {"colorSettings.bpc": false, "colorSettings.intent": "perceptual", "colorSettings.workingRgb": "display-p3", "performance.historyStates": 0}}),
|
||||
),
|
||||
];
|
||||
for (command, params) in cases {
|
||||
let mut s = colorimetric_session(&working);
|
||||
let before = s.prefs_to_json();
|
||||
assert!(s.execute(command, params).is_err());
|
||||
assert!(s.prefs_to_json() == before, "failed batch must preserve both preference stores");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incompatible_single_intent_reset_preserves_the_original_colour_settings() {
|
||||
let file = intent_lut(Intent::Saturation);
|
||||
let mut s = Session::new();
|
||||
s.execute("edit.colorSettings", json!({"workingRgb": file.spec(), "intent": "saturation"})).unwrap();
|
||||
let before = s.prefs_to_json();
|
||||
assert!(s.execute("prefs.reset", json!({"path": "colorSettings.intent"})).is_err());
|
||||
assert!(s.prefs_to_json() == before, "single-setting reset must validate before assignment");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_preference_batches_still_work_with_legacy_invalid_colour_settings() {
|
||||
let invalid = ProfileFile::new(directional_profile(true, false));
|
||||
let mut s = legacy_session(&invalid, Intent::RelativeColorimetric);
|
||||
let before = s.color.settings.clone();
|
||||
s.execute("prefs.set", json!({"values": {"cursors.painting": "precise", "performance.historyStates": 17}})).unwrap();
|
||||
assert_eq!(s.color.settings, before);
|
||||
assert_eq!(s.execute("prefs.get", json!({"path": "performance.historyStates"})).unwrap(), json!(17));
|
||||
}
|
||||
+46
-3
@@ -510,6 +510,31 @@ fn grid_rects(r: Rect, step: u32) -> Vec<Rect> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Number of rectangles `grid_rects` would produce, without allocating them during preflight.
|
||||
fn grid_rect_count(r: Rect, step: u32) -> Result<usize, Unsupported> {
|
||||
if r.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let s = i64::from(step.max(1));
|
||||
let axis = |lo: i32, hi: i32| usize::try_from((i64::from(hi) - 1).div_euclid(s) - i64::from(lo).div_euclid(s) + 1).ok();
|
||||
axis(r.x0, r.x1).and_then(|x| axis(r.y0, r.y1).and_then(|y| x.checked_mul(y))).ok_or_else(|| Unsupported("GPU compositor chunk count is too large".into()))
|
||||
}
|
||||
|
||||
/// Host length and GPU capacity for the chunk/pass uniform records, including their u32
|
||||
/// dynamic binding offsets. Decline unsupported stacks before an invalid buffer faults the device.
|
||||
fn uniform_buffer_len(chunks: usize, passes: usize, limit: u64) -> Result<usize, Unsupported> {
|
||||
let too_large = || Unsupported("GPU compositor uniform buffer is too large".into());
|
||||
let records = chunks.checked_add(passes).and_then(|n| u64::try_from(n).ok()).ok_or_else(too_large)?;
|
||||
let bytes = records.checked_mul(STRIDE).ok_or_else(too_large)?;
|
||||
if bytes > limit {
|
||||
return Err(Unsupported(format!("GPU compositor uniform buffer requires {bytes} bytes; device limit is {limit}")));
|
||||
}
|
||||
if bytes.saturating_sub(STRIDE) > u64::from(u32::MAX) {
|
||||
return Err(Unsupported("GPU compositor uniform offsets exceed u32".into()));
|
||||
}
|
||||
usize::try_from(bytes).map_err(|_| too_large())
|
||||
}
|
||||
|
||||
/// The reach up to which each distance field must be exact (the largest any program asks for).
|
||||
fn field_reaches(progs: &[fx::MapProgram]) -> HashMap<FieldKind, i32> {
|
||||
let mut want: HashMap<FieldKind, i32> = HashMap::new();
|
||||
@@ -915,6 +940,14 @@ impl Compositor {
|
||||
if region.is_empty() {
|
||||
return Ok(stats);
|
||||
}
|
||||
let page = self.page;
|
||||
let mut cells = grid_rects(region, page);
|
||||
// Check every actual page cell before uploads, submissions or sink output. A later
|
||||
// cell can need more chunk records than the first; a failure must leave the device healthy.
|
||||
let buffer_limit = device.limits().max_buffer_size;
|
||||
for part in &cells {
|
||||
uniform_buffer_len(grid_rect_count(*part, self.chunk)?, plan.passes.len(), buffer_limit)?;
|
||||
}
|
||||
if self.frame == 0 {
|
||||
// The first submission after device creation is dropped on some drivers (RADV),
|
||||
// which would render the first frame black; land it on an empty buffer instead.
|
||||
@@ -942,8 +975,6 @@ impl Compositor {
|
||||
|
||||
// Page cells; every other frame in reverse, so a repeated full refresh of a document
|
||||
// larger than the budget starts with the pages still resident.
|
||||
let page = self.page;
|
||||
let mut cells = grid_rects(region, page);
|
||||
if self.frame.is_multiple_of(2) {
|
||||
cells.reverse();
|
||||
}
|
||||
@@ -1168,7 +1199,8 @@ impl Compositor {
|
||||
self.pool.push((t, v));
|
||||
}
|
||||
|
||||
// Uniforms: chunk records, then one record per pass.
|
||||
// Uniforms: chunk records, then one record per pass. encode_scoped preflight checked
|
||||
// the length, device capacity and dynamic offsets before any GPU work for this frame.
|
||||
let op_base = chunks.len() as u64 * STRIDE;
|
||||
let mut data = vec![0u8; (op_base + plan.passes.len() as u64 * STRIDE) as usize];
|
||||
for (i, c) in chunks.iter().enumerate() {
|
||||
@@ -2257,6 +2289,17 @@ pub fn render_to_vec_stats(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn uniform_buffer_sizes_are_checked_before_allocation() {
|
||||
assert_eq!(uniform_buffer_len(1, 255, 65_536).unwrap(), 65_536);
|
||||
assert!(uniform_buffer_len(1, 255, 65_535).is_err());
|
||||
assert!(uniform_buffer_len(usize::MAX, 1, u64::MAX).is_err());
|
||||
assert!(uniform_buffer_len(usize::MAX, 0, u64::MAX).is_err());
|
||||
assert!(uniform_buffer_len(1, 16_777_216, u64::MAX).is_err(), "the last record offset cannot be represented by u32");
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
assert_eq!(uniform_buffer_len(1, 16_777_215, u64::MAX).unwrap(), 4_294_967_296, "the last valid u32 dynamic offset is accepted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_roundtrip() {
|
||||
for v in [0.0f32, 1.0, 0.5, 0.25, 1.0 / 255.0, 0.333, 65504.0, -2.5, 1e-6] {
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! A deep stack that cannot fit the device's uniform buffer must fall back without panicking.
|
||||
|
||||
use photocraft_color::{Color, ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, Fill, Layer, LayerContent};
|
||||
use photocraft_geom::Size;
|
||||
use photocraft_gpu::{Compositor, DeviceHealth, plan, render_to_vec};
|
||||
|
||||
static GPU_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn fills(count: usize) -> Document {
|
||||
fills_size(count, Size::new(1, 1))
|
||||
}
|
||||
|
||||
fn fills_size(count: usize, size: Size) -> Document {
|
||||
let mut doc = Document::new("Small deep stack", size, ColorMode::Rgb, SampleType::U8);
|
||||
for _ in 0..count {
|
||||
doc.layers.push(Layer::new("Translucent fill", LayerContent::Fill(Fill::Solid(Color::rgba(0.25, 0.5, 0.75, 0.5)))));
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
fn constrained_device() -> Option<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> {
|
||||
let instance = wgpu::Instance::default();
|
||||
let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) {
|
||||
Ok(adapter) => adapter,
|
||||
Err(error) => {
|
||||
eprintln!("skipping uniform-limit test: no GPU adapter ({error})");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let limits =
|
||||
wgpu::Limits { max_buffer_size: 65_536, max_storage_buffer_binding_size: 65_536, max_uniform_buffer_binding_size: 65_536, ..Default::default() };
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { required_limits: limits, ..Default::default() }))
|
||||
.expect("the supported reduced device limits must create a device");
|
||||
assert_eq!(device.limits().max_buffer_size, 65_536);
|
||||
Some((adapter, device, queue))
|
||||
}
|
||||
|
||||
fn compositor(adapter: &wgpu::Adapter, device: &wgpu::Device) -> Compositor {
|
||||
let mut compositor =
|
||||
Compositor::try_new_with_format(device, Compositor::preferred_acc_format(adapter)).expect("the reduced-limit device supports the compositor");
|
||||
compositor.set_texture_limit(256);
|
||||
compositor
|
||||
}
|
||||
|
||||
fn healthy_control(compositor: &mut Compositor, device: &wgpu::Device, queue: &wgpu::Queue) {
|
||||
let small = fills(2);
|
||||
let expected = photocraft_compose::flatten(&small);
|
||||
let actual = render_to_vec(compositor, device, queue, &small, small.bounds()).expect("a fitting stack renders on the same device");
|
||||
assert_eq!(actual.len(), 1);
|
||||
for (cpu, gpu) in expected.px[0].iter().zip(actual[0]) {
|
||||
assert!((cpu - gpu).abs() <= 1.0 / 255.0, "the healthy small-stack CPU control differs: {cpu} vs {gpu}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deep_stack_above_the_device_buffer_limit_returns_an_error_without_panicking() {
|
||||
let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some((adapter, device, queue)) = constrained_device() else { return };
|
||||
let mut compositor = compositor(&adapter, &device);
|
||||
healthy_control(&mut compositor, &device, &queue);
|
||||
let deep = fills(150);
|
||||
eprintln!(
|
||||
"uniform-limit reproduction: backend={:?}, buffer limit={}, page={}, passes={}",
|
||||
adapter.get_info().backend,
|
||||
device.limits().max_buffer_size,
|
||||
compositor.page_size(),
|
||||
plan(&deep).unwrap().passes.len()
|
||||
);
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render_to_vec(&mut compositor, &device, &queue, &deep, deep.bounds())));
|
||||
assert!(result.is_ok(), "rendering an oversized uniform buffer must return Unsupported, not panic");
|
||||
assert!(result.unwrap().is_err(), "a stack above the device's buffer limit must return Unsupported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_stack_falls_back_without_faulting_the_watched_device() {
|
||||
let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some((adapter, device, queue)) = constrained_device() else { return };
|
||||
let health = DeviceHealth::watch(&device);
|
||||
let mut compositor = compositor(&adapter, &device);
|
||||
compositor.set_health(health.clone());
|
||||
healthy_control(&mut compositor, &device, &queue);
|
||||
let deep = fills(150);
|
||||
let fallback = match render_to_vec(&mut compositor, &device, &queue, &deep, deep.bounds()) {
|
||||
Ok(_) => panic!("the oversized stack must return Unsupported for CPU fallback"),
|
||||
Err(_) => photocraft_compose::flatten(&deep),
|
||||
};
|
||||
for (actual, expected) in fallback.px[0].iter().zip([0.25, 0.5, 0.75, 1.0]) {
|
||||
assert!((actual - expected).abs() <= 1.0 / 255.0, "CPU fallback preserves the translucent-fill composite: {actual} vs {expected}");
|
||||
}
|
||||
let small = fills(2);
|
||||
let next = render_to_vec(&mut compositor, &device, &queue, &small, small.bounds());
|
||||
eprintln!("watched uniform-limit reproduction: errors={}, fault={:?}", health.errors(), health.fault());
|
||||
eprintln!("next fitting stack after fallback: {next:?}");
|
||||
assert!(health.is_ok(), "the unsupported stack must leave the device healthy: {:?}", health.fault());
|
||||
assert_eq!(health.errors(), 0, "no invalid GPU operation is issued before falling back");
|
||||
healthy_control(&mut compositor, &device, &queue);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exact_buffer_limit_still_renders_with_cpu_parity() {
|
||||
let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some((adapter, device, queue)) = constrained_device() else { return };
|
||||
let health = DeviceHealth::watch(&device);
|
||||
let mut compositor = compositor(&adapter, &device);
|
||||
compositor.set_health(health.clone());
|
||||
let boundary = fills(127);
|
||||
assert_eq!(plan(&boundary).unwrap().passes.len(), 255, "one chunk plus255passes uses exactly65536bytes");
|
||||
let expected = photocraft_compose::flatten(&boundary);
|
||||
let actual = render_to_vec(&mut compositor, &device, &queue, &boundary, boundary.bounds()).expect("the exact supported buffer boundary is accepted");
|
||||
assert_eq!(actual.len(), 1);
|
||||
for (cpu, gpu) in expected.px[0].iter().zip(actual[0]) {
|
||||
assert!((cpu - gpu).abs() <= 1.0 / 255.0, "the boundary render differs from CPU: {cpu} vs {gpu}");
|
||||
}
|
||||
assert_eq!(health.errors(), 0);
|
||||
assert!(health.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_oversized_page_cells_are_rejected_before_render_or_encode_calls_the_sink() {
|
||||
let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some((adapter, device, queue)) = constrained_device() else { return };
|
||||
let health = DeviceHealth::watch(&device);
|
||||
let doc = fills_size(126, Size::new(4096, 2048));
|
||||
let region = photocraft_geom::Rect::new(2047, 0, 4096, 2048);
|
||||
assert_eq!(plan(&doc).unwrap().passes.len(), 253);
|
||||
// Default pages are2048, chunks1024: the narrow first page has2chunks and fits;
|
||||
// the later full page has4chunks and would exceed the same65536byte device limit.
|
||||
for encode_only in [false, true] {
|
||||
let mut compositor = Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter)).unwrap();
|
||||
compositor.set_health(health.clone());
|
||||
assert_eq!(compositor.page_size(), 2048);
|
||||
let mut calls = 0;
|
||||
let mut sink = |_: &mut wgpu::CommandEncoder, _: photocraft_gpu::ChunkOut<'_>| calls += 1;
|
||||
let result = if encode_only {
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
compositor.encode(&device, &queue, &mut encoder, &doc, region, &mut sink)
|
||||
} else {
|
||||
compositor.render(&device, &queue, &doc, region, &mut sink)
|
||||
};
|
||||
assert!(result.is_err(), "a later cell's uniform requirement must trigger CPU fallback");
|
||||
assert_eq!(calls, 0, "preflight must reject the whole render before any partial sink output");
|
||||
assert_eq!(health.errors(), 0);
|
||||
assert!(health.is_ok());
|
||||
}
|
||||
}
|
||||
@@ -109,6 +109,7 @@ testgen::{all_cases, merged_only, layered, small, sample_descriptor, pattern_pla
|
||||
| RGBA8 extraction | ✓ | – | – | RGB / gray / CMYK layers; merged image also supports indexed / bitmap / duotone |
|
||||
| Builder | – | ✓ | – | RGB / gray / CMYK at 8/16 bit, masks, groups, blend modes, opacity, fill, visibility, clipping |
|
||||
| Patterns | ✓ | ✓ | ✓ | `Patt` / `Pat2` / `Pat3`, `.pat`, and `.abr` embedded patterns; non-empty tiles allow in-bounds channel subrectangles, decoded size is capped and PackBits expansion is input-bounded |
|
||||
| Actions (`.atn`) | ✓ | ✓ | ✓ | `atn::parse` / `atn::write`: version-16 sets (Photoshop 6+): actions with function key, modifiers and colour; steps with event code or string name, panel name, enabled/dialog flags and their descriptor. Exact round trip; version-12 (Photoshop 5) files are rejected as unsupported |
|
||||
|
||||
Pattern channel subrectangles are padded with zeroes to the tile rectangle. All channel
|
||||
metadata and the total padded size are checked against `MAX_DECODED_BYTES` before any
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//! Print the actions and steps of `.atn` files, one event per line, with the top-level keys of
|
||||
//! each step's descriptor: `cargo run -p photocraft-psd --example atn_dump -- set.atn…`
|
||||
//!
|
||||
//! Handy when adding a Photoshop event to the engine's `.atn` import table: it shows the event
|
||||
//! id, the panel name and the parameter keys Photoshop recorded.
|
||||
|
||||
use photocraft_psd::atn;
|
||||
use photocraft_psd::descriptor::{Descriptor, ReferenceItem, Value};
|
||||
|
||||
fn summary(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Integer(i) => i.to_string(),
|
||||
Value::Double(d) => format!("{d}"),
|
||||
Value::UnitFloat { unit, value } => format!("{value}{}", String::from_utf8_lossy(unit)),
|
||||
Value::Boolean(b) => b.to_string(),
|
||||
Value::Text(t) => format!("{:?}", t.to_string_lossy()),
|
||||
Value::Enumerated { type_id, value } => format!("{}.{}", String::from_utf8_lossy(type_id.as_bytes()), String::from_utf8_lossy(value.as_bytes())),
|
||||
Value::Descriptor(d) | Value::GlobalObject(d) => format!("{{{}}}", keys(d)),
|
||||
Value::List(l) => format!("[{}]", l.iter().map(summary).collect::<Vec<_>>().join(", ")),
|
||||
Value::Reference(r) => format!("ref[{}]", r.iter().map(reference).collect::<Vec<_>>().join(" ")),
|
||||
other => format!("{other:?}").chars().take(40).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn id(i: &photocraft_psd::descriptor::Id) -> String {
|
||||
String::from_utf8_lossy(i.as_bytes()).trim().to_string()
|
||||
}
|
||||
|
||||
fn reference(item: &ReferenceItem) -> String {
|
||||
match item {
|
||||
ReferenceItem::Property { class, key } => format!("prop({},{})", id(&class.class_id), id(key)),
|
||||
ReferenceItem::Class(c) => format!("Clss({})", id(&c.class_id)),
|
||||
ReferenceItem::Enumerated { class, type_id, value } => format!("Enmr({},{}.{})", id(&class.class_id), id(type_id), id(value)),
|
||||
ReferenceItem::Offset { class, offset } => format!("rele({},{offset})", id(&class.class_id)),
|
||||
ReferenceItem::Identifier { class, id: v } => format!("Idnt({},{v})", id(&class.class_id)),
|
||||
ReferenceItem::Index { class, index } => format!("indx({},{index})", id(&class.class_id)),
|
||||
ReferenceItem::Name { class, name } => format!("name({},{:?})", id(&class.class_id), name.to_string_lossy()),
|
||||
}
|
||||
}
|
||||
|
||||
fn keys(d: &Descriptor) -> String {
|
||||
d.items.iter().map(|(k, v)| format!("{}={}", String::from_utf8_lossy(k.as_bytes()), summary(v))).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut failed = false;
|
||||
for path in std::env::args().skip(1) {
|
||||
let bytes = match std::fs::read(&path) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
eprintln!("{path}: {e}");
|
||||
failed = true;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match atn::parse(&bytes) {
|
||||
Ok(f) => {
|
||||
println!(
|
||||
"== {path}: set {:?}, {} actions{}",
|
||||
f.name.to_string_lossy(),
|
||||
f.actions.len(),
|
||||
if f.warnings.is_empty() { String::new() } else { format!(" ({})", f.warnings.join("; ")) }
|
||||
);
|
||||
for a in &f.actions {
|
||||
println!(" action {:?} ({} steps)", a.name.to_string_lossy(), a.items.len());
|
||||
for item in &a.items {
|
||||
let flags = format!("{}{}", if item.enabled { "" } else { " off" }, if item.with_dialog { " dialog" } else { "" });
|
||||
match &item.descriptor {
|
||||
Some(d) => println!(" {:<22} {:<28}{flags} {}", item.event.id(), item.dictionary, keys(d)),
|
||||
None => println!(" {:<22} {:<28}{flags}", item.event.id(), item.dictionary),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("== {path}: {e}");
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if failed {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -98,3 +98,10 @@ path = "fuzz_targets/resources.rs"
|
||||
test = false
|
||||
doc = false
|
||||
bench = false
|
||||
|
||||
[[bin]]
|
||||
name = "atn"
|
||||
path = "fuzz_targets/atn.rs"
|
||||
test = false
|
||||
doc = false
|
||||
bench = false
|
||||
@@ -0,0 +1,14 @@
|
||||
//! Fuzz the `.atn` actions parser: any input must return `Ok` or `Err`, never panic, and
|
||||
//! anything that parses must survive a write and parse back equal.
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
use photocraft_psd::atn;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
if let Ok(f) = atn::parse(data) {
|
||||
let bytes = atn::write(&f).expect("a parsed set is writable");
|
||||
let again = atn::parse(&bytes).expect("a written set parses");
|
||||
assert_eq!(again.actions, f.actions);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,426 @@
|
||||
//! Photoshop Actions files (`.atn`): one action set, its actions and their steps.
|
||||
//!
|
||||
//! Implemented clean-room from Adobe's "Photoshop File Formats" specification (the *Actions*
|
||||
//! and *Descriptor structure* sections) and observation of files Photoshop writes. No code was
|
||||
//! copied. All numbers are big-endian; strings are the Unicode strings of descriptors (u32
|
||||
//! code-unit count + UTF-16BE, usually NUL-terminated) unless noted.
|
||||
//!
|
||||
//! ```text
|
||||
//! file := version u32 (16), set name UnicodeString, expanded u8, count u32, count × action
|
||||
//! action := function key u16 (0 = none, n = Fn), shift u8, command u8, colour u16,
|
||||
//! name UnicodeString, expanded u8, count u32, count × item
|
||||
//! item := expanded u8, enabled u8, with dialog u8, dialog options u8,
|
||||
//! event kind [4]: "TEXT" (u32 length + ASCII event name) | "long" (4-char event code),
|
||||
//! dictionary name (u32 length + ASCII: the name the Actions panel shows),
|
||||
//! has descriptor i32 (-1 = a descriptor follows, 0 = none), [descriptor]
|
||||
//! ```
|
||||
//!
|
||||
//! The descriptor is a plain ActionDescriptor body ([`Descriptor`], no version prefix): the
|
||||
//! event's parameters, exactly as Photoshop's own "Make", "Set", "Gaussian Blur"… events
|
||||
//! carry them. Photoshop 5-era files (version 12) use a different, undocumented layout and are
|
||||
//! rejected as unsupported.
|
||||
//!
|
||||
//! [`parse`] never panics: every count is bounds-checked against the bytes left, descriptor
|
||||
//! nesting is bounded, and allocations are capped. [`write`] produces the same layout, so
|
||||
//! `parse(write(f)) == f`, and `write(parse(b)) == b` for files Photoshop wrote.
|
||||
|
||||
use crate::descriptor::{Descriptor, UnicodeString};
|
||||
use crate::error::{PsdError, Result};
|
||||
use crate::io::{Reader, WriteExt};
|
||||
|
||||
/// The only version this module reads and writes (Photoshop 6 and every later release).
|
||||
pub const VERSION: u32 = 16;
|
||||
/// Most actions read from one set (Photoshop's own sets hold a few dozen).
|
||||
pub const MAX_ACTIONS: usize = 10_000;
|
||||
/// Most steps read from one action.
|
||||
pub const MAX_ITEMS: usize = 100_000;
|
||||
|
||||
/// A parsed action set.
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct AtnFile {
|
||||
/// The set's name (the Actions panel folder).
|
||||
pub name: UnicodeString,
|
||||
/// Whether the set is shown expanded in the Actions panel.
|
||||
pub expanded: bool,
|
||||
/// The actions, in panel order.
|
||||
pub actions: Vec<AtnAction>,
|
||||
/// Problems that did not stop the parse (trailing bytes…).
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// One action of a set.
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct AtnAction {
|
||||
/// Function key that plays the action: 0 = none, `n` = F`n`.
|
||||
pub function_key: u16,
|
||||
/// Shift modifier of the function key.
|
||||
pub shift: bool,
|
||||
/// Command (Control on Windows) modifier of the function key.
|
||||
pub command: bool,
|
||||
/// Button Mode colour index (0 = none, then red, orange, yellow, green, blue, violet, gray).
|
||||
pub color: u16,
|
||||
/// The action's name.
|
||||
pub name: UnicodeString,
|
||||
/// Whether the action is shown expanded in the Actions panel.
|
||||
pub expanded: bool,
|
||||
/// The steps, in playback order.
|
||||
pub items: Vec<AtnItem>,
|
||||
}
|
||||
|
||||
/// One step of an action: a Photoshop event with its parameters.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct AtnItem {
|
||||
/// Whether the step's parameters are shown expanded in the Actions panel.
|
||||
pub expanded: bool,
|
||||
/// The panel's check mark: a switched-off step is skipped by playback.
|
||||
pub enabled: bool,
|
||||
/// The panel's dialog toggle: playback shows the step's dialog.
|
||||
pub with_dialog: bool,
|
||||
/// Dialog options (0 = none, 2 = show the dialog, 3 = don't show), kept verbatim.
|
||||
pub dialog_options: u8,
|
||||
/// The event.
|
||||
pub event: AtnEvent,
|
||||
/// The name the Actions panel shows for the step ("Gaussian Blur", "Make", …).
|
||||
pub dictionary: String,
|
||||
/// The event's parameters; `None` for events without any.
|
||||
pub descriptor: Option<Descriptor>,
|
||||
}
|
||||
|
||||
impl Default for AtnItem {
|
||||
fn default() -> Self {
|
||||
AtnItem {
|
||||
expanded: false,
|
||||
enabled: true,
|
||||
with_dialog: false,
|
||||
dialog_options: 0,
|
||||
event: AtnEvent::Code(*b" "),
|
||||
dictionary: String::new(),
|
||||
descriptor: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Photoshop event id: a four-character code (`GsnB`) or a string name (`trim`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum AtnEvent {
|
||||
/// Stored as `long` + 4 bytes.
|
||||
Code([u8; 4]),
|
||||
/// Stored as `TEXT` + length-prefixed ASCII.
|
||||
Name(String),
|
||||
}
|
||||
|
||||
impl AtnEvent {
|
||||
/// The event id as text: the code's four characters, or the name.
|
||||
pub fn id(&self) -> String {
|
||||
match self {
|
||||
AtnEvent::Code(c) => String::from_utf8_lossy(c).into_owned(),
|
||||
AtnEvent::Name(n) => n.clone(),
|
||||
}
|
||||
}
|
||||
/// `true` if the event is the code or name `s`.
|
||||
pub fn is(&self, s: &str) -> bool {
|
||||
match self {
|
||||
AtnEvent::Code(c) => c == s.as_bytes(),
|
||||
AtnEvent::Name(n) => n == s,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a u32 length + ASCII bytes (event and dictionary names).
|
||||
fn read_ascii(r: &mut Reader<'_>) -> Result<String> {
|
||||
let n = r.u32()?;
|
||||
Ok(String::from_utf8_lossy(r.bytes_u64(u64::from(n))?).into_owned())
|
||||
}
|
||||
|
||||
fn write_ascii(out: &mut Vec<u8>, s: &str) -> Result<()> {
|
||||
let n = u32::try_from(s.len()).map_err(|_| PsdError::LimitExceeded("action name too long"))?;
|
||||
out.put_u32(n);
|
||||
out.put(s.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_item(r: &mut Reader<'_>) -> Result<AtnItem> {
|
||||
let expanded = r.u8()? != 0;
|
||||
let enabled = r.u8()? != 0;
|
||||
let with_dialog = r.u8()? != 0;
|
||||
let dialog_options = r.u8()?;
|
||||
let event = match &r.array::<4>()? {
|
||||
b"TEXT" => AtnEvent::Name(read_ascii(r)?),
|
||||
b"long" => AtnEvent::Code(r.array()?),
|
||||
other => return Err(PsdError::invalid(format!("unknown event kind {:?}", String::from_utf8_lossy(other)))),
|
||||
};
|
||||
let dictionary = read_ascii(r)?;
|
||||
let descriptor = match r.i32()? {
|
||||
0 => None,
|
||||
-1 => Some(Descriptor::read(r)?),
|
||||
n => return Err(PsdError::invalid(format!("bad descriptor flag {n}"))),
|
||||
};
|
||||
Ok(AtnItem { expanded, enabled, with_dialog, dialog_options, event, dictionary, descriptor })
|
||||
}
|
||||
|
||||
fn read_action(r: &mut Reader<'_>) -> Result<AtnAction> {
|
||||
let function_key = r.u16()?;
|
||||
let shift = r.u8()? != 0;
|
||||
let command = r.u8()? != 0;
|
||||
let color = r.u16()?;
|
||||
let name = UnicodeString::read(r)?;
|
||||
let expanded = r.u8()? != 0;
|
||||
let n = r.u32()?;
|
||||
// Each item needs at least its 4 flags, the event kind, two empty names and the descriptor flag.
|
||||
r.check_count(u64::from(n), 20)?;
|
||||
if n as usize > MAX_ITEMS {
|
||||
return Err(PsdError::LimitExceeded("too many steps in one action"));
|
||||
}
|
||||
let mut items = Vec::with_capacity((n as usize).min(1024));
|
||||
for _ in 0..n {
|
||||
items.push(read_item(r)?);
|
||||
}
|
||||
Ok(AtnAction { function_key, shift, command, color, name, expanded, items })
|
||||
}
|
||||
|
||||
/// Parses an `.atn` file.
|
||||
pub fn parse(data: &[u8]) -> Result<AtnFile> {
|
||||
let mut r = Reader::new(data);
|
||||
let version = r.u32()?;
|
||||
if version != VERSION {
|
||||
return Err(PsdError::Unsupported(format!("actions file version {version} (only version 16, Photoshop 6 and later, is supported)")));
|
||||
}
|
||||
let name = UnicodeString::read(&mut r)?;
|
||||
let expanded = r.u8()? != 0;
|
||||
let n = r.u32()?;
|
||||
// Each action needs at least its key, modifiers, colour, an empty name, the flag and a count.
|
||||
r.check_count(u64::from(n), 15)?;
|
||||
if n as usize > MAX_ACTIONS {
|
||||
return Err(PsdError::LimitExceeded("too many actions in one set"));
|
||||
}
|
||||
let mut actions = Vec::with_capacity((n as usize).min(256));
|
||||
for _ in 0..n {
|
||||
actions.push(read_action(&mut r)?);
|
||||
}
|
||||
let mut warnings = Vec::new();
|
||||
if !r.is_empty() {
|
||||
warnings.push(format!("{} trailing bytes ignored", r.remaining()));
|
||||
}
|
||||
Ok(AtnFile { name, expanded, actions, warnings })
|
||||
}
|
||||
|
||||
fn write_item(out: &mut Vec<u8>, item: &AtnItem) -> Result<()> {
|
||||
out.put_u8(u8::from(item.expanded));
|
||||
out.put_u8(u8::from(item.enabled));
|
||||
out.put_u8(u8::from(item.with_dialog));
|
||||
out.put_u8(item.dialog_options);
|
||||
match &item.event {
|
||||
AtnEvent::Name(n) => {
|
||||
out.put(b"TEXT");
|
||||
write_ascii(out, n)?;
|
||||
}
|
||||
AtnEvent::Code(c) => {
|
||||
out.put(b"long");
|
||||
out.put(c);
|
||||
}
|
||||
}
|
||||
write_ascii(out, &item.dictionary)?;
|
||||
match &item.descriptor {
|
||||
None => out.put_i32(0),
|
||||
Some(d) => {
|
||||
out.put_i32(-1);
|
||||
d.write(out);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn count(n: usize, what: &'static str) -> Result<u32> {
|
||||
u32::try_from(n).map_err(|_| PsdError::LimitExceeded(what))
|
||||
}
|
||||
|
||||
/// Writes an `.atn` file (version 16).
|
||||
pub fn write(f: &AtnFile) -> Result<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
out.put_u32(VERSION);
|
||||
f.name.write(&mut out);
|
||||
out.put_u8(u8::from(f.expanded));
|
||||
out.put_u32(count(f.actions.len(), "too many actions")?);
|
||||
for a in &f.actions {
|
||||
out.put_u16(a.function_key);
|
||||
out.put_u8(u8::from(a.shift));
|
||||
out.put_u8(u8::from(a.command));
|
||||
out.put_u16(a.color);
|
||||
a.name.write(&mut out);
|
||||
out.put_u8(u8::from(a.expanded));
|
||||
out.put_u32(count(a.items.len(), "too many steps")?);
|
||||
for item in &a.items {
|
||||
write_item(&mut out, item)?;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::descriptor::Value;
|
||||
|
||||
fn px(v: f64) -> Value {
|
||||
Value::UnitFloat { unit: *b"#Pxl", value: v }
|
||||
}
|
||||
|
||||
fn set() -> AtnFile {
|
||||
let blur = AtnItem {
|
||||
expanded: true,
|
||||
enabled: true,
|
||||
with_dialog: true,
|
||||
dialog_options: 2,
|
||||
event: AtnEvent::Code(*b"GsnB"),
|
||||
dictionary: "Gaussian Blur".into(),
|
||||
descriptor: Some(Descriptor::new("null").with("Rds ", px(2.5))),
|
||||
};
|
||||
let trim = AtnItem {
|
||||
event: AtnEvent::Name("trim".into()),
|
||||
dictionary: "Trim".into(),
|
||||
descriptor: Some(
|
||||
Descriptor { name: UnicodeString::new_nul("Trim"), class_id: crate::descriptor::Id::Str(b"trim".to_vec()), items: Vec::new() }
|
||||
.with(
|
||||
"trimBasedOn",
|
||||
Value::Enumerated { type_id: crate::descriptor::Id::new("trimBasedOn"), value: crate::descriptor::Id::new("topLeftPixelColor") },
|
||||
)
|
||||
.with("Top ", Value::Boolean(true)),
|
||||
),
|
||||
..Default::default()
|
||||
};
|
||||
let flatten = AtnItem { enabled: false, event: AtnEvent::Code(*b"Fltn"), dictionary: "Flatten Image".into(), ..Default::default() };
|
||||
AtnFile {
|
||||
name: UnicodeString::new_nul("Set ✓"),
|
||||
expanded: true,
|
||||
actions: vec![
|
||||
AtnAction {
|
||||
function_key: 2,
|
||||
shift: true,
|
||||
command: false,
|
||||
color: 3,
|
||||
name: UnicodeString::new_nul("Soften"),
|
||||
expanded: true,
|
||||
items: vec![blur, flatten],
|
||||
},
|
||||
AtnAction { name: UnicodeString::new_nul("Tidy"), items: vec![trim], ..Default::default() },
|
||||
AtnAction { name: UnicodeString::new_nul("Empty"), ..Default::default() },
|
||||
],
|
||||
warnings: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip() {
|
||||
let f = set();
|
||||
let bytes = write(&f).unwrap();
|
||||
let parsed = parse(&bytes).unwrap();
|
||||
assert_eq!(parsed, f);
|
||||
assert_eq!(write(&parsed).unwrap(), bytes, "writing is stable");
|
||||
assert_eq!(parsed.actions[0].items[0].event.id(), "GsnB");
|
||||
assert!(parsed.actions[1].items[0].event.is("trim"));
|
||||
assert_eq!(parsed.actions[1].items[0].event.id(), "trim");
|
||||
}
|
||||
|
||||
/// The layout Photoshop writes for a one-step Trim action, assembled by hand from the
|
||||
/// format description: field by field, so a mistake names the field.
|
||||
#[test]
|
||||
fn layout_matches_the_specification() {
|
||||
let f = AtnFile {
|
||||
name: UnicodeString::new_nul("Trim"),
|
||||
expanded: false,
|
||||
actions: vec![AtnAction {
|
||||
name: UnicodeString::new_nul("Action 1"),
|
||||
expanded: true,
|
||||
items: vec![AtnItem {
|
||||
expanded: true,
|
||||
event: AtnEvent::Name("trim".into()),
|
||||
dictionary: "Trim".into(),
|
||||
descriptor: Some(Descriptor {
|
||||
name: UnicodeString::new_nul("Trim"),
|
||||
class_id: crate::descriptor::Id::Str(b"trim".to_vec()),
|
||||
items: Vec::new(),
|
||||
}),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}],
|
||||
warnings: Vec::new(),
|
||||
};
|
||||
let mut expect = Vec::new();
|
||||
expect.extend_from_slice(&[0, 0, 0, 16]); // version
|
||||
expect.extend_from_slice(&[0, 0, 0, 5, 0, b'T', 0, b'r', 0, b'i', 0, b'm', 0, 0]); // set name
|
||||
expect.push(0); // set collapsed
|
||||
expect.extend_from_slice(&[0, 0, 0, 1]); // one action
|
||||
expect.extend_from_slice(&[0, 0, 0, 0, 0, 0]); // no function key, no modifiers, no colour
|
||||
expect.extend_from_slice(&[0, 0, 0, 9]);
|
||||
for c in "Action 1\0".encode_utf16() {
|
||||
expect.extend_from_slice(&c.to_be_bytes());
|
||||
}
|
||||
expect.push(1); // action expanded
|
||||
expect.extend_from_slice(&[0, 0, 0, 1]); // one step
|
||||
expect.extend_from_slice(&[1, 1, 0, 0]); // expanded, enabled, no dialog, options 0
|
||||
expect.extend_from_slice(b"TEXT\0\0\0\x04trim");
|
||||
expect.extend_from_slice(b"\0\0\0\x04Trim");
|
||||
expect.extend_from_slice(&[0xff; 4]); // a descriptor follows
|
||||
expect.extend_from_slice(&[0, 0, 0, 5, 0, b'T', 0, b'r', 0, b'i', 0, b'm', 0, 0]); // class name
|
||||
expect.extend_from_slice(b"\0\0\0\x04trim"); // class id, length-4 string form
|
||||
expect.extend_from_slice(&[0, 0, 0, 0]); // no items
|
||||
assert_eq!(write(&f).unwrap(), expect);
|
||||
assert_eq!(parse(&expect).unwrap(), f);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncation_never_parses_and_never_panics() {
|
||||
let bytes = write(&set()).unwrap();
|
||||
for cut in 0..bytes.len() {
|
||||
assert!(parse(&bytes[..cut]).is_err(), "cut at {cut}/{}", bytes.len());
|
||||
}
|
||||
let mut padded = bytes.clone();
|
||||
padded.extend_from_slice(b"junk");
|
||||
let f = parse(&padded).unwrap();
|
||||
assert_eq!(f.warnings, ["4 trailing bytes ignored"]);
|
||||
assert_eq!(f.actions, set().actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_versions_and_bad_structure() {
|
||||
let mut bytes = write(&set()).unwrap();
|
||||
bytes[3] = 12;
|
||||
assert!(matches!(parse(&bytes), Err(PsdError::Unsupported(_))));
|
||||
// A count far beyond the data must fail before allocating.
|
||||
let mut huge = vec![0, 0, 0, 16, 0, 0, 0, 0, 0];
|
||||
huge.extend_from_slice(&u32::MAX.to_be_bytes());
|
||||
assert!(matches!(parse(&huge), Err(PsdError::UnexpectedEof { .. })));
|
||||
// Unknown event kinds and descriptor flags are reported, not guessed.
|
||||
let mut bad_kind = write(&set()).unwrap();
|
||||
let at = bad_kind.windows(4).position(|w| w == b"long").unwrap();
|
||||
bad_kind[at..at + 4].copy_from_slice(b"what");
|
||||
assert!(matches!(parse(&bad_kind), Err(PsdError::Invalid(_))));
|
||||
let mut bad_flag = write(&set()).unwrap();
|
||||
let at = bad_flag.windows(4).position(|w| w == [0xff; 4]).unwrap();
|
||||
bad_flag[at..at + 4].copy_from_slice(&[0, 0, 0, 7]);
|
||||
assert!(matches!(parse(&bad_flag), Err(PsdError::Invalid(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_never_panics() {
|
||||
let seed = write(&set()).unwrap();
|
||||
let mut x: u32 = 0x9e37_79b9;
|
||||
for i in 0..2000 {
|
||||
let mut bytes = seed.clone();
|
||||
for _ in 0..(i % 7 + 1) {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
let at = (x as usize) % bytes.len();
|
||||
bytes[at] = (x >> 8) as u8;
|
||||
}
|
||||
let _ = parse(&bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -149,10 +149,20 @@ pub enum ReferenceItem {
|
||||
/// Offset.
|
||||
offset: i32,
|
||||
},
|
||||
/// `Idnt`
|
||||
Identifier(u32),
|
||||
/// `indx`
|
||||
Index(u32),
|
||||
/// `Idnt`: a class plus an identifier (Photoshop's layer ids in action references).
|
||||
Identifier {
|
||||
/// Class.
|
||||
class: Class,
|
||||
/// Identifier.
|
||||
id: u32,
|
||||
},
|
||||
/// `indx`: a class plus a zero-based index.
|
||||
Index {
|
||||
/// Class.
|
||||
class: Class,
|
||||
/// Index.
|
||||
index: u32,
|
||||
},
|
||||
/// `name`
|
||||
Name {
|
||||
/// Class.
|
||||
@@ -454,8 +464,8 @@ fn read_reference_item(r: &mut Reader<'_>) -> Result<ReferenceItem> {
|
||||
b"Clss" => ReferenceItem::Class(Class::read(r)?),
|
||||
b"Enmr" => ReferenceItem::Enumerated { class: Class::read(r)?, type_id: Id::read(r)?, value: Id::read(r)? },
|
||||
b"rele" => ReferenceItem::Offset { class: Class::read(r)?, offset: r.i32()? },
|
||||
b"Idnt" => ReferenceItem::Identifier(r.u32()?),
|
||||
b"indx" => ReferenceItem::Index(r.u32()?),
|
||||
b"Idnt" => ReferenceItem::Identifier { class: Class::read(r)?, id: r.u32()? },
|
||||
b"indx" => ReferenceItem::Index { class: Class::read(r)?, index: r.u32()? },
|
||||
b"name" => ReferenceItem::Name { class: Class::read(r)?, name: UnicodeString::read(r)? },
|
||||
other => {
|
||||
return Err(PsdError::Unsupported(format!("reference item type {:?}", String::from_utf8_lossy(other))));
|
||||
@@ -556,13 +566,15 @@ fn write_reference_item(it: &ReferenceItem, out: &mut Vec<u8>) {
|
||||
class.write(out);
|
||||
out.put_i32(*offset);
|
||||
}
|
||||
ReferenceItem::Identifier(v) => {
|
||||
ReferenceItem::Identifier { class, id } => {
|
||||
out.put(b"Idnt");
|
||||
out.put_u32(*v);
|
||||
class.write(out);
|
||||
out.put_u32(*id);
|
||||
}
|
||||
ReferenceItem::Index(v) => {
|
||||
ReferenceItem::Index { class, index } => {
|
||||
out.put(b"indx");
|
||||
out.put_u32(*v);
|
||||
class.write(out);
|
||||
out.put_u32(*index);
|
||||
}
|
||||
ReferenceItem::Name { class, name } => {
|
||||
out.put(b"name");
|
||||
@@ -614,8 +626,8 @@ mod tests {
|
||||
ReferenceItem::Class(class("", "Dcmn")),
|
||||
ReferenceItem::Enumerated { class: class("", "Lyr "), type_id: Id::new("Ordn"), value: Id::new("Trgt") },
|
||||
ReferenceItem::Offset { class: class("", "Lyr "), offset: -1 },
|
||||
ReferenceItem::Identifier(7),
|
||||
ReferenceItem::Index(2),
|
||||
ReferenceItem::Identifier { class: class("", "Lyr "), id: 7 },
|
||||
ReferenceItem::Index { class: class("\0", "Lyr "), index: 2 },
|
||||
ReferenceItem::Name { class: class("", "Lyr "), name: UnicodeString::new("Bg") },
|
||||
]),
|
||||
)
|
||||
@@ -793,8 +805,8 @@ pub(crate) mod proptests {
|
||||
arb_class().prop_map(ReferenceItem::Class),
|
||||
(arb_class(), arb_id(), arb_id()).prop_map(|(class, type_id, value)| ReferenceItem::Enumerated { class, type_id, value }),
|
||||
(arb_class(), any::<i32>()).prop_map(|(class, offset)| ReferenceItem::Offset { class, offset }),
|
||||
any::<u32>().prop_map(ReferenceItem::Identifier),
|
||||
any::<u32>().prop_map(ReferenceItem::Index),
|
||||
(arb_class(), any::<u32>()).prop_map(|(class, id)| ReferenceItem::Identifier { class, id }),
|
||||
(arb_class(), any::<u32>()).prop_map(|(class, index)| ReferenceItem::Index { class, index }),
|
||||
(arb_class(), arb_ustr()).prop_map(|(class, name)| ReferenceItem::Name { class, name }),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
pub mod abr;
|
||||
pub mod aco;
|
||||
pub mod ase;
|
||||
pub mod atn;
|
||||
pub mod blend;
|
||||
pub mod builder;
|
||||
pub mod compression;
|
||||
|
||||
@@ -218,11 +218,126 @@ fn step_label(id: &str, params: &Value) -> String {
|
||||
if id == "actions.play" {
|
||||
let target = params.get("action").map(|v| v.as_str().map(str::to_owned).unwrap_or_else(|| v.to_string())).unwrap_or_default();
|
||||
format!("{}: {target}", label_of(id))
|
||||
} else if id == photocraft_engine::atn_cmds::STOP_MESSAGE {
|
||||
format!("{}: {}", label_of(id), params.get("message").and_then(Value::as_str).unwrap_or_default())
|
||||
} else if id == photocraft_engine::atn_cmds::PHOTOSHOP_STEP {
|
||||
// A step from a .atn file PhotoCraft can't play yet: its Photoshop name, marked.
|
||||
let name = params.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).unwrap_or("?");
|
||||
crate::i18n::fmt(tl!("{name} (Photoshop)"), &[("name", name)])
|
||||
} else {
|
||||
label_of(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Command params for a picked file: a real path keeps the journal small; browser files arrive
|
||||
/// as bytes.
|
||||
fn source(name: &str, bytes: &[u8]) -> Value {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if std::path::Path::new(name).is_absolute() && std::path::Path::new(name).is_file() {
|
||||
return json!({"path": name});
|
||||
}
|
||||
let _ = name;
|
||||
json!({"data": photocraft_engine::paint::tile::b64_encode(bytes)})
|
||||
}
|
||||
|
||||
/// Load a `.atn` file's bytes into the Actions panel (the panel menu's Load Actions…).
|
||||
pub fn load_bytes(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Result<Value, String> {
|
||||
let r = app.run("actions.load", source(name, bytes))?;
|
||||
let n = r["actions"].as_array().map_or(0, Vec::len) as u64;
|
||||
let unsupported = r["unsupported"].as_array().map_or(0, Vec::len);
|
||||
let shown = crate::file_open::display_name(name);
|
||||
let loaded =
|
||||
crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n, "Loaded {n} action from {file}", "Loaded {n} actions from {file}"), &[("file", &shown)]);
|
||||
app.ui.status_error = false;
|
||||
app.ui.status = if unsupported > 0 {
|
||||
let note = crate::i18n::trn(
|
||||
crate::i18n::current(),
|
||||
unsupported as u64,
|
||||
"{n} step has no PhotoCraft equivalent yet",
|
||||
"{n} steps have no PhotoCraft equivalent yet",
|
||||
);
|
||||
let template = "{message} ({note})";
|
||||
crate::i18n::fmt(tl!(template), &[("message", &loaded), ("note", ¬e)])
|
||||
} else {
|
||||
loaded
|
||||
};
|
||||
// Show what arrived: select the first loaded action, expanded.
|
||||
let list = &app.session.actions.list;
|
||||
if let Some(first) = r["actions"][0].as_str()
|
||||
&& let Some(i) = list.iter().position(|a| a.name == first)
|
||||
{
|
||||
app.ui.actions.selected = Some(i);
|
||||
app.ui.actions.selected_step = None;
|
||||
app.ui.actions.expanded.resize(list.len(), false);
|
||||
if let Some(e) = app.ui.actions.expanded.get_mut(i) {
|
||||
*e = true;
|
||||
}
|
||||
}
|
||||
app.ui.panels.history = true;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn load_dialog(app: &mut PhotocraftApp) -> Result<Value, String> {
|
||||
app.pick_file_bytes_filtered(&["atn"], |app, name, bytes| load_bytes(app, &name, &bytes))
|
||||
}
|
||||
|
||||
/// Save Actions…: the selected action's set (every action of it), or every action when none
|
||||
/// came from a set, as a `.atn` file Photoshop loads.
|
||||
fn save_dialog(app: &mut PhotocraftApp) -> Result<Value, String> {
|
||||
let set = selected_action(app).and_then(|a| a.set.clone());
|
||||
let params = match &set {
|
||||
Some(set) => json!({"set": set, "skipUnsupported": true}),
|
||||
None => json!({"skipUnsupported": true}),
|
||||
};
|
||||
let r = app.run("actions.save", params)?;
|
||||
let bytes = r["data"].as_str().and_then(photocraft_engine::paint::tile::b64_decode).ok_or("the export returned no data")?;
|
||||
let n = r["actions"].as_array().map_or(0, Vec::len) as u64;
|
||||
let skipped = r["skipped"].as_array().map_or(0, Vec::len);
|
||||
let file = format!("{}.atn", r["set"].as_str().unwrap_or("Actions"));
|
||||
app.pick_save(&file, move |app, path| {
|
||||
let write = app.services.write.as_mut().ok_or("no writer configured")?;
|
||||
write(&path, &bytes)?;
|
||||
let shown = crate::file_open::display_name(&path);
|
||||
let saved =
|
||||
crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n, "Saved {n} action to {file}", "Saved {n} actions to {file}"), &[("file", &shown)]);
|
||||
app.ui.status_error = false;
|
||||
app.ui.status = if skipped > 0 {
|
||||
let note = crate::i18n::trn(
|
||||
crate::i18n::current(),
|
||||
skipped as u64,
|
||||
"{n} step with no Photoshop equivalent left out",
|
||||
"{n} steps with no Photoshop equivalent left out",
|
||||
);
|
||||
let template = "{message} ({note})";
|
||||
crate::i18n::fmt(tl!(template), &[("message", &saved), ("note", ¬e)])
|
||||
} else {
|
||||
saved
|
||||
};
|
||||
Ok(json!({"path": path, "actions": n, "skipped": skipped}))
|
||||
})
|
||||
}
|
||||
|
||||
/// The Actions entries of the panel group's menu ("…").
|
||||
pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let mut act: Option<&str> = None;
|
||||
if ui.button(tl!("Load Actions…")).clicked() {
|
||||
act = Some("load");
|
||||
}
|
||||
let any = !app.session.actions.list.is_empty();
|
||||
if ui.add_enabled(any, egui::Button::new(tl!("Save Actions…"))).clicked() {
|
||||
act = Some("save");
|
||||
}
|
||||
let Some(a) = act else { return };
|
||||
ui.close();
|
||||
let r = if a == "load" { load_dialog(app) } else { save_dialog(app) };
|
||||
if let Err(e) = r
|
||||
&& e != "cancelled"
|
||||
{
|
||||
app.ui.status = e;
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct DragRow {
|
||||
action: usize,
|
||||
@@ -555,7 +670,7 @@ mod tests {
|
||||
let bottom = |height: f32| {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
for i in 0..50 {
|
||||
app.session.actions.list.push(Action { name: format!("Action {i}"), steps: vec![], disabled: Default::default() });
|
||||
app.session.actions.list.push(Action { name: format!("Action {i}"), steps: vec![], disabled: Default::default(), ..Default::default() });
|
||||
}
|
||||
let mut h = Harness::builder().with_size(vec2(320.0, height)).build_ui_state(|ui, app| panel(app, ui), app);
|
||||
h.run_steps(3);
|
||||
@@ -572,7 +687,12 @@ mod tests {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 32, "height": 32})).unwrap();
|
||||
app.session.actions.list.push(Action { name: "Action 1".into(), steps: vec![("layer.new.layer".into(), json!({}))], disabled: Default::default() });
|
||||
app.session.actions.list.push(Action {
|
||||
name: "Action 1".into(),
|
||||
steps: vec![("layer.new.layer".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
let layers = app.session.active().unwrap().doc.layers.len();
|
||||
// 60 fps steps, so two clicks a frame apart count as a double-click.
|
||||
let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| panel(app, ui), app);
|
||||
@@ -606,8 +726,18 @@ mod tests {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 32, "height": 32})).unwrap();
|
||||
assert_eq!(playback_selection(&app), None);
|
||||
app.session.actions.list.push(Action { name: "Make Layer".into(), steps: vec![("layer.new.layer".into(), json!({}))], disabled: Default::default() });
|
||||
app.session.actions.list.push(Action { name: "Fit".into(), steps: vec![("view.fitOnScreen".into(), json!({}))], disabled: Default::default() });
|
||||
app.session.actions.list.push(Action {
|
||||
name: "Make Layer".into(),
|
||||
steps: vec![("layer.new.layer".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
app.session.actions.list.push(Action {
|
||||
name: "Fit".into(),
|
||||
steps: vec![("view.fitOnScreen".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(playback_selection(&app), Some(0));
|
||||
app.ui.actions.selected = Some(1);
|
||||
assert_eq!(playback_selection(&app), Some(1));
|
||||
@@ -654,7 +784,12 @@ mod tests {
|
||||
use egui_kittest::{Harness, kittest::Queryable};
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 32, "height": 32})).unwrap();
|
||||
app.session.actions.list.push(Action { name: "Bad action".into(), steps: vec![("not.a.command".into(), json!({}))], disabled: Default::default() });
|
||||
app.session.actions.list.push(Action {
|
||||
name: "Bad action".into(),
|
||||
steps: vec![("not.a.command".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
let mut h = Harness::builder().with_size(vec2(400.0, 320.0)).build_ui_state(|ui, app| panel(app, ui), app);
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Play selection").click();
|
||||
@@ -669,7 +804,7 @@ mod tests {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width":4,"height":4})).unwrap();
|
||||
for i in 0..30 {
|
||||
app.session.actions.list.push(Action { name: format!("Existing {i}"), steps: vec![], disabled: Default::default() });
|
||||
app.session.actions.list.push(Action { name: format!("Existing {i}"), steps: vec![], disabled: Default::default(), ..Default::default() });
|
||||
}
|
||||
let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).build_ui_state(|ui, app| panel(app, ui), app);
|
||||
h.run_steps(4);
|
||||
@@ -694,8 +829,9 @@ mod tests {
|
||||
name: "First".into(),
|
||||
steps: vec![("view.zoomOut".into(), json!({})), ("view.fitOnScreen".into(), json!({})), ("view.actualPixels".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
app.session.actions.list.push(Action { name: "Second".into(), steps: vec![], disabled: Default::default() });
|
||||
app.session.actions.list.push(Action { name: "Second".into(), steps: vec![], disabled: Default::default(), ..Default::default() });
|
||||
app.ui.actions.expanded = vec![true, false];
|
||||
let mut h = Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app);
|
||||
h.run_steps(4);
|
||||
@@ -735,6 +871,7 @@ mod tests {
|
||||
name: "Child".into(),
|
||||
steps: vec![("layer.new.layer".into(), json!({})), ("view.fitOnScreen".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
app.run("actions.record", json!({"name":"Parent"})).unwrap();
|
||||
app.run("actions.play", json!({"action":"Child"})).unwrap();
|
||||
@@ -827,6 +964,7 @@ mod tests {
|
||||
name: "Fit".into(),
|
||||
steps: vec![("view.fitOnScreen".into(), json!({})), ("view.actualPixels".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
let result = app.run("actions.play", json!({"action": "Fit"})).unwrap();
|
||||
assert_eq!(result["ran"], 0);
|
||||
|
||||
@@ -2514,6 +2514,7 @@ mod tests {
|
||||
name: "Linked contents".into(),
|
||||
steps: vec![(command.into(), json!({"layer": smart.0}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
}];
|
||||
let r = call(&mut app, &ctx, "engine.execute", json!({"command": "actions.play", "params": {"action": "Linked contents"}}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
@@ -2544,6 +2545,7 @@ mod tests {
|
||||
name: "Open".into(),
|
||||
steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
let ctx = egui::Context::default();
|
||||
let r = call(&mut app, &ctx, "engine.execute", json!({"command": "actions.play", "params": {"action": "Open"}}));
|
||||
@@ -2563,6 +2565,7 @@ mod tests {
|
||||
name: "Open".into(),
|
||||
steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
app.automation_input = true;
|
||||
let r = app.run("actions.play", json!({"action": "Open"})).unwrap();
|
||||
|
||||
@@ -601,6 +601,10 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, shown: &[Group], mut bod
|
||||
crate::swatches_ui::panel_menu(app, ui);
|
||||
ui.separator();
|
||||
}
|
||||
if tabs.get(sel) == Some(&"Actions") {
|
||||
crate::actions::panel_menu(app, ui);
|
||||
ui.separator();
|
||||
}
|
||||
if let Some(label) = tabs.get(sel) {
|
||||
crate::panel_docking::legacy_menu(app, ui, label);
|
||||
}
|
||||
|
||||
@@ -3669,6 +3669,16 @@ navigator Zoom Zvětšení
|
||||
Remove after each stroke Odstranit po každém tahu
|
||||
Apply the removal ({key}) Použít odstranění ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Tahy k odstranění: {n} (Enter použije, Esc zruší)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Načíst akce…
|
||||
Save Actions… Uložit akce…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} Načtena {n} akce ze souboru {file}|Načteny {n} akce ze souboru {file}|Načteno {n} akcí ze souboru {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} krok zatím nemá v PhotoCraftu obdobu|{n} kroky zatím nemají v PhotoCraftu obdobu|{n} kroků zatím nemá v PhotoCraftu obdobu
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} Uložena {n} akce do souboru {file}|Uloženy {n} akce do souboru {file}|Uloženo {n} akcí do souboru {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Vynechán {n} krok bez obdoby v Photoshopu|Vynechány {n} kroky bez obdoby v Photoshopu|Vynecháno {n} kroků bez obdoby v Photoshopu
|
||||
Automatically Create First Snapshot Automaticky vytvořit první snímek
|
||||
Automatically Create New Snapshot When Saving Automaticky vytvořit nový snímek při ukládání
|
||||
Show New Snapshot Dialog by Default Ve výchozím nastavení zobrazit dialog Nový snímek
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -2701,6 +2701,16 @@ curves Smooth Glätten
|
||||
Remove after each stroke Nach jedem Strich entfernen
|
||||
Apply the removal ({key}) Entfernen anwenden ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Striche zum Entfernen: {n} (Eingabe wendet an, Esc bricht ab)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Aktionen laden…
|
||||
Save Actions… Aktionen speichern…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} {n} Aktion aus {file} geladen|{n} Aktionen aus {file} geladen
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} Schritt hat noch keine Entsprechung in PhotoCraft|{n} Schritte haben noch keine Entsprechung in PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} Aktion in {file} gespeichert|{n} Aktionen in {file} gespeichert
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} Schritt ohne Photoshop-Entsprechung ausgelassen|{n} Schritte ohne Photoshop-Entsprechung ausgelassen
|
||||
Automatically Create First Snapshot Ersten Snapshot automatisch erstellen
|
||||
Automatically Create New Snapshot When Saving Beim Speichern automatisch neuen Snapshot erstellen
|
||||
Show New Snapshot Dialog by Default Dialogfeld „Neuer Snapshot“ standardmäßig anzeigen
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3758,3 +3758,13 @@ curves Smooth Εξομάλυνση
|
||||
Remove after each stroke Αφαίρεση μετά από κάθε πινελιά
|
||||
Apply the removal ({key}) Εφαρμογή της αφαίρεσης ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Πινελιές προς αφαίρεση: {n} (Enter εφαρμόζει, Esc ακυρώνει)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Φόρτωση ενεργειών…
|
||||
Save Actions… Αποθήκευση ενεργειών…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} Φορτώθηκε {n} ενέργεια από το {file}|Φορτώθηκαν {n} ενέργειες από το {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} βήμα δεν έχει ακόμη αντίστοιχο στο PhotoCraft|{n} βήματα δεν έχουν ακόμη αντίστοιχο στο PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} Αποθηκεύτηκε {n} ενέργεια στο {file}|Αποθηκεύτηκαν {n} ενέργειες στο {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Παραλείφθηκε {n} βήμα χωρίς αντίστοιχο στο Photoshop|Παραλείφθηκαν {n} βήματα χωρίς αντίστοιχο στο Photoshop
|
||||
|
Can't render this file because it contains an unexpected character in line 1003 and column 18.
|
@@ -2742,6 +2742,16 @@ curves Smooth Suavizar
|
||||
Remove after each stroke Eliminar después de cada trazo
|
||||
Apply the removal ({key}) Aplicar la eliminación ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Trazos por eliminar: {n} (Intro aplica, Esc cancela)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Cargar acciones…
|
||||
Save Actions… Guardar acciones…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} Se cargó {n} acción de {file}|Se cargaron {n} acciones de {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} paso aún no tiene equivalente en PhotoCraft|{n} pasos aún no tienen equivalente en PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} Se guardó {n} acción en {file}|Se guardaron {n} acciones en {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} paso sin equivalente en Photoshop omitido|{n} pasos sin equivalente en Photoshop omitidos
|
||||
Automatically Create First Snapshot Crear automáticamente la primera instantánea
|
||||
Automatically Create New Snapshot When Saving Crear automáticamente una instantánea nueva al guardar
|
||||
Show New Snapshot Dialog by Default Mostrar el cuadro de diálogo Instantánea nueva de forma predeterminada
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -3061,3 +3061,13 @@ curves Smooth Lisser
|
||||
Remove after each stroke Supprimer après chaque trait
|
||||
Apply the removal ({key}) Appliquer la suppression ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Traits à supprimer : {n} (Entrée applique, Échap annule)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Charger des actions…
|
||||
Save Actions… Enregistrer les actions…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} {n} action chargée depuis {file}|{n} actions chargées depuis {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} étape n’a pas encore d’équivalent dans PhotoCraft|{n} étapes n’ont pas encore d’équivalent dans PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} action enregistrée dans {file}|{n} actions enregistrées dans {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} étape sans équivalent Photoshop omise|{n} étapes sans équivalent Photoshop omises
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3978,3 +3978,13 @@ cameraRaw Yellow Sárga
|
||||
Transform On Drop Átalakítás elengedéskor
|
||||
Vanishing Point is not active Az Enyészpont nem aktív
|
||||
Vanishing Point: click four corners to create a plane Enyészpont: sík létrehozásához kattintson a négy sarokra
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Műveletek betöltése…
|
||||
Save Actions… Műveletek mentése…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} {n} művelet betöltve. Forrás: {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} lépésnek még nincs megfelelője a PhotoCraftban
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} művelet mentve. Cél: {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} Photoshop-megfelelő nélküli lépés kihagyva
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3048,3 +3048,13 @@ curves Smooth Haluskan
|
||||
Remove after each stroke Hapus setelah setiap goresan
|
||||
Apply the removal ({key}) Terapkan penghapusan ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Goresan untuk dihapus: {n} (Enter menerapkan, Esc membatalkan)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Muat Tindakan…
|
||||
Save Actions… Simpan Tindakan…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} {n} tindakan dimuat dari {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} langkah belum memiliki padanan di PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} tindakan disimpan ke {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} langkah tanpa padanan Photoshop dilewati
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -4024,3 +4024,13 @@ navigator Zoom Zoom
|
||||
Remove after each stroke Rimuovi dopo ogni tratto
|
||||
Apply the removal ({key}) Applica la rimozione ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Tratti da rimuovere: {n} (Invio applica, Esc annulla)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Carica azioni…
|
||||
Save Actions… Salva azioni…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} Caricata {n} azione da {file}|Caricate {n} azioni da {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} passaggio non ha ancora un equivalente in PhotoCraft|{n} passaggi non hanno ancora un equivalente in PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} Salvata {n} azione in {file}|Salvate {n} azioni in {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Omesso {n} passaggio senza equivalente in Photoshop|Omessi {n} passaggi senza equivalente in Photoshop
|
||||
|
Can't render this file because it contains an unexpected character in line 2595 and column 53.
|
@@ -3670,3 +3670,13 @@ curves Smooth スムーズ
|
||||
Remove after each stroke ストロークごとに削除
|
||||
Apply the removal ({key}) 削除を適用 ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) 削除するストローク: {n}(Enter で適用、Esc で取り消し)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… アクションを読み込み…
|
||||
Save Actions… アクションを保存…
|
||||
{name} (Photoshop) {name}(Photoshop)
|
||||
{message} ({note}) {message}({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} {file} からアクション {n} 個を読み込みました
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} 個のステップにはまだ PhotoCraft の対応機能がありません
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} {file} にアクション {n} 個を保存しました
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Photoshop に対応するもののない {n} 個のステップを省きました
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3231,6 +3231,16 @@ curves Smooth 매끄럽게
|
||||
Remove after each stroke 획마다 제거
|
||||
Apply the removal ({key}) 제거 적용 ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) 제거할 획: {n} (Enter 적용, Esc 취소)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… 액션 불러오기…
|
||||
Save Actions… 액션 저장…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} {file}에서 액션 {n}개를 불러왔습니다
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n}개 단계에는 아직 PhotoCraft에 해당하는 기능이 없습니다
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} {file}에 액션 {n}개를 저장했습니다
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Photoshop에 해당하는 기능이 없는 {n}개 단계를 제외했습니다
|
||||
Automatically Create First Snapshot 첫 번째 스냅샷 자동 만들기
|
||||
Automatically Create New Snapshot When Saving 저장할 때 새 스냅샷 자동 만들기
|
||||
Show New Snapshot Dialog by Default 기본적으로 새 스냅샷 대화 상자 표시
|
||||
|
Can't render this file because it contains an unexpected character in line 3105 and column 53.
|
@@ -3820,3 +3820,13 @@ curves Smooth Vloeiend maken
|
||||
Remove after each stroke Verwijderen na elke streek
|
||||
Apply the removal ({key}) Verwijdering toepassen ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Streken om te verwijderen: {n} (Enter past toe, Esc annuleert)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Handelingen laden…
|
||||
Save Actions… Handelingen opslaan…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} {n} handeling geladen uit {file}|{n} handelingen geladen uit {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} stap heeft nog geen equivalent in PhotoCraft|{n} stappen hebben nog geen equivalent in PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} handeling opgeslagen in {file}|{n} handelingen opgeslagen in {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} stap zonder Photoshop-equivalent weggelaten|{n} stappen zonder Photoshop-equivalent weggelaten
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -3657,3 +3657,13 @@ curves Smooth Wygładź
|
||||
Remove after each stroke Usuwaj po każdym pociągnięciu
|
||||
Apply the removal ({key}) Zastosuj usuwanie ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Pociągnięcia do usunięcia: {n} (Enter stosuje, Esc anuluje)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Wczytaj operacje…
|
||||
Save Actions… Zapisz operacje…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} Wczytano {n} operację z {file}|Wczytano {n} operacje z {file}|Wczytano {n} operacji z {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} krok nie ma jeszcze odpowiednika w PhotoCraft|{n} kroki nie mają jeszcze odpowiednika w PhotoCraft|{n} kroków nie ma jeszcze odpowiednika w PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} Zapisano {n} operację do {file}|Zapisano {n} operacje do {file}|Zapisano {n} operacji do {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Pominięto {n} krok bez odpowiednika w Photoshopie|Pominięto {n} kroki bez odpowiednika w Photoshopie|Pominięto {n} kroków bez odpowiednika w Photoshopie
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3850,3 +3850,13 @@ layerLabel No Color Sem cor
|
||||
Remove after each stroke Remover após cada traço
|
||||
Apply the removal ({key}) Aplicar a remoção ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Traços a remover: {n} (Enter aplica, Esc cancela)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Carregar ações…
|
||||
Save Actions… Salvar ações…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} {n} ação carregada de {file}|{n} ações carregadas de {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} etapa ainda não tem equivalente no PhotoCraft|{n} etapas ainda não têm equivalente no PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} ação salva em {file}|{n} ações salvas em {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} etapa sem equivalente no Photoshop foi omitida|{n} etapas sem equivalente no Photoshop foram omitidas
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3005,3 +3005,13 @@ curves Smooth Сгладить
|
||||
Remove after each stroke Удалять после каждого штриха
|
||||
Apply the removal ({key}) Применить удаление ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Штрихов к удалению: {n} (Enter применяет, Esc отменяет)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Загрузить операции…
|
||||
Save Actions… Сохранить операции…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} Загружена {n} операция из {file}|Загружено {n} операции из {file}|Загружено {n} операций из {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} шаг пока не имеет эквивалента в PhotoCraft|{n} шага пока не имеют эквивалента в PhotoCraft|{n} шагов пока не имеют эквивалента в PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} Сохранена {n} операция в {file}|Сохранено {n} операции в {file}|Сохранено {n} операций в {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Пропущен {n} шаг без эквивалента в Photoshop|Пропущено {n} шага без эквивалента в Photoshop|Пропущено {n} шагов без эквивалента в Photoshop
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3790,3 +3790,13 @@ cameraData Lens Lens
|
||||
@plural {n} step|{n} steps {n} adım
|
||||
@plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} fırça ön ayarı uyarısı daha)
|
||||
@plural {what} with {n} warning|{what} with {n} warnings {what}, {n} uyarı ile
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Eylemleri Yükle…
|
||||
Save Actions… Eylemleri Kaydet…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} {file} dosyasından {n} eylem yüklendi
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} adımın PhotoCraft’ta henüz karşılığı yok
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} eylem {file} dosyasına kaydedildi
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Photoshop karşılığı olmayan {n} adım atlandı
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -3758,3 +3758,13 @@ curves Smooth Згладити
|
||||
Remove after each stroke Видаляти після кожного штриха
|
||||
Apply the removal ({key}) Застосувати видалення ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Штрихів для видалення: {n} (Enter застосовує, Esc скасовує)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Завантажити операції…
|
||||
Save Actions… Зберегти операції…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} Завантажено {n} операцію з {file}|Завантажено {n} операції з {file}|Завантажено {n} операцій з {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} крок ще не має відповідника в PhotoCraft|{n} кроки ще не мають відповідника в PhotoCraft|{n} кроків ще не мають відповідника в PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} Збережено {n} операцію до {file}|Збережено {n} операції до {file}|Збережено {n} операцій до {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Пропущено {n} крок без відповідника в Photoshop|Пропущено {n} кроки без відповідника в Photoshop|Пропущено {n} кроків без відповідника в Photoshop
|
||||
|
Can't render this file because it contains an unexpected character in line 1357 and column 18.
|
@@ -3541,6 +3541,15 @@ curves Smooth Làm mượt
|
||||
Apply the removal ({key}) Áp dụng việc xóa ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) Nét vẽ cần xóa: {n} (Enter áp dụng, Esc hủy)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… Nạp hành động…
|
||||
Save Actions… Lưu hành động…
|
||||
{name} (Photoshop) {name} (Photoshop)
|
||||
{message} ({note}) {message} ({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} Đã nạp {n} hành động từ {file}
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} bước chưa có chức năng tương ứng trong PhotoCraft
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} Đã lưu {n} hành động vào {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Đã bỏ qua {n} bước không có chức năng tương ứng trong Photoshop
|
||||
# History panel › History Options… (#2966)
|
||||
History Options… Tùy chọn lịch sử…
|
||||
Allow Non-Linear History Cho phép lịch sử không tuyến tính
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -2666,6 +2666,16 @@ curves Smooth 平滑
|
||||
Remove after each stroke 每次描边后移除
|
||||
Apply the removal ({key}) 应用移除 ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) 待移除的描边:{n}(Enter 应用,Esc 取消)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… 载入动作…
|
||||
Save Actions… 存储动作…
|
||||
{name} (Photoshop) {name}(Photoshop)
|
||||
{message} ({note}) {message}({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} 已从 {file} 载入 {n} 个动作
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} 个步骤在 PhotoCraft 中尚无对应功能
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} 已将 {n} 个动作存储到 {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out 已省略 {n} 个没有 Photoshop 对应功能的步骤
|
||||
Automatically Create First Snapshot 自动创建第一幅快照
|
||||
Automatically Create New Snapshot When Saving 存储时自动创建新快照
|
||||
Show New Snapshot Dialog by Default 默认显示新建快照对话框
|
||||
|
Can't render this file because it contains an unexpected character in line 2538 and column 53.
|
@@ -2651,6 +2651,16 @@ curves Smooth 平滑
|
||||
Remove after each stroke 每次描邊後移除
|
||||
Apply the removal ({key}) 套用移除 ({key})
|
||||
Strokes to remove: {n} (Enter applies, Esc cancels) 待移除的描邊:{n}(Enter 套用,Esc 取消)
|
||||
|
||||
# Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
|
||||
Load Actions… 載入動作…
|
||||
Save Actions… 儲存動作…
|
||||
{name} (Photoshop) {name}(Photoshop)
|
||||
{message} ({note}) {message}({note})
|
||||
@plural Loaded {n} action from {file}|Loaded {n} actions from {file} 已從 {file} 載入 {n} 個動作
|
||||
@plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} 個步驟在 PhotoCraft 中尚無對應功能
|
||||
@plural Saved {n} action to {file}|Saved {n} actions to {file} 已將 {n} 個動作儲存到 {file}
|
||||
@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out 已略過 {n} 個沒有 Photoshop 對應功能的步驟
|
||||
Automatically Create First Snapshot 自動建立第一個快照
|
||||
Automatically Create New Snapshot When Saving 儲存時自動建立新快照
|
||||
Show New Snapshot Dialog by Default 預設顯示新增快照對話框
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -51,10 +51,10 @@ fn drag(app: &mut PhotocraftApp, from: [f64; 2], by: [f64; 2], mods: egui::Modif
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_select_is_on_by_default_with_the_layer_target() {
|
||||
fn auto_select_is_on_by_default_with_the_group_target() {
|
||||
let o = ToolOptions::default();
|
||||
assert!(o.move_auto_select, "Photoshop ships with Auto-Select checked");
|
||||
assert_eq!(o.move_target, "layer");
|
||||
assert_eq!(o.move_target, "group", "Photoshop defaults Auto-Select to Group (#4056)");
|
||||
// A saved tool preset that predates the option gets the default too.
|
||||
let mut v = serde_json::to_value(&o).unwrap();
|
||||
v.as_object_mut().unwrap().remove("move_auto_select");
|
||||
|
||||
@@ -843,6 +843,10 @@ fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui, panel: &str) {
|
||||
crate::swatches_ui::panel_menu(app, ui);
|
||||
ui.separator();
|
||||
}
|
||||
"actions" => {
|
||||
crate::actions::panel_menu(app, ui);
|
||||
ui.separator();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -543,6 +543,7 @@ fn named_action_function_key_replays_and_survives_preferences_roundtrip() {
|
||||
name: "LivePrint 2R".into(),
|
||||
steps: vec![("layer.new.layer".into(), json!({"name": "F6 overlay"}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
};
|
||||
h.state_mut().session.actions.list.push(action);
|
||||
crate::actions::assign_shortcut(h.state_mut(), "LivePrint 2R", "F6").unwrap();
|
||||
@@ -568,6 +569,7 @@ fn assigning_action_function_key_moves_it_and_reports_failed_steps() {
|
||||
name: name.into(),
|
||||
steps: vec![("no.such.command".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
crate::actions::assign_shortcut(h.state_mut(), "first", "F6").unwrap();
|
||||
@@ -587,6 +589,7 @@ fn action_function_key_checks_automation_authorization() {
|
||||
name: "restricted".into(),
|
||||
steps: vec![("layer.new.layer".into(), json!({"name": "should not exist"}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
crate::actions::assign_shortcut(h.state_mut(), "restricted", "F6").unwrap();
|
||||
h.state_mut().services.automation_command = Some(Box::new(|id, _| if id == "actions.play" { Err("denied action playback".into()) } else { Ok(()) }));
|
||||
@@ -624,6 +627,7 @@ fn f6_while_recording_records_a_named_call_not_the_child_steps() {
|
||||
name: "LivePrint 2R".into(),
|
||||
steps: vec![("layer.new.layer".into(), json!({"name":"Nested overlay"})), ("view.fitOnScreen".into(), json!({}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
crate::actions::assign_shortcut(h.state_mut(), "LivePrint 2R", "F6").unwrap();
|
||||
h.state_mut().run("actions.record", json!({"name":"Action 2"})).unwrap();
|
||||
|
||||
@@ -594,7 +594,8 @@ pub struct ToolOptions {
|
||||
#[serde(default = "one")]
|
||||
pub marquee_height: f32,
|
||||
/// Move tool: Auto-Select (with "layer" or "group" target) and Show Transform Controls.
|
||||
/// Auto-Select is on by default, as in current Photoshop; ⌘/Ctrl-click inverts it.
|
||||
/// Auto-Select is on with the "group" target by default, as in current Photoshop;
|
||||
/// ⌘/Ctrl-click inverts it.
|
||||
#[serde(default = "yes")]
|
||||
pub move_auto_select: bool,
|
||||
#[serde(default = "default_move_target")]
|
||||
@@ -706,7 +707,7 @@ fn default_crop_resolution_unit() -> String {
|
||||
}
|
||||
|
||||
fn default_move_target() -> String {
|
||||
"layer".into()
|
||||
"group".into()
|
||||
}
|
||||
|
||||
fn default_curve_fit() -> f32 {
|
||||
|
||||
@@ -415,6 +415,21 @@ Input calls (`ui.key`, `ui.type`, `ui.click`) now reply only after the app has p
|
||||
so a following `ui.inspect` observes their effect.
|
||||
|
||||
|
||||
## Photoshop Actions (.atn)
|
||||
|
||||
`photocraft-psd` reads and writes Photoshop Actions files (`atn`, version 16: Photoshop 6 and
|
||||
later); `photocraft-engine`'s `atn_cmds` maps their events onto commands (`actions.load`,
|
||||
`actions.save`; the Actions panel menu's Load/Save Actions…; `photocraft-cli batch --actions
|
||||
set.atn`). To see what a set holds (event ids, panel names, the parameter keys Photoshop
|
||||
recorded) when adding an event to the table:
|
||||
|
||||
```sh
|
||||
cargo run -p photocraft-psd --example atn_dump -- "Default Actions.atn"
|
||||
```
|
||||
|
||||
Events outside the table load as `actions.photoshopStep` steps that keep the descriptor
|
||||
verbatim (so Save Actions writes them back) and fail at playback with the step's Photoshop name.
|
||||
|
||||
## Remove Tool quality
|
||||
|
||||
`cargo run --release -p photocraft-engine --example remove_quality -- <dir> [out dir]` fills
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# File-format parity
|
||||
|
||||
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (Photoshop Actions `.atn` read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and
|
||||
tests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write
|
||||
@@ -130,7 +130,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.
|
||||
| LUTs `.cube` / `.3dl` / `.look` | R/W (Export Color Lookup) | R/W / R / R | `cms/src/lutfile.rs` |
|
||||
| Keyboard shortcuts `.kys` | R/W | R | `engine/src/kys.rs` |
|
||||
| ICC profiles | R | R | Own CMS |
|
||||
| Actions `.atn` | R/W | no | AUTO-219-2 |
|
||||
| Actions `.atn` | R/W | R/W | `psd/src/atn.rs` (version 16 sets, exact round trip), `engine/src/atn_cmds.rs` (90 Photoshop events ↔ commands; other steps kept verbatim). Panel menu, CLI `batch --actions set.atn`, `actions.load`/`actions.save`. Photoshop 5-era version 12 files unsupported (AUTO-219-2) |
|
||||
| Styles `.asl` | R/W | no | #1693 |
|
||||
| Contours `.shc`, custom shapes `.csh`, tool presets `.tpl` | R/W | no | FILE-215-15 |
|
||||
| Curves `.acv`, Levels `.alv`, other adjustment presets | R/W | not audited | |
|
||||
@@ -140,6 +140,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-12 | minor | Photoshop Actions `.atn`: read and write, 90 events mapped, the rest kept verbatim (AUTO-219-2) |
|
||||
| 2026-10-12 | minor | Palette BMPs open in Indexed Color mode (#3802) |
|
||||
| 2026-10-12 | minor | Save writes a JPEG at its own estimated quality and a WebP lossy or lossless as opened (#2399) |
|
||||
| 2026-10-11 | minor | D5100 image area and fitted-look preservation in Camera Raw tuning |
|
||||
|
||||
+10
-4
@@ -1,6 +1,6 @@
|
||||
# Where PhotoCraft falls short of Photoshop
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (G8: Character panel OpenType buttons landed, TYPE-218-5 stays partial; G8: triple-, quadruple- and five-click type selection landed, TYPE-218-8 done; Czech UI localization evidence added to G13; G14: D5100 crop and Camera Raw tuning validation) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; 2026-10-11: G8: Character panel OpenType buttons landed, TYPE-218-5 stays partial; G8: triple-, quadruple- and five-click type selection landed, TYPE-218-8 done; Czech UI localization evidence added to G13; G14: D5100 crop and Camera Raw tuning validation) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact
|
||||
on the way to beta. This is the work list agents pick from: take the highest-ranked entry that
|
||||
@@ -87,9 +87,14 @@ what an agent can't finish alone.
|
||||
- **Estimate:** 120–200 h.
|
||||
|
||||
### G11. Actions and scripting
|
||||
- **Missing:** document-independent action recording (AUTO-219-1), a full Actions panel with
|
||||
step toggles and .atn import (AUTO-219-2), replay tests (AUTO-219-4), Batch recursion and
|
||||
naming (AUTO-219-5), ExtendScript/UXP compatibility.
|
||||
- **Missing:** document-independent action recording (AUTO-219-1), the rest of the Actions
|
||||
panel: grouping by set, an Insert Stop item and editing the dialog toggle (AUTO-219-2), Batch
|
||||
recursion and naming (AUTO-219-5), ExtendScript/UXP compatibility. `.atn` steps outside the
|
||||
90 mapped events (Transform with scale or rotation, Apply Image, Save for Web, Place, smart
|
||||
object edits, Generative Fill…) load as kept Photoshop steps that fail at playback by name.
|
||||
- **Done 2026-10-12:** Load/Save Actions `.atn` in the panel menu, `batch --actions set.atn`
|
||||
and `actions.load`/`actions.save`; 90 Photoshop events map to commands both ways, Play and
|
||||
Stop steps included; layer steps replay by layer name in any document (AUTO-219-2 partial).
|
||||
- **Ahead of Photoshop:** CLI, MCP and the JSON control channel drive every command.
|
||||
- **Estimate:** 120–200 h. **Human:** whether to support a JavaScript scripting dialect at all
|
||||
(AGENTS.md forbids JS in the app).
|
||||
@@ -225,6 +230,7 @@ what an agent can't finish alone.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-12 | minor | G11: Load/Save Actions `.atn` landed (AUTO-219-2 partial); remaining panel work listed |
|
||||
| 2026-10-11 | minor | D5100 image area and Camera Raw tuning validation; G14 remains open |
|
||||
| 2026-10-11 | minor | G13: Czech dynamic UI text localized; engine messages and native review remain open |
|
||||
| 2026-10-11 | minor | G8: triple/quadruple/five-click type selection done (TYPE-218-8, #3493); Type evidence recounted |
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
|
||||
| [Tools](#tools) | 28 | 14 | 1 | |
|
||||
| [Workspace and UI](#workspace-and-ui) | 13 | 5 | 5 | settings that do nothing: 27 of 161 (target 0) |
|
||||
| [Type](#type) | 4 | 2 | 3 | |
|
||||
| [Automation](#automation) | 4 | 2 | 5 | 631 of 631 menu items live (100.0%) |
|
||||
| [Automation](#automation) | 4 | 3 | 4 | 631 of 631 menu items live (100.0%) |
|
||||
| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present |
|
||||
| [Distribution](#distribution) | 5 | 4 | 2 | |
|
||||
| [Open bugs](#open-bugs) | 29 | 2 | 1 | |
|
||||
@@ -228,7 +228,7 @@ Menu wiring (`docs/parity-checklist.md`): 631 of 631 menu items live (100.0%). T
|
||||
|---|---|---|---|---|
|
||||
| AUTO-1 | Every menu item dispatches a command id (UI, CLI, control channel and MCP share them) | done | | docs/parity-checklist.md: all menu items live; menus.rs is_live |
|
||||
| AUTO-219-1 | Record actions in a document-independent form (implicit layer, merged type keystrokes) | missing | [#219](https://github.com/storytold/photocraft/issues/219) | actions.rs:47 copies raw journal entries with explicit layer ids |
|
||||
| AUTO-219-2 | Actions panel: step and dialog toggles, reorder, delete a step, Stop, sets, .atn import | missing | [#219](https://github.com/storytold/photocraft/issues/219) | Panel deletes whole actions only (actions.rs:146) |
|
||||
| AUTO-219-2 | Actions panel: step and dialog toggles, reorder, delete a step, Stop, sets, .atn import | partial | [#219](https://github.com/storytold/photocraft/issues/219) | 2026-10-12: Load/Save Actions (.atn) in the panel menu, CLI batch and actions.load/save (atn_cmds.rs): 90 Photoshop events map to commands both ways, the rest are kept verbatim and fail at playback by name; step toggles, reorder and delete a step done; Stop steps play (actions.stopMessage) but there is no Insert Stop menu item; sets and dialog toggles are stored and round-trip but the panel neither groups by set nor edits the dialog toggle |
|
||||
| AUTO-219-3 | actions.record/stop/play/list commands for agents and the CLI | done | [#219](https://github.com/storytold/photocraft/issues/219) | actions.list/get/record/stop/play/delete in actions_cmds.rs; the panel, CLI and MCP share them. Nested steps pass the session authorize hook. |
|
||||
| AUTO-219-4 | Replay tests for crop, filters, selections and styled text on a second document | done | [#219](https://github.com/storytold/photocraft/issues/219) | actions_cmds.rs: a_recorded_edit_run_replays_on_a_second_document records a crop, a Gaussian Blur, a selection fill and faux-bold type on one document and replays all of them onto a second (plus the original layer/select/fill replay) |
|
||||
| AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds.rs:590-631 folder/array input, per-file errors; no recursion, template or cancel |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# PhotoCraft vs Adobe Photoshop: target-app parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The
|
||||
one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md);
|
||||
@@ -66,7 +66,7 @@ architecture and the PSD writer are the serial parts.
|
||||
| Filters and adjustments | 10% | every Filter and Image › Adjustments item live; Filter Gallery 47 looks | 100% | measured (menu catalog) |
|
||||
| File formats (usage-weighted) | 15% | 13 of 31 Photoshop formats supported in Photoshop's directions, 4 partial; the common ones (PSD/PSB, TIFF, JPEG, PNG, WebP) all present | ~80% (48% by count) | measured list, estimated weights ([file-format-parity.md](file-format-parity.md)) |
|
||||
| AI / generative | 10% | classical Select Subject/Sky, Remove tool, Content-Aware; no Generative Fill/Expand, Neural Filters, Sky Replacement, Super Zoom | ~15% | estimated |
|
||||
| Ecosystem (plug-ins, scripting, libraries) | 10% | WebAssembly plug-ins, CLI, MCP, actions; no .8BF, UXP/ExtendScript, .atn import, Libraries | ~20% | estimated |
|
||||
| Ecosystem (plug-ins, scripting, libraries) | 10% | WebAssembly plug-ins, CLI, MCP, actions, `.atn` load/save (90 events); no .8BF, UXP/ExtendScript, Libraries | ~20% | estimated |
|
||||
| **Weighted** | 100% | | **~76%** | |
|
||||
|
||||
## Ready for real work: ~45% (weighted)
|
||||
@@ -83,7 +83,7 @@ Weights reflect what a working Photoshop user depends on (photographers, retouch
|
||||
| Hardware | 5% | 50% | 80–150 | GPU compositor (wgpu), pen pressure on all desktops but tilt/rotation not on Windows, Wayland pen broken (#2622), no HDR/EDR output, monitor profile auto-detected on macOS only | [hardware-parity.md](hardware-parity.md) |
|
||||
| Localization | 5% | 55% | 80–140 | 7 of the 12 key languages at 100% of measured UI keys; Hindi, Arabic, Vietnamese absent; no RTL UI; engine messages English | [localization-parity.md](localization-parity.md) |
|
||||
| Platforms | 5% | 80% | 30–60 | macOS (notarized), Windows (unsigned), Linux (AppImage/deb/rpm/Flatpak), web, FreeBSD partial; no Windows ARM64, no in-app updates | [scorecard.md](scorecard.md#distribution) |
|
||||
| Ecosystem (plug-ins, scripting, presets, libraries) | 5% | 15% | 250–450 | No .8BF hosting (#2647), no UXP/ExtendScript, no .atn import; .abr/.grd/.pat/.aco/.ase/.cube supported | [gaps.md](gaps.md) |
|
||||
| Ecosystem (plug-ins, scripting, presets, libraries) | 5% | 15% | 250–450 | No .8BF hosting (#2647), no UXP/ExtendScript; .atn load/save (2026-10-12, 90 events, the rest kept verbatim), .abr/.grd/.pat/.aco/.ase/.cube supported | [gaps.md](gaps.md) |
|
||||
| AI features | 5% | 10% | 300–600 | No ML runtime at all (scorecard AUTO-219-7); classical substitutes only. Needs an owner decision and openly licensed models (#41) | [gaps.md](gaps.md) |
|
||||
| **Weighted** | 100% | **~46%** | **2,340–4,100** | | |
|
||||
|
||||
@@ -177,7 +177,7 @@ parity for the area and are already contained in the dimension rows above.
|
||||
| Vector shapes and paths | 55% | 80–140 | Pen, Direct/Path Selection, shapes, shape strokes. Freeform and Curvature Pen (#1054). Missing anchor tools, on-canvas corner radius, path-point nudge; shape parity tracking issue #2496 |
|
||||
| Colour management and modes | 70% | 60–100 | Own ICC engine, soft proof, CMYK/Lab/Indexed/Duotone/Multichannel; no Adobe CMYK profiles, no spot plates (FILE-215-17), monitor profile only at launch |
|
||||
| Camera Raw and computational photo (Photomerge, HDR, lens) | 45% | 120–200 | Raw for DNG/CR2/NEF/ARW/RW2/ORF/RAF(uncompressed)/PEF; no CR3; ACR dialog partial (no masking, calibration); generic lens profiles only |
|
||||
| Automation, actions, batch, scripting | 45% | 120–200 | CLI/MCP/control channel ahead of Photoshop; Actions panel and recording not document-independent (AUTO-219-1/2), no .atn, no ExtendScript/UXP |
|
||||
| Automation, actions, batch, scripting | 45% | 120–200 | CLI/MCP/control channel ahead of Photoshop; Actions panel and recording not document-independent (AUTO-219-1/2); `.atn` load/save since 2026-10-12 (90 events mapped, the rest kept verbatim); no ExtendScript/UXP |
|
||||
| File I/O | 60% | 300–500 | See [file-format-parity.md](file-format-parity.md) |
|
||||
| Print, export, Save for Web | 50% | 60–100 | JPEG Options dialog missing (FILE-215-19), no Photoshop PDF, no separations, Save for Web settings not remembered |
|
||||
| Video / timeline, data-driven graphics | 30% | 100–200 | Menu items live; frame model persists in `.pcraft`; no PSD video-layer mapping |
|
||||
@@ -450,7 +450,7 @@ filled bar. This extends UI reachability and does not claim Photoshop-authored s
|
||||
| Stability | Never-crash lint series, crash guard, `panic_hunt` fuzzing in the gate | medium-high | No field crash data yet. |
|
||||
| Camera RAW | DNG, CR2, Sony ARW (lossless + compressed), Nikon NEF (lossless + lossy compressed), RW2, uncompressed ORF; 2026-10-09: uncompressed Fujifilm RAF, Bayer and X-Trans (edge-directed X-Trans demosaic; 26 MP X-Trans develop 306 ms on 12 cores) | medium | CR3, compressed RAF and Nikon "lossy after split" still open (#50). Non-DNG cameras have no calibration: their colour (matrix + tone curve) is fitted per file to the camera's embedded JPEG, with the neutral sRGB-primaries fallback when the fit doesn't clearly help (2026-10-08: 8 D3200 NEFs, mean ΔE vs the camera JPEG 11.6–26.0 → 1.0–7.5); measured per-model calibration still open. |
|
||||
| AI / generative | none | ~0% | Deferred by decision (#41). |
|
||||
| Ecosystem | Sandboxed WebAssembly plug-ins instead of .8BF; no ExtendScript/UXP/.atn; no Adobe Fonts/Libraries/cloud docs | low | By design for 8BF; scripting compatibility open. |
|
||||
| Ecosystem | Sandboxed WebAssembly plug-ins instead of .8BF; `.atn` actions load and save (2026-10-12); no ExtendScript/UXP; no Adobe Fonts/Libraries/cloud docs | low | By design for 8BF; scripting compatibility open. |
|
||||
| Platforms | macOS (notarized), Windows, Linux (AppImage/deb/rpm/Flatpak bundle), web | medium-high | Flathub later (#173); Windows signing material pending. |
|
||||
| Localisation | 2026-10-07: 10 UI languages; menu, `tl!`, blend mode, preference and brush-section coverage enforced by tests; live switching and scoped Preferences previews | medium | Engine errors/status messages still partly English; CJK web fonts, browser-locale detection, and RTL remain open. |
|
||||
|
||||
@@ -563,6 +563,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-12 | minor | Photoshop Actions `.atn` load and save (90 events mapped both ways); percentages unchanged |
|
||||
| 2026-10-10 | minor | Added measured Tilt-Shift computation/filtered-proxy gains and inconclusive cases; parity percentages and budgets unchanged |
|
||||
| 2026-10-10 | minor | Readiness-by-audience table: percent and hours for full, mainstream and essentials; full number confirmed as the additive weighted sum over dimensions (46%, reported ~45%) |
|
||||
| 2026-10-10 | minor | Added mainstream-practitioner (~43%) and essentials-user (~61%) numbers with written weights and discounts; full ready-for-real-work rechecked against its written weights (46%, reported ~45%), unchanged |
|
||||
|
||||
@@ -21,9 +21,9 @@ note = "actions.rs:47 copies raw journal entries with explicit layer ids"
|
||||
[[item]]
|
||||
id = "AUTO-219-2"
|
||||
target = "Actions panel: step and dialog toggles, reorder, delete a step, Stop, sets, .atn import"
|
||||
status = "missing"
|
||||
status = "partial"
|
||||
issue = 219
|
||||
note = "Panel deletes whole actions only (actions.rs:146)"
|
||||
note = "2026-10-12: Load/Save Actions (.atn) in the panel menu, CLI batch and actions.load/save (atn_cmds.rs): 90 Photoshop events map to commands both ways, the rest are kept verbatim and fail at playback by name; step toggles, reorder and delete a step done; Stop steps play (actions.stopMessage) but there is no Insert Stop menu item; sets and dialog toggles are stored and round-trip but the panel neither groups by set nor edits the dialog toggle"
|
||||
|
||||
[[item]]
|
||||
id = "AUTO-219-3"
|
||||
|
||||
Reference in new issue
Block a user