mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge branch 'main' into perf/adopt-retained-ui-20261129
This commit is contained in:
11 files changed
+255
-38
No files matched your search
@@ -573,7 +573,7 @@ fn doc_export_layers_reports_skips_in_workspace_and_trusted_sessions() {
|
||||
let mut h =
|
||||
if trusted { Headless::trusted_local() } else { Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&base), Some(&base)).unwrap()) };
|
||||
h.handle("doc.new", json!({"width": 4, "height": 4, "background": "white", "name": "card"})).unwrap();
|
||||
let adjustment = h.handle("engine.execute", json!({"command": "layer.newAdjustmentLayer.levels"})).unwrap()["layer"].clone();
|
||||
h.handle("engine.execute", json!({"command": "layer.newAdjustmentLayer.levels"})).unwrap();
|
||||
h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"name": "Levels"}})).unwrap();
|
||||
let hidden = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Hidden"}})).unwrap()["layer"].clone();
|
||||
h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"visible": false}})).unwrap();
|
||||
@@ -586,23 +586,22 @@ fn doc_export_layers_reports_skips_in_workspace_and_trusted_sessions() {
|
||||
let reply: Value = serde_json::from_slice(&output).unwrap();
|
||||
assert_eq!(reply["id"], 8491);
|
||||
assert_eq!(reply["ok"], true, "{reply}");
|
||||
assert_eq!(reply["result"]["files"], json!([format!("{out_dir}/card_0002_Background.png")]));
|
||||
assert_eq!(reply["result"]["files"], json!([format!("{out_dir}/card_0001_Levels.png"), format!("{out_dir}/card_0002_Background.png")]));
|
||||
if !trusted {
|
||||
assert_eq!(reply["result"]["count"], 1);
|
||||
assert_eq!(reply["result"]["count"], 2);
|
||||
}
|
||||
assert_eq!(
|
||||
reply["result"]["skipped"],
|
||||
json!([
|
||||
{"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"},
|
||||
{"layer": adjustment, "name": "Levels", "reason": "adjustment layer has no pixels of its own"}
|
||||
{"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"}
|
||||
])
|
||||
);
|
||||
assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 1);
|
||||
assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 2);
|
||||
let mut h = h.into_inner().unwrap();
|
||||
let all_dir = base.join("all").to_string_lossy().into_owned();
|
||||
let all = h.export_layers(None, &all_dir, &json!({"visibleOnly": false})).unwrap();
|
||||
assert_eq!(all["files"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(all["skipped"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(all["files"].as_array().unwrap().len(), 3);
|
||||
assert_eq!(all["skipped"].as_array().unwrap().len(), 0);
|
||||
// Workspace no-overwrite errors still fail and remove only newly created files.
|
||||
if !trusted {
|
||||
let collision = base.join("collision");
|
||||
|
||||
@@ -983,22 +983,22 @@ async fn doc_export_layers_reports_skipped_layers() {
|
||||
let hidden = json_of(&call(&client, "command_run", json!({"id": "layer.new.layer", "params": {"name": "Hidden"}})).await)["layer"].clone();
|
||||
json_of(&call(&client, "command_run", json!({"id": "layer.setProps", "params": {"visible": false}})).await);
|
||||
let result = json_of(&call(&client, "doc_export_layers", json!({"dir": "layers"})).await);
|
||||
assert_eq!(result["count"], 1);
|
||||
assert_eq!(result["files"], json!(["layers/card_0002_Background.png"]));
|
||||
assert_eq!(result["count"], 2);
|
||||
assert_eq!(result["files"], json!(["layers/card_0001_Levels_α.png", "layers/card_0002_Background.png"]));
|
||||
assert_eq!(
|
||||
result["skipped"],
|
||||
json!([
|
||||
{"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"},
|
||||
{"layer": adjustment, "name": "Levels/α", "reason": "adjustment layer has no pixels of its own"}
|
||||
{"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"}
|
||||
])
|
||||
);
|
||||
let all = json_of(&call(&client, "doc_export_layers", json!({"dir": "all", "visible_only": false})).await);
|
||||
assert_eq!(all["count"], 2);
|
||||
assert_eq!(all["skipped"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(std::fs::read_dir(base.join("layers")).unwrap().count(), 1);
|
||||
assert_eq!(std::fs::read_dir(base.join("all")).unwrap().count(), 2);
|
||||
assert_eq!(all["count"], 3);
|
||||
assert_eq!(all["skipped"].as_array().unwrap().len(), 0);
|
||||
assert_eq!(std::fs::read_dir(base.join("layers")).unwrap().count(), 2);
|
||||
assert_eq!(std::fs::read_dir(base.join("all")).unwrap().count(), 3);
|
||||
// Every top-level layer is still accounted for when none can be exported.
|
||||
json_of(&call(&client, "command_run", json!({"id": "layer.setProps", "params": {"layer": background, "visible": false}})).await);
|
||||
json_of(&call(&client, "command_run", json!({"id": "layer.setProps", "params": {"layer": adjustment, "visible": false}})).await);
|
||||
let none = json_of(&call(&client, "doc_export_layers", json!({"dir": "none"})).await);
|
||||
assert_eq!(none["files"], json!([]));
|
||||
assert_eq!(none["count"], 0);
|
||||
|
||||
@@ -887,7 +887,8 @@ fn toggle_last_state(s: &mut Session) -> Result<Value> {
|
||||
/// Edit › Transform › Again: replay the last `edit.transform` on the selected layers (#6501).
|
||||
fn transform_again(s: &mut Session) -> Result<Value> {
|
||||
let ids = s.active().map(crate::transform_cmds::selection_targets).unwrap_or_default();
|
||||
let p = transform_again_params(s, &ids)?;
|
||||
let mut p = transform_again_params(s, &ids)?;
|
||||
p["stepName"] = json!(crate::transform_cmds::TRANSFORM_AGAIN);
|
||||
s.execute("edit.transform", p)
|
||||
}
|
||||
|
||||
|
||||
@@ -489,6 +489,10 @@ mod layers_to_files_single_layer_tests;
|
||||
#[path = "file_cmds/layers_to_files_png_names_tests.rs"]
|
||||
mod layers_to_files_png_names_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "file_cmds/layers_to_files_adjustment_tests.rs"]
|
||||
mod layers_to_files_adjustment_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "file_cmds/place_job_tests.rs"]
|
||||
mod place_job_tests;
|
||||
|
||||
@@ -84,7 +84,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&
|
||||
}
|
||||
let mut report = LayerExportReport::default();
|
||||
let mut planned = Vec::new();
|
||||
plan_layer_exports(&doc.layers, &mut Vec::new(), "", visible_only, &mut planned, &mut report.skipped)?;
|
||||
plan_layer_exports(&doc.layers, &mut Vec::new(), "", &format, visible_only, &mut planned, &mut report.skipped)?;
|
||||
// PNG file names use dashes for spaces (measured); the other formats keep them.
|
||||
let part = |text: &str| if format == "png" { sanitize(text).replace(' ', "-") } else { sanitize(text) };
|
||||
// The prefix is optional; only the layer name needs the empty-name fallback.
|
||||
@@ -165,6 +165,7 @@ fn plan_layer_exports<'a>(
|
||||
layers: &'a [Layer],
|
||||
groups: &mut Vec<&'a Layer>,
|
||||
path: &str,
|
||||
format: &str,
|
||||
visible_only: bool,
|
||||
planned: &mut Vec<PlannedLayer<'a>>,
|
||||
skipped: &mut Vec<SkippedExportLayer>,
|
||||
@@ -182,20 +183,31 @@ fn plan_layer_exports<'a>(
|
||||
continue;
|
||||
}
|
||||
groups.push(l);
|
||||
let r = plan_layer_exports(children, groups, &format!("{path}{number:04}s_"), visible_only, planned, skipped);
|
||||
let r = plan_layer_exports(children, groups, &format!("{path}{number:04}s_"), format, visible_only, planned, skipped);
|
||||
groups.pop();
|
||||
r?;
|
||||
continue;
|
||||
}
|
||||
// Every layer takes its index, even one skipped as hidden or as an adjustment, so a file
|
||||
// keeps the same number whether Visible Layers Only is on or off (#13959).
|
||||
// keeps the same number whether Visible Layers Only is on or off (#13959). An adjustment
|
||||
// layer has no pixels of its own: for PNG and JPEG it exports like an empty layer under its
|
||||
// own number, as measured (#13966); the other formats were not measured and still skip it,
|
||||
// leaving its number unused.
|
||||
let number = format!("{path}{art:04}");
|
||||
art += 1;
|
||||
if !l.visible && visible_only {
|
||||
skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" });
|
||||
continue;
|
||||
}
|
||||
if matches!(l.content, LayerContent::Adjustment(_)) {
|
||||
// Only a top-level adjustment whose mask hides nothing was measured: the white mask every
|
||||
// new one gets. One whose mask hides something (painted, or made from a selection), that
|
||||
// has a vector mask or that sits in a group was not, so it keeps today's skip in every format.
|
||||
let masked = l.vector_mask.is_some()
|
||||
|| l.mask
|
||||
.as_ref()
|
||||
.is_some_and(|m| m.enabled && (m.surface.default_pixel().first().is_some_and(|v| *v < 1.0) || !m.surface.content_bounds().is_empty()));
|
||||
let measured = !masked && groups.is_empty() && matches!(format, "png" | "jpg" | "jpeg");
|
||||
if matches!(l.content, LayerContent::Adjustment(_)) && !measured {
|
||||
skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" });
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Layers to Files writes a file for an adjustment layer, like an empty layer, for PNG and JPEG
|
||||
//! (#13966); the formats that were not measured still skip it.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn tmp(name: &str) -> String {
|
||||
let d = std::env::temp_dir().join(format!("photocraft-l2f-adjustment-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// A 100 x 80 document: `Background`, then `Empty`, then a Levels adjustment layer named `Levels 1`.
|
||||
fn session() -> Session {
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Empty"})).unwrap();
|
||||
s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap();
|
||||
s.execute("layer.setProps", json!({"name": "Levels 1"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn decode_file(dir: &str, name: &str) -> photocraft_codecs::Image {
|
||||
photocraft_codecs::decode(&std::fs::read(std::path::Path::new(dir).join(name)).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_with_trim_writes_a_full_canvas_transparent_file_for_the_adjustment() {
|
||||
let dir = tmp("png");
|
||||
let mut s = session();
|
||||
let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "trim": true})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect();
|
||||
let names: Vec<&str> = files.iter().map(|f| f.rsplit(['/', '\\']).next().unwrap()).collect();
|
||||
assert_eq!(names, ["doc_0000_Levels-1.png", "doc_0001_Empty.png", "doc_0002_Background.png"]);
|
||||
let img = decode_file(&dir, "doc_0000_Levels-1.png");
|
||||
assert_eq!((img.width(), img.height()), (100, 80));
|
||||
let rgba = img.to_rgba8();
|
||||
assert!(rgba.chunks(4).all(|p| p[3] == 0), "every pixel is fully transparent");
|
||||
let empty = decode_file(&dir, "doc_0001_Empty.png");
|
||||
assert_eq!((empty.width(), empty.height()), (100, 80));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_writes_a_white_full_canvas_image_for_the_adjustment() {
|
||||
let dir = tmp("jpeg");
|
||||
let mut s = session();
|
||||
let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "format": "jpg"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([]));
|
||||
let img = decode_file(&dir, "doc_0000_Levels 1.jpg");
|
||||
assert_eq!((img.width(), img.height()), (100, 80));
|
||||
let rgba = img.to_rgba8();
|
||||
assert!(rgba.chunks(4).all(|p| p[..3].iter().all(|&c| c >= 253)), "white");
|
||||
let empty = decode_file(&dir, "doc_0001_Empty.jpg").to_rgba8();
|
||||
assert_eq!(rgba, empty, "the same as the empty layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_adjustment_is_skipped_by_visible_only() {
|
||||
let dir = tmp("hidden");
|
||||
let mut s = session();
|
||||
let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0;
|
||||
s.execute("layer.setProps", json!({"visible": false})).unwrap();
|
||||
let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "hidden by visibleOnly"}]));
|
||||
assert_eq!(r["files"].as_array().unwrap().len(), 2);
|
||||
let all = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "visibleOnly": false})).unwrap();
|
||||
assert_eq!(all["skipped"], json!([]));
|
||||
assert_eq!(all["files"].as_array().unwrap().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_formats_still_skip_the_adjustment_and_keep_its_number() {
|
||||
// Only PNG and JPEG were measured; PSD (like TIFF, BMP, Targa and PDF) keeps today's skip.
|
||||
let dir = tmp("psd");
|
||||
let mut s = session();
|
||||
let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0;
|
||||
let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "format": "psd"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "adjustment layer has no pixels of its own"}]));
|
||||
let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect();
|
||||
let names: Vec<&str> = files.iter().map(|f| f.rsplit(['/', '\\']).next().unwrap()).collect();
|
||||
assert_eq!(names, ["doc_0001_Empty.psd", "doc_0002_Background.psd"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_adjustment_whose_mask_hides_part_of_it_is_still_skipped() {
|
||||
// Not measured: a mask that hides something (here made from a selection) keeps today's skip.
|
||||
let dir = tmp("masked");
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 50, "height": 80})).unwrap();
|
||||
s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap();
|
||||
let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0;
|
||||
let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "adjustment layer has no pixels of its own"}]));
|
||||
assert_eq!(r["files"].as_array().unwrap().len(), 1, "only the Background");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_adjustment_with_a_vector_mask_is_still_skipped() {
|
||||
let dir = tmp("vector-masked");
|
||||
let mut s = crate::session();
|
||||
s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap();
|
||||
let path = json!({"subpaths": [{"closed": true, "knots": [[0, 0], [50, 0], [50, 80], [0, 80]]}]});
|
||||
s.execute("layer.newAdjustmentLayer.levels", json!({"path": path})).unwrap();
|
||||
let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0;
|
||||
let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "format": "jpg"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "adjustment layer has no pixels of its own"}]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_adjustment_inside_a_group_is_still_skipped() {
|
||||
// Not measured: an adjustment in a group keeps today's skip, and its number.
|
||||
let mut s = session();
|
||||
s.edit("group the adjustment", |doc, _| {
|
||||
let levels = doc.layers.pop().unwrap();
|
||||
doc.layers.push(Layer::group("Grp", vec![levels]));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let adjustment = s.active().unwrap().doc.layers.last().unwrap().children().unwrap()[0].id.0;
|
||||
let r = s.execute("file.export.layersToFiles", json!({"dir": tmp("grouped"), "prefix": "doc"})).unwrap();
|
||||
assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "adjustment layer has no pixels of its own"}]));
|
||||
assert_eq!(r["files"].as_array().unwrap().len(), 2, "Empty and Background");
|
||||
}
|
||||
@@ -2749,7 +2749,7 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() {
|
||||
for depth in [8, 16, 32] {
|
||||
let dir = tmp(&format!("skipped-layers-{depth}"));
|
||||
let mut s = session(4, 4, depth);
|
||||
let adjustment = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].clone();
|
||||
s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap();
|
||||
s.execute("layer.setProps", json!({"name": "Levels/α"})).unwrap();
|
||||
let hidden = s.execute("layer.new.layer", json!({"name": "Levels/α"})).unwrap()["layer"].clone();
|
||||
s.execute("layer.setProps", json!({"visible": false})).unwrap();
|
||||
@@ -2758,22 +2758,16 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() {
|
||||
assert_eq!(
|
||||
result["skipped"],
|
||||
json!([
|
||||
{"layer": hidden, "name": "Levels/α", "reason": "hidden by visibleOnly"},
|
||||
{"layer": adjustment, "name": "Levels/α", "reason": "adjustment layer has no pixels of its own"}
|
||||
{"layer": hidden, "name": "Levels/α", "reason": "hidden by visibleOnly"}
|
||||
])
|
||||
);
|
||||
assert_eq!(result["files"], json!([join(&dir, "doc_0002_Background.png")]));
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
|
||||
assert_eq!(result["files"], json!([join(&dir, "doc_0001_Levels_α.png"), join(&dir, "doc_0002_Background.png")]));
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2);
|
||||
assert_eq!(s.active().unwrap().doc.layers.len(), before.layers.len());
|
||||
assert!(!s.active().unwrap().doc.layer(LayerId(hidden.as_u64().unwrap())).unwrap().visible);
|
||||
let all = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "visibleOnly": false})).unwrap();
|
||||
assert_eq!(
|
||||
all["skipped"],
|
||||
json!([
|
||||
{"layer": adjustment, "name": "Levels/α", "reason": "adjustment layer has no pixels of its own"}
|
||||
])
|
||||
);
|
||||
assert_eq!(all["files"], json!([join(&dir, "all_0000_Levels_α.png"), join(&dir, "all_0002_Background.png")]));
|
||||
assert_eq!(all["skipped"], json!([]));
|
||||
assert_eq!(all["files"], json!([join(&dir, "all_0000_Levels_α.png"), join(&dir, "all_0001_Levels_α.png"), join(&dir, "all_0002_Background.png")]));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ fn has_layer(s: &Session) -> std::result::Result<(), String> {
|
||||
|
||||
/// The History step name of a shape-tool bounding box scale (`edit.transform` `stepName`).
|
||||
pub const TRANSFORM_PATH: &str = "Transform Path";
|
||||
pub(crate) const TRANSFORM_AGAIN: &str = "Transform Again";
|
||||
|
||||
fn bad(msg: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: "edit.transform".into(), msg: msg.into() }
|
||||
@@ -858,12 +859,12 @@ fn with_panel_target(s: &Session, p: &Value) -> Value {
|
||||
}
|
||||
|
||||
fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The shape tools' bounding box scales live shapes with this command and names the step as
|
||||
// the reference does. Passed in, not renamed after: the edit may land later as a job.
|
||||
// Pass the history label to the edit job so it is used when the transform lands.
|
||||
let step_name = match p.get("stepName") {
|
||||
None | Some(Value::Null) => "Free Transform",
|
||||
Some(Value::String(n)) if n == TRANSFORM_PATH => TRANSFORM_PATH,
|
||||
Some(_) => return Err(bad("`stepName` must be \"Transform Path\"")),
|
||||
Some(Value::String(n)) if n == TRANSFORM_AGAIN => TRANSFORM_AGAIN,
|
||||
Some(_) => return Err(bad("`stepName` must be \"Transform Path\" or \"Transform Again\"")),
|
||||
};
|
||||
let p = &with_panel_target(s, p);
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
@@ -1037,7 +1038,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
label: "Free Transform",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"layer":id?,"layers":[id,…]? (several layers moved by one box, one step; default with neither = the selected layers, as Photoshop's Free Transform with several selected; refused as locked when the Background is among several),"rect":[x0,y0,x1,y1]? (source frame; default = the layers' content ∩ selection),"quad":[[x,y]×4]? (where the frame's corners go, clockwise from top-left),"matrix":[a,b,c,d,e,f]? (affine alternative),"scaleX":%?,"scaleY":%?,"rotate":deg?,"dx":px?,"dy":px?,"reference":"center|topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight"|[x,y]="center" (relative alternative: scale and rotate about this point, then move),"interpolation":"bicubic|bilinear|nearest|bicubicSharper|bicubicSmoother|bicubicAutomatic"="bicubic" (Photoshop's bicubic variants render as Bicubic),"stepName":"Transform Path"? (History step name; the shape tools' bounding box sends it; default "Free Transform"; any other value is refused),"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, an alpha channel or the Quick Mask transforms alone; a linked mask moves with its layer)}"##,
|
||||
params: r##"{"layer":id?,"layers":[id,…]? (several layers moved by one box, one step; default with neither = the selected layers, as Photoshop's Free Transform with several selected; refused as locked when the Background is among several),"rect":[x0,y0,x1,y1]? (source frame; default = the layers' content ∩ selection),"quad":[[x,y]×4]? (where the frame's corners go, clockwise from top-left),"matrix":[a,b,c,d,e,f]? (affine alternative),"scaleX":%?,"scaleY":%?,"rotate":deg?,"dx":px?,"dy":px?,"reference":"center|topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight"|[x,y]="center" (relative alternative: scale and rotate about this point, then move),"interpolation":"bicubic|bilinear|nearest|bicubicSharper|bicubicSmoother|bicubicAutomatic"="bicubic" (Photoshop's bicubic variants render as Bicubic),"stepName":"Transform Path|Transform Again"? (History step name; default "Free Transform"),"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, an alpha channel or the Quick Mask transforms alone; a linked mask moves with its layer)}"##,
|
||||
enabled: has_layer,
|
||||
journal: true,
|
||||
run: transform,
|
||||
|
||||
@@ -195,6 +195,7 @@ mod smart_rerender_fallback;
|
||||
mod style_and_align;
|
||||
mod svg_smart_object;
|
||||
mod tone_target_picker;
|
||||
mod transform_again_history_name_tests;
|
||||
mod transform_budget_unclamped;
|
||||
mod type_format_targets;
|
||||
mod type_postscript_font;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
use photocraft_doc::LayerId;
|
||||
use photocraft_engine::Session;
|
||||
use photocraft_geom::Rect;
|
||||
use serde_json::json;
|
||||
|
||||
fn skewed_document(layer_count: usize) -> (Session, Vec<LayerId>) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 1000, "height": 700})).unwrap();
|
||||
let mut layers = Vec::new();
|
||||
for (name, rect, color) in
|
||||
[("A", Rect::new(100, 100, 300, 300), [1.0, 0.0, 0.0, 1.0]), ("B", Rect::new(500, 300, 800, 500), [0.0, 0.0, 1.0, 1.0])].into_iter().take(layer_count)
|
||||
{
|
||||
let made = s.execute("layer.new.layer", json!({"name": name})).unwrap();
|
||||
let id = LayerId(made["layer"].as_u64().unwrap());
|
||||
s.edit("Paint rectangle", |doc, _| {
|
||||
doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(rect, &color);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
layers.push(id);
|
||||
}
|
||||
s.execute("layer.select", json!({"layer": layers[0].0})).unwrap();
|
||||
for id in &layers[1..] {
|
||||
s.execute("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap();
|
||||
}
|
||||
s.execute("edit.transform", json!({"rect": [100, 100, 800, 500], "quad": [[200, 100], [900, 100], [800, 500], [100, 500]], "interpolation": "nearest"}))
|
||||
.unwrap();
|
||||
(s, layers)
|
||||
}
|
||||
|
||||
fn bounds(s: &Session, layers: &[LayerId]) -> Vec<Rect> {
|
||||
let doc = &s.active().unwrap().doc;
|
||||
layers.iter().map(|id| doc.layer(*id).unwrap().surface().unwrap().content_bounds()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_again_adds_one_named_undo_step_for_single_and_multiple_layers() {
|
||||
for layer_count in [1, 2] {
|
||||
let (mut s, layers) = skewed_document(layer_count);
|
||||
let state = s.active().unwrap();
|
||||
let before = state.doc.clone();
|
||||
let previous_steps = state.history.past_len();
|
||||
assert_eq!(state.history.undo_label(), Some("Free Transform"));
|
||||
|
||||
s.execute("edit.transform.again", json!({})).unwrap();
|
||||
let state = s.active().unwrap();
|
||||
assert_eq!(state.history.past_len(), previous_steps + 1);
|
||||
assert_eq!(state.history.undo_label(), Some("Transform Again"));
|
||||
assert_eq!(bounds(&s, &layers), [Rect::new(200, 100, 500, 300), Rect::new(500, 300, 900, 500)][..layer_count]);
|
||||
|
||||
assert_eq!(s.execute("history.undo", json!({})).unwrap(), json!(true));
|
||||
let state = s.active().unwrap();
|
||||
assert_eq!(state.doc, before);
|
||||
assert_eq!(state.history.past_len(), previous_steps);
|
||||
assert_eq!(state.history.redo_label(), Some("Transform Again"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recorded_transform_again_plays_the_concrete_transform_once() {
|
||||
let (mut s, layers) = skewed_document(2);
|
||||
s.execute("prefs.set", json!({"path": "actions.createSingleHistoryState", "value": false})).unwrap();
|
||||
s.execute("actions.record", json!({"name": "Repeat skew"})).unwrap();
|
||||
s.execute("edit.transform.again", json!({})).unwrap();
|
||||
s.execute("actions.stop", json!({})).unwrap();
|
||||
let repeated_bounds = bounds(&s, &layers);
|
||||
let recorded = s.execute("actions.get", json!({"action": "Repeat skew"})).unwrap();
|
||||
let [step] = recorded["steps"].as_array().unwrap().as_slice() else { panic!("expected a single recorded step: {recorded}") };
|
||||
assert_eq!(step[0], "edit.transform");
|
||||
|
||||
assert_eq!(s.execute("history.undo", json!({})).unwrap(), json!(true));
|
||||
let before = s.active().unwrap().history.past_len();
|
||||
let played = s.execute("actions.play", json!({"action": "Repeat skew"})).unwrap();
|
||||
assert_eq!(played["ran"], 1, "{played}");
|
||||
assert!(played.get("failed").is_none(), "{played}");
|
||||
assert_eq!(bounds(&s, &layers), repeated_bounds);
|
||||
let state = s.active().unwrap();
|
||||
assert_eq!(state.history.past_len(), before + 1);
|
||||
assert_eq!(state.history.undo_label(), Some("Transform Again"));
|
||||
}
|
||||
@@ -559,7 +559,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl
|
||||
| `doc.open` / `doc.new` | `{path, approveHighMemory? (false)}` / `file.new` params (`approveHighMemory` is the same one-shot PSD/PSB consent as the `file.openAs` command; see [development.md](development.md) for the structured refusal fields) |
|
||||
| `doc.place` | `{path, scale? (percent), fit? (true), center? ([x, y]), approveHighMemory? (false), index?}`: places a file as a Smart Object layer above the active one and returns `{layer, scale, bounds}`. `path` resolves beneath the read root, so this is the capability-scoped `file.placeEmbedded` — that command itself still refuses an ambient path. `approveHighMemory` is refused unless it is a boolean |
|
||||
| `doc.replaceSmartObject` | `{path, layer? (id or name; default the active layer), index?}` → the command's `{layer, instances}`: replaces a Smart Object's contents (one history step, transform and filters kept). `path` resolves beneath the read root, so this is the capability-scoped `layer.smartObjects.replaceContents`, which itself still refuses an ambient path (#8061) |
|
||||
| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported layer, named like `file.export.layersToFiles` names them: `<prefix>_<index>_<name>` at the top level and `<prefix>_<group index>s_<index>_<name>` inside a group (one `<index>s_` per group level), art layers and groups counted separately at each level. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups are walked: a group gets no file, each layer in it does (inside its groups in the file), and with `visibleOnly` the layers of a hidden group are skipped as `"hidden by visibleOnly"`. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips |
|
||||
| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported layer, named like `file.export.layersToFiles` names them: `<prefix>_<index>_<name>` at the top level and `<prefix>_<group index>s_<index>_<name>` inside a group (one `<index>s_` per group level), art layers and groups counted separately at each level. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or, for formats other than PNG and JPEG, `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden layers. For PNG and JPEG a top-level adjustment layer whose mask hides nothing is exported like an empty layer; one with a mask that hides something, a vector mask, or inside a group is still skipped. Groups are walked: a group gets no file, each layer in it does (inside its groups in the file), and with `visibleOnly` the layers of a hidden group are skipped as `"hidden by visibleOnly"`. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips |
|
||||
| `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command |
|
||||
| `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root |
|
||||
| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, dpxBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?, pcraftFullComposite?, maximizeCompatibility?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `dpxBits` selects 8, 10, 12 or 16 bits per sample for DPX (unset: 8 for an 8-bit document, otherwise 16); `tgaBits` 24 or 32 sets a TGA's bits per pixel, `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, and `maximizeCompatibility: false` writes a layered PSD/PSB with Photoshop's placeholder instead of the merged image, except for Bitmap, Indexed Color and Duotone documents, as `app.save` does; `pdfSpotPlates: false` leaves a PDF's spot plates out, which are written by default, and refuses a Multichannel document, which has no image to write without them; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty |
|
||||
|
||||
Reference in new issue
Block a user