mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge remote-tracking branch 'origin/main' into fix/tiff-alpha-compression
Batch and Image Processor params keep main's includeSubfolders and this branch's tiffCompression. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
bb8fc93908
47 files changed
+1192
-97
No files matched your search
@@ -974,13 +974,106 @@ pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result<Vec<String>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// One input of a batch run: the file, and the folder it sits in relative to the input folder
|
||||
/// (`""` at the top level, `"a/b"` two levels down), which its result keeps under `output`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct BatchInput {
|
||||
pub path: String,
|
||||
pub rel_dir: String,
|
||||
}
|
||||
|
||||
/// Subfolders below a batch input folder are walked at most this deep ("Include All Subfolders").
|
||||
pub(crate) const MAX_SUBFOLDER_DEPTH: usize = 32;
|
||||
/// A batch over subfolders lists at most this many files; a larger tree is an error, not a run
|
||||
/// that silently stops partway.
|
||||
pub(crate) const MAX_SUBFOLDER_FILES: usize = 100_000;
|
||||
|
||||
/// [`batch_inputs`] for the commands whose Photoshop dialog has "Include All Subfolders" (Batch,
|
||||
/// Image Processor): with `"includeSubfolders": true` a folder input also yields the images in its
|
||||
/// subfolders, each tagged with its relative folder. `output` (when inside the input folder, as
|
||||
/// the dialog's default `<input>/batch` is) is not walked, so a rerun doesn't process its results.
|
||||
pub(crate) fn batch_inputs_tree(p: &Value, cmd: &str, output: &str) -> Result<Vec<BatchInput>> {
|
||||
let recurse = match p.get("includeSubfolders") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "\"includeSubfolders\" must be true or false".into() }),
|
||||
};
|
||||
match p.get("input").or_else(|| p.get("files")) {
|
||||
Some(Value::String(dir)) if recurse => list_images_tree(dir, output, cmd),
|
||||
_ => Ok(batch_inputs(p, cmd)?.into_iter().map(|path| BatchInput { path, rel_dir: String::new() }).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The images under `dir` and its subfolders: each folder's files sorted by name, then its
|
||||
/// subfolders in name order (depth first). Bounded by [`MAX_SUBFOLDER_DEPTH`] and
|
||||
/// [`MAX_SUBFOLDER_FILES`]; a folder reached twice (a symlink loop) is walked once, and `skip`
|
||||
/// (the output folder) is left out.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn list_images_tree(dir: &str, skip: &str, cmd: &str) -> Result<Vec<BatchInput>> {
|
||||
use std::path::{Path, PathBuf};
|
||||
let canon = |p: &Path| std::fs::canonicalize(p).ok();
|
||||
let root = Path::new(dir);
|
||||
let root_canon = canon(root).ok_or_else(|| EngineError::Other(format!("{dir}: cannot open the folder")))?;
|
||||
let skip = if skip.is_empty() { None } else { canon(Path::new(skip)) };
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
seen.insert(root_canon);
|
||||
let mut out = Vec::new();
|
||||
// Depth first with an explicit stack (no recursion): (folder, relative folder, depth).
|
||||
let mut stack: Vec<(PathBuf, String, usize)> = vec![(root.to_path_buf(), String::new(), 0)];
|
||||
while let Some((folder, rel, depth)) = stack.pop() {
|
||||
let shown = folder.to_string_lossy().into_owned();
|
||||
// The top folder must be readable; a subfolder that isn't is skipped.
|
||||
let files = match list_images(&shown) {
|
||||
Ok(f) => f,
|
||||
Err(e) if depth == 0 => return Err(e),
|
||||
Err(_) => continue,
|
||||
};
|
||||
if out.len().saturating_add(files.len()) > MAX_SUBFOLDER_FILES {
|
||||
return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("{dir} holds more than {MAX_SUBFOLDER_FILES} images with its subfolders") });
|
||||
}
|
||||
out.extend(files.into_iter().map(|path| BatchInput { path, rel_dir: rel.clone() }));
|
||||
if depth >= MAX_SUBFOLDER_DEPTH {
|
||||
continue;
|
||||
}
|
||||
let Ok(rd) = std::fs::read_dir(&folder) else { continue };
|
||||
let mut subs: Vec<(String, PathBuf)> = rd
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.is_dir())
|
||||
.filter_map(|p| Some((p.file_name()?.to_string_lossy().into_owned(), p)))
|
||||
.collect();
|
||||
subs.sort();
|
||||
// Pushed in reverse so the stack pops them in name order.
|
||||
for (name, sub) in subs.into_iter().rev() {
|
||||
let Some(c) = canon(&sub) else { continue };
|
||||
if skip.as_ref() == Some(&c) || !seen.insert(c) {
|
||||
continue;
|
||||
}
|
||||
let rel = if rel.is_empty() { name } else { format!("{rel}/{name}") };
|
||||
stack.push((sub, rel, depth + 1));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn list_images_tree(dir: &str, _skip: &str, _cmd: &str) -> Result<Vec<BatchInput>> {
|
||||
Err(EngineError::Other(format!("cannot list {dir}: no file system on the web")))
|
||||
}
|
||||
|
||||
/// Opens each input in a scratch session, runs `f` on it and saves it to `output` as `format`
|
||||
/// (`"same"` keeps the input's extension). Errors per file are collected, not fatal.
|
||||
pub(crate) fn process_files(inputs: &[String], output: &str, format: &str, save: SaveOpts, suffix: &str, f: &dyn Fn(&mut Session) -> Result<()>) -> Value {
|
||||
let outputs = inputs.iter().map(|path| {
|
||||
let inputs: Vec<BatchInput> = inputs.iter().map(|path| BatchInput { path: path.clone(), rel_dir: String::new() }).collect();
|
||||
process_tree(&inputs, output, format, save, suffix, f)
|
||||
}
|
||||
|
||||
/// [`process_files`] for inputs from subfolders: each result goes to its input's relative folder
|
||||
/// under `output` (created as needed), so `a/x.png` and `b/x.png` don't collide.
|
||||
pub(crate) fn process_tree(inputs: &[BatchInput], output: &str, format: &str, save: SaveOpts, suffix: &str, f: &dyn Fn(&mut Session) -> Result<()>) -> Value {
|
||||
let outputs = inputs.iter().map(|BatchInput { path, rel_dir }| {
|
||||
let ext =
|
||||
if format == "same" { path.rsplit('.').next().unwrap_or("png").to_ascii_lowercase() } else { format.trim_start_matches('.').to_ascii_lowercase() };
|
||||
(path.as_str(), join(output, &format!("{}{suffix}.{ext}", stem(path))))
|
||||
(path.as_str(), join(&join(output, rel_dir), &format!("{}{suffix}.{ext}", stem(path))))
|
||||
});
|
||||
process_outputs(outputs, save, f)
|
||||
}
|
||||
@@ -1044,8 +1137,8 @@ fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some((id, _)) = steps.iter().find(|(id, _)| crate::commands::find(id).is_none()) {
|
||||
return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unknown command `{id}` in the action") });
|
||||
}
|
||||
let inputs = batch_inputs(p, cmd)?;
|
||||
let output = str_param(p, "output", cmd)?.to_string();
|
||||
let inputs = batch_inputs_tree(p, cmd, &output)?;
|
||||
let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string();
|
||||
// Steps that call another action play it from the caller's actions; the playback stack comes
|
||||
// along so an action that batches itself is caught as a recursive call.
|
||||
@@ -1076,23 +1169,23 @@ fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(())
|
||||
};
|
||||
let r = match names {
|
||||
Some(names) => process_outputs(inputs.iter().map(String::as_str).zip(names), save, &run),
|
||||
None => process_files(&inputs, &output, &format, save, "", &run),
|
||||
Some(names) => process_outputs(inputs.iter().map(|i| i.path.as_str()).zip(names), save, &run),
|
||||
None => process_tree(&inputs, &output, &format, save, "", &run),
|
||||
};
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.scripts.imageProcessor";
|
||||
let inputs = batch_inputs(p, cmd)?;
|
||||
let output = str_param(p, "output", cmd)?.to_string();
|
||||
let inputs = batch_inputs_tree(p, cmd, &output)?;
|
||||
let format = p.get("format").and_then(Value::as_str).unwrap_or("jpg").to_string();
|
||||
let fit = match (size_param(p, "width"), size_param(p, "height")) {
|
||||
(None, None) => None,
|
||||
(w, h) => Some(json!({"width": w.unwrap_or(1e9), "height": h.unwrap_or(1e9), "dontEnlarge": true})),
|
||||
};
|
||||
let to_srgb = p.get("convertToSrgb").and_then(Value::as_bool).unwrap_or(false);
|
||||
let r = process_files(&inputs, &output, &format, SaveOpts::from_params(s, p, cmd)?.or_quality(8.0), "", &|scratch| {
|
||||
let r = process_tree(&inputs, &output, &format, SaveOpts::from_params(s, p, cmd)?.or_quality(8.0), "", &|scratch| {
|
||||
if to_srgb && scratch.active().is_some_and(|d| d.doc.mode != ColorMode::Rgb) {
|
||||
scratch.execute("image.mode.rgb", json!({}))?;
|
||||
}
|
||||
@@ -1593,7 +1686,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch…",
|
||||
&["File", "Automate"],
|
||||
None,
|
||||
r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
|
||||
r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
|
||||
native,
|
||||
batch
|
||||
),
|
||||
@@ -1602,7 +1695,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Image Processor…",
|
||||
&["File", "Scripts"],
|
||||
None,
|
||||
r##"{"input":folder|[paths],"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
|
||||
r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
|
||||
native,
|
||||
image_processor
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Batch output names are planned before opening or writing files. Names substituted from an
|
||||
//! input are literal: braces in a source filename must never be interpreted as template tokens.
|
||||
|
||||
use super::{EngineError, Result, Value, join, stem};
|
||||
use super::{BatchInput, EngineError, Result, Value, join, stem};
|
||||
|
||||
fn bad(message: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: "file.automate.batch".into(), msg: message.into() }
|
||||
@@ -51,7 +51,7 @@ fn expand(parts: &[Part<'_>], name: &str, serial: u32, date: &str) -> String {
|
||||
|
||||
/// An absent or empty template preserves the old filename path exactly. An explicit template
|
||||
/// generates one component per input; the export format supplies the extension separately.
|
||||
pub(super) fn plan(inputs: &[String], output: &str, format: &str, params: &Value) -> Result<Option<Vec<String>>> {
|
||||
pub(super) fn plan(inputs: &[BatchInput], output: &str, format: &str, params: &Value) -> Result<Option<Vec<String>>> {
|
||||
let start = match params.get("startingSerial") {
|
||||
None => 1,
|
||||
Some(n) => {
|
||||
@@ -77,7 +77,7 @@ pub(super) fn plan(inputs: &[String], output: &str, format: &str, params: &Value
|
||||
return Err(bad("naming: the current UTC date is unavailable"));
|
||||
}
|
||||
let mut outputs = Vec::with_capacity(inputs.len());
|
||||
for (index, path) in inputs.iter().enumerate() {
|
||||
for (index, BatchInput { path, rel_dir }) in inputs.iter().enumerate() {
|
||||
let serial = if has_serial {
|
||||
u32::try_from(index).ok().and_then(|index| start.checked_add(index)).ok_or_else(|| bad("startingSerial plus the input count exceeds 4294967295"))?
|
||||
} else {
|
||||
@@ -93,14 +93,15 @@ pub(super) fn plan(inputs: &[String], output: &str, format: &str, params: &Value
|
||||
if name.len() > 255 || name.chars().any(|c| c.is_control() || "/\\<>:\"|?*".contains(c)) {
|
||||
return Err(bad("naming must produce a filename of at most 255 bytes without path separators or reserved characters"));
|
||||
}
|
||||
outputs.push(join(output, &name));
|
||||
// From subfolders ("Include All Subfolders"), each result keeps its subfolder.
|
||||
outputs.push(join(&join(output, rel_dir), &name));
|
||||
}
|
||||
// Renaming within the source folder could replace a later input before it is read. Resolve
|
||||
// existing paths so aliases such as `source/./001.png` cannot bypass the check. The default
|
||||
// (no template) path keeps its existing in-place behavior.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let sources: std::collections::HashSet<_> = inputs.iter().filter_map(|p| std::fs::canonicalize(p).ok()).collect();
|
||||
let sources: std::collections::HashSet<_> = inputs.iter().filter_map(|i| std::fs::canonicalize(&i.path).ok()).collect();
|
||||
for output in &outputs {
|
||||
if std::fs::canonicalize(output).ok().is_some_and(|p| sources.contains(&p)) {
|
||||
return Err(bad(format!("naming would replace an input file: {output}; choose a different destination or template")));
|
||||
|
||||
@@ -1044,6 +1044,110 @@ fn reveal_in_finder_reveals_the_documents_saved_path() {
|
||||
assert_eq!(r["program"], json!(program));
|
||||
assert_eq!(r["args"], json!(args));
|
||||
}
|
||||
|
||||
/// "Include All Subfolders" (AUTO-219-5, #3753): Batch and Image Processor take the images in
|
||||
/// subfolders too, each result keeping its subfolder under the output folder (so same-named files
|
||||
/// don't collide), and skip the output folder when it sits inside the input folder.
|
||||
#[test]
|
||||
fn batch_include_all_subfolders() {
|
||||
let dir = tmp("batch-subfolders");
|
||||
let input = join(&dir, "in");
|
||||
for sub in ["sub/deeper", "z"] {
|
||||
std::fs::create_dir_all(join(&input, sub)).unwrap();
|
||||
}
|
||||
png(&input, "a.png", 8, 8, "#ff0000");
|
||||
png(&join(&input, "sub"), "b.png", 8, 8, "#00ff00");
|
||||
png(&join(&input, "sub/deeper"), "a.png", 8, 8, "#0000ff");
|
||||
png(&join(&input, "z"), "a.png", 8, 8, "#ffffff");
|
||||
let mut s = Session::new();
|
||||
// Default: the top level only, as before.
|
||||
let out = join(&input, "batch");
|
||||
let r = s.execute("file.automate.batch", json!({"steps": [], "input": input, "output": out, "format": "png"})).unwrap();
|
||||
assert_eq!((r["files"].as_array().unwrap().len(), r["errors"].as_array().unwrap().len()), (1, 0), "{r}");
|
||||
// With subfolders: every image, in folder order, results kept apart by subfolder; the output
|
||||
// folder (inside the input folder, holding last run's a.png) is not an input.
|
||||
let r = s
|
||||
.execute(
|
||||
"file.automate.batch",
|
||||
json!({"steps": [["image.adjustments.invert", {}]], "input": input, "includeSubfolders": true, "output": out, "format": "png"}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(r["errors"].as_array().unwrap().is_empty(), "{r}");
|
||||
let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().replace('\\', "/")).collect();
|
||||
let o = out.replace('\\', "/");
|
||||
assert_eq!(files, vec![format!("{o}/a.png"), format!("{o}/sub/b.png"), format!("{o}/sub/deeper/a.png"), format!("{o}/z/a.png")]);
|
||||
let deep = photocraft_io::import("a.png", &std::fs::read(join(&out, "sub/deeper/a.png")).unwrap()).unwrap().document;
|
||||
let px = photocraft_compose::render(&deep, Rect::new(1, 1, 2, 2)).px[0];
|
||||
assert!(px[0] > 0.99 && px[1] > 0.99 && px[2] < 0.01, "blue inverted to yellow: {px:?}");
|
||||
std::fs::remove_dir_all(&out).unwrap();
|
||||
// A naming template applies within each kept subfolder (output outside the input folder).
|
||||
let named = join(&dir, "named");
|
||||
let r = s
|
||||
.execute("file.automate.batch", json!({"steps": [], "input": input, "includeSubfolders": true, "output": named, "format": "png", "naming": "{serial}"}))
|
||||
.unwrap();
|
||||
assert!(r["errors"].as_array().unwrap().is_empty(), "{r}");
|
||||
let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().replace('\\', "/")).collect();
|
||||
let n = named.replace('\\', "/");
|
||||
assert_eq!(files, vec![format!("{n}/001.png"), format!("{n}/sub/002.png"), format!("{n}/sub/deeper/003.png"), format!("{n}/z/004.png")]);
|
||||
// Image Processor shares the option (with its results out of the input folder).
|
||||
let out = join(&dir, "jpg");
|
||||
let r = s.execute("file.scripts.imageProcessor", json!({"input": input, "includeSubfolders": true, "output": out})).unwrap();
|
||||
assert_eq!((r["files"].as_array().unwrap().len(), r["errors"].as_array().unwrap().len()), (4, 0), "{r}");
|
||||
assert!(std::path::Path::new(&join(&out, "sub/deeper/a.jpg")).is_file());
|
||||
// A wrong type is a parameter error, for both.
|
||||
for bad in [json!("yes"), json!(1), json!([true])] {
|
||||
for cmd in ["file.automate.batch", "file.scripts.imageProcessor"] {
|
||||
let e = s.execute(cmd, json!({"steps": [], "input": input, "includeSubfolders": bad, "output": out})).unwrap_err();
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {bad}: {e}");
|
||||
}
|
||||
}
|
||||
// A missing input folder is an error, not a panic.
|
||||
assert!(s.execute("file.automate.batch", json!({"steps": [], "input": join(&dir, "nope"), "includeSubfolders": true, "output": out})).is_err());
|
||||
}
|
||||
|
||||
/// The subfolder walk stops at `MAX_SUBFOLDER_DEPTH` levels.
|
||||
#[test]
|
||||
fn batch_subfolder_walk_is_depth_limited() {
|
||||
let dir = tmp("batch-subfolder-depth");
|
||||
let mut deep = dir.clone();
|
||||
for level in 1..=MAX_SUBFOLDER_DEPTH + 1 {
|
||||
deep = join(&deep, "d");
|
||||
std::fs::create_dir_all(&deep).unwrap();
|
||||
if level >= MAX_SUBFOLDER_DEPTH {
|
||||
std::fs::write(join(&deep, &format!("l{level}.png")), b"x").unwrap();
|
||||
}
|
||||
}
|
||||
let found = list_images_tree(&dir, "", "test").unwrap();
|
||||
let names: Vec<_> = found.iter().map(|i| file_name(&i.path)).collect();
|
||||
assert_eq!(names, vec![format!("l{MAX_SUBFOLDER_DEPTH}.png")], "{found:?}");
|
||||
assert_eq!(found[0].rel_dir.split('/').count(), MAX_SUBFOLDER_DEPTH);
|
||||
}
|
||||
|
||||
/// A symlink back up the tree is walked once, not forever. Skipped where the platform doesn't
|
||||
/// let the test create directory symlinks (Windows without developer mode).
|
||||
#[test]
|
||||
fn batch_subfolder_walk_survives_symlink_loops() {
|
||||
let dir = tmp("batch-subfolder-loop");
|
||||
let sub = join(&dir, "sub");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
std::fs::write(join(&dir, "a.png"), b"x").unwrap();
|
||||
std::fs::write(join(&sub, "b.png"), b"x").unwrap();
|
||||
let link = std::path::Path::new(&sub).join("loop");
|
||||
#[cfg(unix)]
|
||||
let made = std::os::unix::fs::symlink(&dir, &link);
|
||||
#[cfg(windows)]
|
||||
let made = std::os::windows::fs::symlink_dir(&dir, &link);
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let made: std::io::Result<()> = Err(std::io::Error::other("no symlinks"));
|
||||
if made.is_err() {
|
||||
eprintln!("skipped: cannot create a directory symlink here");
|
||||
return;
|
||||
}
|
||||
let found = list_images_tree(&dir, "", "test").unwrap();
|
||||
let names: Vec<_> = found.iter().map(|i| (i.rel_dir.as_str(), file_name(&i.path))).collect();
|
||||
assert_eq!(names, vec![("", "a.png".to_string()), ("sub", "b.png".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_naming_validates_the_whole_plan_before_writing() {
|
||||
let dir = tmp("naming-invalid");
|
||||
|
||||
@@ -1037,6 +1037,9 @@ pub struct Preferences {
|
||||
/// differ from their defaults, saved as the user changes them and restored at launch, as
|
||||
/// Photoshop remembers each tool's options between sessions. JSON owned by the shell.
|
||||
pub tool_options: Value,
|
||||
/// Last selected tool, restored at launch. A tool-name string owned and validated by the
|
||||
/// shell; null in older files. Kept separate from tool options so neither overwrites the other.
|
||||
pub selected_tool: Value,
|
||||
/// View › Extras, the View › Show items (Pixel Grid, Grid, Guides, …) and the View › Snap To
|
||||
/// targets that differ from their defaults, saved as the user toggles them and restored at
|
||||
/// launch, as Photoshop keeps them between sessions (#3762). JSON owned by the shell.
|
||||
|
||||
@@ -36,6 +36,23 @@ pub fn transform_bounds(doc: &Document, layer: &Layer) -> Rect {
|
||||
}
|
||||
}
|
||||
|
||||
/// The box Free Transform opens on `layer`, and the Move tool's transform controls show (#5297).
|
||||
/// With a selection that limits the transform it is the selection's own bounds, as in Photoshop:
|
||||
/// the box and the marching ants are one rectangle, however little of the selection the layer
|
||||
/// fills. Empty, like [`transform_bounds`], when the selection holds none of the layer.
|
||||
pub fn transform_frame(doc: &Document, layer: &Layer) -> Rect {
|
||||
let b = transform_bounds(doc, layer);
|
||||
if moves_whole(layer) { b } else { framed_by_selection(doc, b) }
|
||||
}
|
||||
|
||||
/// `bounds` (what a selection left of a transform's content), or the selection's own bounds.
|
||||
fn framed_by_selection(doc: &Document, bounds: Rect) -> Rect {
|
||||
match &doc.selection {
|
||||
Some(sel) if !bounds.is_empty() => sel.content_bounds(),
|
||||
_ => bounds,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -199,6 +216,12 @@ pub fn target_bounds(doc: &Document, surf: &Surface) -> Rect {
|
||||
}
|
||||
}
|
||||
|
||||
/// The box Free Transform opens on a lone target: like [`transform_frame`], the selection's own
|
||||
/// bounds when there is one (#5297).
|
||||
pub fn target_frame(doc: &Document, surf: &Surface) -> Rect {
|
||||
framed_by_selection(doc, target_bounds(doc, surf))
|
||||
}
|
||||
|
||||
/// The locks `id` inherits from the groups around it.
|
||||
pub(crate) fn group_locks(doc: &Document, id: LayerId) -> Locks {
|
||||
doc.path_of(id).and_then(|p| Some(doc.locks_at(p.split_last()?.1))).unwrap_or_default()
|
||||
@@ -1164,6 +1187,32 @@ mod tests {
|
||||
assert_eq!(transform_bounds(&st.doc, st.doc.layer(st.active_layer.unwrap()).unwrap()), Rect::new(10, 10, 15, 20));
|
||||
}
|
||||
|
||||
/// #5297: the box Free Transform opens with a selection is the selection's own rectangle,
|
||||
/// not the part of it the layer fills; type still moves whole, and a selection that holds none
|
||||
/// of the layer leaves nothing to transform.
|
||||
#[test]
|
||||
fn the_frame_is_the_selections_own_bounds() {
|
||||
let mut s = session();
|
||||
let frame = |s: &Session| {
|
||||
let st = s.active().unwrap();
|
||||
let l = st.doc.layer(st.active_layer.unwrap()).unwrap();
|
||||
(transform_frame(&st.doc, l), transform_bounds(&st.doc, l))
|
||||
};
|
||||
let content = Rect::new(10, 10, 30, 20);
|
||||
assert_eq!(frame(&s), (content, content), "no selection: the content");
|
||||
s.execute("select.rect", json!({"x": 5, "y": 5, "width": 15, "height": 40})).unwrap();
|
||||
assert_eq!(frame(&s), (Rect::new(5, 5, 20, 45), Rect::new(10, 10, 20, 20)));
|
||||
s.execute("select.rect", json!({"x": 60, "y": 60, "width": 10, "height": 10})).unwrap();
|
||||
assert!(frame(&s).0.is_empty(), "nothing of the layer is selected");
|
||||
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 200, "height": 120})).unwrap();
|
||||
s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 36})).unwrap();
|
||||
let whole = active_bounds(&s);
|
||||
s.execute("select.rect", json!({"x": whole.x0, "y": whole.y0, "width": whole.width() / 2, "height": whole.height()})).unwrap();
|
||||
assert_eq!(frame(&s), (whole, whole), "type moves whole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_transform_ignores_selections_inside_its_children() {
|
||||
group_transform_with_selection(Rect::new(10, 10, 15, 15));
|
||||
|
||||
@@ -3070,12 +3070,19 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
// The view centre can be any finite number (`ui.set`, #980). Past ±2³⁰ there is no document
|
||||
// to outline, and the padding below (at most 2 · 256 · 64) can't overflow i32 from there.
|
||||
let px = |v: f64| v.clamp(-f64::from(1 << 30), f64::from(1 << 30)) as i32;
|
||||
let vis = photocraft_geom::Rect::new(
|
||||
px(x0.floor()).div_euclid(q) * q - q,
|
||||
px(y0.floor()).div_euclid(q) * q - q,
|
||||
(px(x1.ceil()).div_euclid(q) + 2) * q,
|
||||
(px(y1.ceil()).div_euclid(q) + 2) * q,
|
||||
);
|
||||
// A Free Transform carries the selection to wherever its box goes (#5297), so all of
|
||||
// it is outlined: the part now in view may have started out of it.
|
||||
let carried = app.session.active_index() == Some(idx) && crate::transform_tool::carries_selection_of(app, doc.id);
|
||||
let vis = if carried {
|
||||
photocraft_geom::Rect::new(-(1 << 30), -(1 << 30), 1 << 30, 1 << 30)
|
||||
} else {
|
||||
photocraft_geom::Rect::new(
|
||||
px(x0.floor()).div_euclid(q) * q - q,
|
||||
px(y0.floor()).div_euclid(q) * q - q,
|
||||
(px(x1.ceil()).div_euclid(q) + 2) * q,
|
||||
(px(y1.ceil()).div_euclid(q) + 2) * q,
|
||||
)
|
||||
};
|
||||
let key = crate::surface_fingerprint(sel)
|
||||
^ (step as u64) << 56
|
||||
^ doc.id.0.rotate_left(17)
|
||||
@@ -3109,7 +3116,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
if let Some((dx, dy)) = selection_shown_offset(app) {
|
||||
shown.center = [xf.center[0] - dx as f32, xf.center[1] - dy as f32];
|
||||
}
|
||||
marching_ants_segments(&painter, &shown, segs, time);
|
||||
// Under a Free Transform box they are where the box puts them (#5297).
|
||||
if !(carried && crate::transform_tool::draw_selection(app, &painter, &xf, doc.id, segs, time)) {
|
||||
marching_ants_segments(&painter, &shown, segs, time);
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
@@ -4103,6 +4113,31 @@ fn marching_ants_segments(painter: &egui::Painter, xf: &ViewXform, segs: &[crate
|
||||
/// [`marching_ants_segments`] with each outline point placed on screen by `to_screen` (a
|
||||
/// transformed outline: Content-Aware Move's Transform On Drop).
|
||||
pub(crate) fn marching_ants_mapped(painter: &egui::Painter, segs: &[crate::outline::Segment], time: f64, to_screen: impl Fn([i32; 2]) -> Pos2) {
|
||||
marching_ants_lines(painter, segs.iter().map(|(a, b)| (to_screen(*a), to_screen(*b))), time);
|
||||
}
|
||||
|
||||
/// The part of the line `a`–`b` inside `r` (Liang–Barsky), if any.
|
||||
fn clip_line(r: Rect, a: Pos2, b: Pos2) -> Option<(Pos2, Pos2)> {
|
||||
let d = b - a;
|
||||
let (mut t0, mut t1) = (0.0f32, 1.0f32);
|
||||
for (p, q) in [(-d.x, a.x - r.min.x), (d.x, r.max.x - a.x), (-d.y, a.y - r.min.y), (d.y, r.max.y - a.y)] {
|
||||
if p == 0.0 {
|
||||
if q < 0.0 {
|
||||
return None;
|
||||
}
|
||||
} else if p < 0.0 {
|
||||
t0 = t0.max(q / p);
|
||||
} else {
|
||||
t1 = t1.min(q / p);
|
||||
}
|
||||
}
|
||||
(t0 <= t1).then(|| (a + d * t0, a + d * t1))
|
||||
}
|
||||
|
||||
/// Marching ants along lines already placed on screen (a warped outline is a run of short ones).
|
||||
pub(crate) fn marching_ants_lines(painter: &egui::Painter, lines: impl Iterator<Item = (Pos2, Pos2)>, time: f64) {
|
||||
// Longer than any line that fits the view: only its part in view is dashed.
|
||||
const LONG: f32 = 8192.0;
|
||||
let dash = 4.0f32;
|
||||
let phase = ((time * 10.0) % (dash as f64 * 2.0)) as f32;
|
||||
let clip = painter.clip_rect();
|
||||
@@ -4120,12 +4155,17 @@ pub(crate) fn marching_ants_mapped(painter: &egui::Painter, segs: &[crate::outli
|
||||
mesh.add_triangle(i, i + 1, i + 2);
|
||||
mesh.add_triangle(i, i + 2, i + 3);
|
||||
};
|
||||
for (a, b) in segs {
|
||||
let pa = to_screen(*a);
|
||||
let pb = to_screen(*b);
|
||||
if !clip.intersects(Rect::from_two_pos(pa, pb).expand(1.0)) {
|
||||
for (pa, pb) in lines {
|
||||
// A transformed outline can land anywhere, or nowhere (a point on a Distort's horizon).
|
||||
if !(pa.is_finite() && pb.is_finite()) || !clip.intersects(Rect::from_two_pos(pa, pb).expand(1.0)) {
|
||||
continue;
|
||||
}
|
||||
let (pa, pb) = if pa.distance(pb) > LONG {
|
||||
let Some(inside) = clip_line(clip.expand(4.0 * dash), pa, pb) else { continue };
|
||||
inside
|
||||
} else {
|
||||
(pa, pb)
|
||||
};
|
||||
let pa = pos2(pa.x.round() + 0.5, pa.y.round() + 0.5);
|
||||
let pb = pos2(pb.x.round() + 0.5, pb.y.round() + 0.5);
|
||||
let len = pa.distance(pb);
|
||||
@@ -4501,7 +4541,7 @@ pub(crate) fn layer_edges_rect(app: &PhotocraftApp, idx: usize) -> Option<photoc
|
||||
Some(b.translate(dx, dy))
|
||||
}
|
||||
|
||||
/// Move tool › Show Transform Controls: the active layer's transform bounds.
|
||||
/// Move tool › Show Transform Controls: the box Free Transform would open on the active layer.
|
||||
fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Option<Rect> {
|
||||
if app.ui.tool != Tool::Move || !app.ui.tool_options.move_show_transform || app.ui.transform.is_some() || app.drag.is_some() {
|
||||
return None;
|
||||
@@ -4511,7 +4551,7 @@ fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Option<Rect>
|
||||
if crate::doc_props_ui::is_background(&st.doc, l) {
|
||||
return None;
|
||||
}
|
||||
let b = photocraft_engine::transform_cmds::transform_bounds(&st.doc, l);
|
||||
let b = photocraft_engine::transform_cmds::transform_frame(&st.doc, l);
|
||||
let (dx, dy) = crate::move_ui::floating_offset(app).unwrap_or((0, 0));
|
||||
let b = b.translate(dx, dy);
|
||||
if b.is_empty() {
|
||||
@@ -7761,6 +7801,27 @@ mod transform_controls_tests {
|
||||
assert_eq!(app.ui.transform.as_ref().unwrap().rect, [200.0, 150.0, 300.0, 210.0]);
|
||||
}
|
||||
|
||||
/// #5297: with a selection the Move tool's transform controls are the selection's rectangle,
|
||||
/// though the layer fills only part of it, and a press on them opens that box.
|
||||
#[test]
|
||||
fn move_transform_controls_frame_the_selection() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap();
|
||||
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
|
||||
app.run("select.rect", json!({"x": 60, "y": 80, "width": 100, "height": 120})).unwrap();
|
||||
app.ui.tool = Tool::Move;
|
||||
app.ui.tool_options.move_show_transform = true;
|
||||
let xf =
|
||||
ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [200.0, 150.0], flip: false, rotation: 0.0, aspect: 1.0 };
|
||||
let r = transform_controls_rect(&app, &xf).unwrap();
|
||||
assert_eq!(r, Rect::from_min_max(pos2(60.0, 80.0), pos2(160.0, 200.0)));
|
||||
let ctx = egui::Context::default();
|
||||
assert!(begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom()));
|
||||
assert_eq!(app.ui.transform.as_ref().unwrap().rect, [60.0, 80.0, 160.0, 200.0]);
|
||||
}
|
||||
|
||||
/// #2585: Free Transform on a position-locked layer is refused before the box opens, with
|
||||
/// Photoshop's alert, from ⌘T and from the Move tool's transform controls alike. It used to
|
||||
/// open, preview every drag and fail only at commit.
|
||||
|
||||
@@ -131,7 +131,7 @@ pub enum Outcome {
|
||||
/// field's value is validated before the first one is applied, so a typo, an unknown field, a
|
||||
/// bad value or a bad nested key can't reply with success while nothing — or only half of it —
|
||||
/// changed (#412).
|
||||
pub const UI_SET_FIELDS: [&str; 35] = [
|
||||
pub const UI_SET_FIELDS: [&str; 36] = [
|
||||
"tool",
|
||||
"panels",
|
||||
"dock",
|
||||
@@ -167,6 +167,7 @@ pub const UI_SET_FIELDS: [&str; 35] = [
|
||||
"shapeStroke",
|
||||
"camTransformOnDrop",
|
||||
"tileGrid",
|
||||
"layerFilter",
|
||||
];
|
||||
|
||||
/// Most clicks one `ui.click` may queue (#982). Each click is a press and a release that the app
|
||||
@@ -511,6 +512,7 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
|
||||
let cam_transform_on_drop = bool_field(p, "camTransformOnDrop")?;
|
||||
// Developer overlay of the active layer's storage tiles (tile_overlay.rs).
|
||||
let tile_grid = bool_field(p, "tileGrid")?;
|
||||
let layer_filter = p.get("layerFilter").map(|v| crate::layer_filter_ui::patched(&app.ui, v)).transpose()?;
|
||||
// The Crop tool's overlay menu (#1919).
|
||||
let crop_overlay = match p.get("cropOverlay") {
|
||||
Some(v) => Some(v.as_str().and_then(crate::crop_overlay::CropOverlay::from_id).ok_or_else(|| {
|
||||
@@ -642,7 +644,7 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
|
||||
}
|
||||
}
|
||||
if let Some(t) = tool {
|
||||
app.ui.tool = t;
|
||||
crate::tool_memory::select(app, t);
|
||||
// Each tool keeps its own brush (#218), so switch it in before `brushSize`
|
||||
// below sets the new tool's size.
|
||||
crate::paint_mouse::sync_tool_brush(app);
|
||||
@@ -672,6 +674,9 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
|
||||
if let Some(on) = tile_grid {
|
||||
app.ui.view.tile_grid = on;
|
||||
}
|
||||
if let Some(f) = layer_filter {
|
||||
crate::layer_filter_ui::apply(&mut app.ui, f);
|
||||
}
|
||||
if let Some(k) = crop_overlay {
|
||||
app.ui.tool_options.crop_overlay = k;
|
||||
}
|
||||
@@ -985,7 +990,7 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
|
||||
let secondary = matches!(button.as_str(), "secondary" | "right");
|
||||
let mods = modifiers_from(&m);
|
||||
if let Some(t) = tool {
|
||||
app.ui.tool = t;
|
||||
crate::tool_memory::select(app, t);
|
||||
}
|
||||
// Space held: the Crop tool moves the frame being drawn, a marquee, lasso or shape
|
||||
// being drawn moves instead of growing (hold_keys.rs). Like a modifier flag, it may be
|
||||
@@ -1930,6 +1935,36 @@ mod tests {
|
||||
assert!(app.ui.tool_options.gradient_classic, "invalid mode must not change options");
|
||||
}
|
||||
|
||||
/// #5048: the Layers panel filter is drivable; a bad field changes nothing.
|
||||
#[test]
|
||||
fn ui_set_drives_the_layers_panel_filter() {
|
||||
use crate::layer_filter_ui::FilterBy;
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let ctx = egui::Context::default();
|
||||
let ok = call(&mut app, &ctx, "ui.set", json!({"layerFilter": {"by": "name", "name": "ink"}}));
|
||||
assert_eq!(ok["ok"], true, "{ok}");
|
||||
assert_eq!((app.ui.layer_filter_by, app.ui.layer_filter_name.as_str()), (FilterBy::Name, "ink"));
|
||||
let ok = call(&mut app, &ctx, "ui.set", json!({"layerFilter": {"by": "mode", "mode": "Pass Through", "kinds": ["type", "pixel", "type"]}}));
|
||||
assert_eq!(ok["ok"], true, "{ok}");
|
||||
assert_eq!((app.ui.layer_filter_by, app.ui.layer_filter_mode), (FilterBy::Mode, photocraft_color::BlendMode::PassThrough));
|
||||
assert_eq!(app.ui.layer_filter, ["type", "pixel"], "kinds are kept once each");
|
||||
assert_eq!(app.ui.layer_filter_name, "ink", "fields left out keep their value");
|
||||
for bad in [
|
||||
json!({"layerFilter": "name"}),
|
||||
json!({"layerFilter": {"by": "colour"}}),
|
||||
json!({"layerFilter": {"kinds": ["pixels"]}}),
|
||||
json!({"layerFilter": {"kinds": "pixel"}}),
|
||||
json!({"layerFilter": {"name": 3}}),
|
||||
json!({"layerFilter": {"mode": "Nonsense"}}),
|
||||
json!({"layerFilter": {"by": "kind", "extra": true}}),
|
||||
json!({"layerFilter": {"by": "kind"}, "tileGrid": "yes"}),
|
||||
] {
|
||||
let r = call(&mut app, &ctx, "ui.set", bad.clone());
|
||||
assert_eq!(r["ok"], false, "{bad} → {r}");
|
||||
assert_eq!(app.ui.layer_filter_by, FilterBy::Mode, "{bad} changed nothing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ui_set_toggles_the_developer_tile_grid() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
|
||||
@@ -3741,6 +3741,8 @@ navigator Zoom Zvětšení
|
||||
Action playback stopped Přehrávání akce zastaveno
|
||||
Step {step} is waiting for its dialog Krok {step} čeká na svůj dialog
|
||||
@plural {n} action|{n} actions {n} akce|{n} akce|{n} akcí
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Zahrnout všechny podsložky
|
||||
Auto Add/Delete Automaticky přidat/odstranit
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3131,6 +3131,8 @@ curves Smooth Glätten
|
||||
Action playback stopped Aktionswiedergabe angehalten
|
||||
Step {step} is waiting for its dialog Schritt {step} wartet auf seinen Dialog
|
||||
@plural {n} action|{n} actions {n} Aktion|{n} Aktionen
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Alle Unterordner einschließen
|
||||
Auto Add/Delete Autom. hinzuf./löschen
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3831,6 +3831,8 @@ curves Smooth Εξομάλυνση
|
||||
Action playback stopped Η αναπαραγωγή της ενέργειας σταμάτησε
|
||||
Step {step} is waiting for its dialog Το βήμα {step} περιμένει το παράθυρο διαλόγου του
|
||||
@plural {n} action|{n} actions {n} ενέργεια|{n} ενέργειες
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Συμπερίληψη όλων των υποφακέλων
|
||||
Auto Add/Delete Αυτόματη προσθήκη/διαγραφή
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1029 and column 18.
|
@@ -2818,6 +2818,8 @@ curves Smooth Suavizar
|
||||
Action playback stopped Reproducción de la acción detenida
|
||||
Step {step} is waiting for its dialog El paso {step} está esperando su cuadro de diálogo
|
||||
@plural {n} action|{n} actions {n} acción|{n} acciones
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Incluir todas las subcarpetas
|
||||
Auto Add/Delete Añadir/eliminar automáticamente
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -3135,6 +3135,8 @@ curves Smooth Lisser
|
||||
Action playback stopped Exécution de l’action arrêtée
|
||||
Step {step} is waiting for its dialog L’étape {step} attend sa boîte de dialogue
|
||||
@plural {n} action|{n} actions {n} action|{n} actions
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Inclure tous les sous-dossiers
|
||||
Auto Add/Delete Ajout/suppr. auto
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -606,6 +606,7 @@
|
||||
HSB/HSL HSB/HSL
|
||||
Huge Óriási
|
||||
Image Processor Képfeldolgozó
|
||||
Include All Subfolders Az összes almappa belefoglalása
|
||||
Indexed Color… Indexelt szín…
|
||||
Info Információ
|
||||
Install Plug-in Bővítmény telepítése
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3122,6 +3122,8 @@ curves Smooth Haluskan
|
||||
Action playback stopped Pemutaran tindakan dihentikan
|
||||
Step {step} is waiting for its dialog Langkah {step} menunggu dialognya
|
||||
@plural {n} action|{n} actions {n} tindakan
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Sertakan semua subfolder
|
||||
Auto Add/Delete Tambah/Hapus Otomatis
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -4096,6 +4096,8 @@ navigator Zoom Zoom
|
||||
Action playback stopped Esecuzione dell’azione interrotta
|
||||
Step {step} is waiting for its dialog Il passaggio {step} attende la sua finestra di dialogo
|
||||
@plural {n} action|{n} actions {n} azione|{n} azioni
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Includi tutte le sottocartelle
|
||||
Auto Add/Delete Aggiungi/elimina automaticamente
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2644 and column 53.
|
@@ -3740,6 +3740,8 @@ curves Smooth スムーズ
|
||||
Action playback stopped アクションの再生を停止しました
|
||||
Step {step} is waiting for its dialog ステップ {step} はダイアログを待っています
|
||||
@plural {n} action|{n} actions アクション {n} 個
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders すべてのサブフォルダーを含める
|
||||
|
||||
# Liquify tool names (shown via tl!(tool.label()) in the UI, so they are not found by the static scan)
|
||||
Forward Warp 前方ワープ
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3308,6 +3308,8 @@ curves Smooth 매끄럽게
|
||||
Action playback stopped 액션 재생이 중지되었습니다
|
||||
Step {step} is waiting for its dialog {step}단계가 대화 상자를 기다리고 있습니다
|
||||
@plural {n} action|{n} actions 액션 {n}개
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders 모든 하위 폴더 포함
|
||||
Auto Add/Delete 자동 추가/삭제
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 3157 and column 53.
|
@@ -3893,6 +3893,8 @@ curves Smooth Vloeiend maken
|
||||
Action playback stopped Afspelen van de handeling gestopt
|
||||
Step {step} is waiting for its dialog Stap {step} wacht op zijn dialoogvenster
|
||||
@plural {n} action|{n} actions {n} handeling|{n} handelingen
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Alle submappen opnemen
|
||||
Auto Add/Delete Automatisch toevoegen/verwijderen
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -3731,6 +3731,8 @@ curves Smooth Wygładź
|
||||
Action playback stopped Odtwarzanie operacji zatrzymane
|
||||
Step {step} is waiting for its dialog Krok {step} czeka na swoje okno dialogowe
|
||||
@plural {n} action|{n} actions {n} operacja|{n} operacje|{n} operacji
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Uwzględnij wszystkie podfoldery
|
||||
Auto Add/Delete Automatyczne dodawanie/usuwanie
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3923,6 +3923,8 @@ layerLabel No Color Sem cor
|
||||
Action playback stopped Reprodução da ação interrompida
|
||||
Step {step} is waiting for its dialog A etapa {step} está aguardando sua caixa de diálogo
|
||||
@plural {n} action|{n} actions {n} ação|{n} ações
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Incluir todas as subpastas
|
||||
Auto Add/Delete Adicionar/excluir automaticamente
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3079,6 +3079,8 @@ curves Smooth Сгладить
|
||||
Action playback stopped Воспроизведение операции остановлено
|
||||
Step {step} is waiting for its dialog Шаг {step} ожидает своего диалога
|
||||
@plural {n} action|{n} actions {n} операция|{n} операции|{n} операций
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Включить все вложенные папки
|
||||
Auto Add/Delete Автодобавление/удаление
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -2997,6 +2997,7 @@ cameraData Lens Objektiv
|
||||
Create a new rectangular frame Napravi novi pravougaoni okvir
|
||||
Create a new elliptical frame Napravi novi eliptični okvir
|
||||
Include in playback Uključi u reprodukciju
|
||||
Include All Subfolders Uključi sve podfascikle
|
||||
Perspective Crop Tool Alatka za perspektivno opsecanje
|
||||
Show Grid Prikaži mrežu
|
||||
Drag a box or click four corners · drag the corners onto the edges of a skewed shape · {commit} commits · Esc cancels Prevucite okvir ili kliknite četiri ugla · prevucite uglove na ivice iskošenog oblika · {commit} potvrđuje · Esc otkazuje
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3355,6 +3355,7 @@ cameraRaw Color Renk
|
||||
How often fastening points are placed by themselves Sabitleme noktalarının kendi başlarına ne sıklıkla yerleştirildiği
|
||||
ISO Speed ISO Hızı
|
||||
Image Processor Görüntü İşlemcisi
|
||||
Include All Subfolders Tüm Alt Klasörleri Dahil Et
|
||||
In içinde
|
||||
Install Plug-in Eklentiyi Yükle
|
||||
Interpret Footage Görüntüyü Yorumlama
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -3832,6 +3832,8 @@ curves Smooth Згладити
|
||||
Action playback stopped Відтворення операції зупинено
|
||||
Step {step} is waiting for its dialog Крок {step} очікує на свій діалог
|
||||
@plural {n} action|{n} actions {n} операція|{n} операції|{n} операцій
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Включити всі вкладені папки
|
||||
Auto Add/Delete Автододавання/видалення
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1385 and column 18.
|
@@ -3617,6 +3617,8 @@ curves Smooth Làm mượt
|
||||
Step {step} is waiting for its dialog Bước {step} đang chờ hộp thoại của nó
|
||||
@plural {n} action|{n} actions {n} hành động
|
||||
Presentation Trình bày
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders Bao gồm tất cả thư mục con
|
||||
Gradient Preset Options Tùy chọn thiết lập sẵn chuyển sắc
|
||||
Import .GRD Nhập .GRD
|
||||
Choose a gradient file (.grd). Chọn tệp chuyển sắc (.grd).
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -2743,6 +2743,8 @@ curves Smooth 平滑
|
||||
Action playback stopped 动作播放已停止
|
||||
Step {step} is waiting for its dialog 步骤 {step} 正在等待其对话框
|
||||
@plural {n} action|{n} actions {n} 个动作
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders 包含所有子文件夹
|
||||
Auto Add/Delete 自动添加/删除
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2590 and column 53.
|
@@ -2728,6 +2728,8 @@ curves Smooth 平滑
|
||||
Action playback stopped 動作播放已停止
|
||||
Step {step} is waiting for its dialog 步驟 {step} 正在等待其對話框
|
||||
@plural {n} action|{n} actions {n} 個動作
|
||||
# Batch / Image Processor
|
||||
Include All Subfolders 包含所有子資料夾
|
||||
Auto Add/Delete 自動增加/刪除
|
||||
|
||||
# Native Windows printing qualification
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -0,0 +1,162 @@
|
||||
//! The Layers panel's filter row (#5048): a filter-type dropdown, as in Photoshop, then the
|
||||
//! controls for that type. Kind toggles layer kinds, Name matches part of the layer name, Mode
|
||||
//! picks one blend mode. The criteria live in `UiState` (`layer_filter*`), so the control channel
|
||||
//! can read and set them.
|
||||
|
||||
use photocraft_color::BlendMode;
|
||||
use photocraft_doc::{Layer, LayerContent};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::state::UiState;
|
||||
use crate::{PhotocraftApp, icons, widgets};
|
||||
|
||||
/// What the Layers panel filters by.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum FilterBy {
|
||||
#[default]
|
||||
Kind,
|
||||
Name,
|
||||
Mode,
|
||||
}
|
||||
|
||||
/// The filter criteria, copied out of `UiState` for one frame of the Layers panel.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Filter {
|
||||
pub by: FilterBy,
|
||||
pub kinds: Vec<String>,
|
||||
/// As typed; matched trimmed and ignoring case.
|
||||
pub name: String,
|
||||
pub mode: BlendMode,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
pub fn of(ui: &UiState) -> Self {
|
||||
Self { by: ui.layer_filter_by, kinds: ui.layer_filter.clone(), name: ui.layer_filter_name.clone(), mode: ui.layer_filter_mode }
|
||||
}
|
||||
|
||||
/// Whether the panel is filtered. Like Photoshop, Mode always filters (by Normal at first);
|
||||
/// Kind and Name only once a kind is toggled or some text is typed.
|
||||
pub fn active(&self) -> bool {
|
||||
match self.by {
|
||||
FilterBy::Kind => !self.kinds.is_empty(),
|
||||
FilterBy::Name => !self.name.trim().is_empty(),
|
||||
FilterBy::Mode => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `l` is listed under this filter.
|
||||
pub fn shows(&self, l: &Layer) -> bool {
|
||||
if !self.active() {
|
||||
return true;
|
||||
}
|
||||
match self.by {
|
||||
FilterBy::Kind => self.kinds.iter().any(|k| k == kind(l)),
|
||||
FilterBy::Name => l.name.to_lowercase().contains(&self.name.trim().to_lowercase()),
|
||||
FilterBy::Mode => l.blend == self.mode,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The kinds the Kind filter toggles.
|
||||
pub const KINDS: [&str; 5] = ["pixel", "adjustment", "type", "shape", "smart"];
|
||||
|
||||
/// `ui.set {layerFilter: {by?, kinds?, name?, mode?}}`: `current` with the given fields replaced,
|
||||
/// or an error naming the bad field (nothing changes then). `by` is `kind`, `name` or `mode`;
|
||||
/// `kinds` a list of [`KINDS`]; `mode` a blend mode name such as `Multiply` or `Pass Through`.
|
||||
pub fn patched(current: &UiState, v: &serde_json::Value) -> Result<Filter, String> {
|
||||
let Some(o) = v.as_object() else { return Err("layerFilter must be an object".into()) };
|
||||
if let Some(k) = o.keys().find(|k| !["by", "kinds", "name", "mode"].contains(&k.as_str())) {
|
||||
return Err(format!("unknown layerFilter field `{k}` (fields: by, kinds, name, mode)"));
|
||||
}
|
||||
let mut f =
|
||||
Filter { by: current.layer_filter_by, kinds: current.layer_filter.clone(), name: current.layer_filter_name.clone(), mode: current.layer_filter_mode };
|
||||
if let Some(by) = o.get("by") {
|
||||
f.by = serde_json::from_value(by.clone()).map_err(|_| "layerFilter.by must be kind, name or mode".to_string())?;
|
||||
}
|
||||
if let Some(kinds) = o.get("kinds") {
|
||||
let list = kinds.as_array().ok_or("layerFilter.kinds must be a list")?;
|
||||
f.kinds = Vec::new();
|
||||
for k in list {
|
||||
let Some(k) = k.as_str().filter(|k| KINDS.contains(k)) else {
|
||||
return Err(format!("layerFilter.kinds: unknown kind {k} (kinds: {})", KINDS.join(", ")));
|
||||
};
|
||||
if !f.kinds.iter().any(|have| have == k) {
|
||||
f.kinds.push(k.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(name) = o.get("name") {
|
||||
f.name = name.as_str().ok_or("layerFilter.name must be a string")?.to_string();
|
||||
}
|
||||
if let Some(mode) = o.get("mode") {
|
||||
let name = mode.as_str().ok_or("layerFilter.mode must be a blend mode name")?;
|
||||
f.mode = photocraft_engine::commands::blend_from_str(name)
|
||||
.filter(|m| *m == BlendMode::PassThrough || BlendMode::LAYER_MODES.contains(m))
|
||||
.ok_or_else(|| format!("layerFilter.mode: unknown blend mode `{name}`"))?;
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// Store `f` as the Layers panel's filter.
|
||||
pub fn apply(ui: &mut UiState, f: Filter) {
|
||||
ui.layer_filter_by = f.by;
|
||||
ui.layer_filter = f.kinds;
|
||||
ui.layer_filter_name = f.name;
|
||||
ui.layer_filter_mode = f.mode;
|
||||
}
|
||||
|
||||
/// The kind filter's name for `l`'s content ("" for groups, which no kind matches).
|
||||
fn kind(l: &Layer) -> &'static str {
|
||||
match &l.content {
|
||||
LayerContent::Raster(_) => "pixel",
|
||||
LayerContent::Adjustment(_) | LayerContent::Fill(_) => "adjustment",
|
||||
LayerContent::Text(_) => "type",
|
||||
LayerContent::Shape(_) => "shape",
|
||||
LayerContent::Smart(_) => "smart",
|
||||
LayerContent::Group(_) => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the filter row: the type dropdown, then that type's controls.
|
||||
pub fn bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
let by = [(FilterBy::Kind, tl!("Kind")), (FilterBy::Name, tl!("Name")), (FilterBy::Mode, tl!("Mode"))];
|
||||
widgets::dropdown(ui, "layer-filter-by", &mut app.ui.layer_filter_by, &by, 64.0);
|
||||
ui.add_space(4.0);
|
||||
match app.ui.layer_filter_by {
|
||||
FilterBy::Kind => {
|
||||
for (kind, icon, tip) in [
|
||||
("pixel", "image", tl!("Filter for pixel layers")),
|
||||
("adjustment", "adjustment-layer", tl!("Filter for adjustment layers")),
|
||||
("type", "type", tl!("Filter for type layers")),
|
||||
("shape", "square", tl!("Filter for shape layers")),
|
||||
("smart", "app-window", tl!("Filter for smart objects")),
|
||||
] {
|
||||
let on = app.ui.layer_filter.iter().any(|k| k == kind);
|
||||
if icons::button(ui, icon, 22.0, on, tip).clicked() {
|
||||
if on {
|
||||
app.ui.layer_filter.retain(|k| k != kind);
|
||||
} else {
|
||||
app.ui.layer_filter.push(kind.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
FilterBy::Name => {
|
||||
let width = ui.available_width().max(48.0);
|
||||
widgets::text_field(ui, ui.id().with("layer-filter-name"), &mut app.ui.layer_filter_name, tl!("Search"), width, false);
|
||||
}
|
||||
FilterBy::Mode => {
|
||||
let modes: Vec<(BlendMode, &str)> = std::iter::once(BlendMode::PassThrough).chain(BlendMode::LAYER_MODES).map(|m| (m, m.label())).collect();
|
||||
let width = ui.available_width().max(96.0);
|
||||
widgets::dropdown(ui, "layer-filter-mode", &mut app.ui.layer_filter_mode, &modes, width);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "layer_filter_ui_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,136 @@
|
||||
//! #5048: the Layers panel's filter-type dropdown (Kind, Name, Mode).
|
||||
|
||||
use egui::vec2;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use photocraft_color::BlendMode;
|
||||
use photocraft_doc::Document;
|
||||
use serde_json::json;
|
||||
|
||||
use super::{Filter, FilterBy};
|
||||
use crate::PhotocraftApp;
|
||||
use crate::state::UiState;
|
||||
|
||||
/// Background, "Ink" (Multiply) and "Paper" in a group "Sheets", and "ink notes" (type) on top.
|
||||
fn session() -> photocraft_engine::Session {
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Paper"})).unwrap();
|
||||
s.execute("layer.groupLayers", json!({"name": "Sheets"})).unwrap();
|
||||
let paper = layer(&s.active().unwrap().doc, "Paper");
|
||||
s.execute("layer.select", json!({"layer": paper})).unwrap();
|
||||
let ink = s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.setProps", json!({"layer": ink, "blend": "Multiply"})).unwrap();
|
||||
let sheets = layer(&s.active().unwrap().doc, "Sheets");
|
||||
s.execute("layer.select", json!({"layer": sheets})).unwrap();
|
||||
let text = s.execute("type.create", json!({"text": "ink notes", "x": 4, "y": 20, "size": 12})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("layer.setProps", json!({"layer": text, "name": "ink notes"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn layer(doc: &Document, name: &str) -> u64 {
|
||||
doc.walk().into_iter().find(|(_, _, l)| l.name == name).map(|(_, _, l)| l.id.0).unwrap_or_else(|| panic!("no layer {name}"))
|
||||
}
|
||||
|
||||
/// The names `filter` lists, top to bottom.
|
||||
fn listed(doc: &Document, filter: &Filter) -> Vec<String> {
|
||||
crate::layer_tree_ui::display_rows(doc, filter.active()).into_iter().filter(|(_, l)| filter.shows(l)).map(|(_, l)| l.name.clone()).collect()
|
||||
}
|
||||
|
||||
fn filter(by: FilterBy, kinds: &[&str], name: &str, mode: BlendMode) -> Filter {
|
||||
Filter::of(&UiState {
|
||||
layer_filter_by: by,
|
||||
layer_filter: kinds.iter().map(|k| k.to_string()).collect(),
|
||||
layer_filter_name: name.into(),
|
||||
layer_filter_mode: mode,
|
||||
..UiState::default()
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_filter_type_lists_its_matches() {
|
||||
let s = session();
|
||||
let doc = &s.active().unwrap().doc;
|
||||
let all = listed(doc, &Filter::of(&UiState::default()));
|
||||
assert_eq!(all, ["ink notes", "Sheets", "Ink", "Paper", "Background"]);
|
||||
// Kind: groups match no kind, as before.
|
||||
assert_eq!(listed(doc, &filter(FilterBy::Kind, &["pixel"], "", BlendMode::Normal)), ["Ink", "Paper", "Background"]);
|
||||
assert_eq!(listed(doc, &filter(FilterBy::Kind, &["type"], "", BlendMode::Normal)), ["ink notes"]);
|
||||
// Name: part of the name, ignoring case and surrounding spaces; groups match too.
|
||||
assert_eq!(listed(doc, &filter(FilterBy::Name, &[], " INK ", BlendMode::Normal)), ["ink notes", "Ink"]);
|
||||
assert_eq!(listed(doc, &filter(FilterBy::Name, &[], "sheet", BlendMode::Normal)), ["Sheets"]);
|
||||
assert_eq!(listed(doc, &filter(FilterBy::Name, &[], "nothing like it", BlendMode::Normal)), Vec::<String>::new());
|
||||
// Mode: one blend mode; a group's own Pass Through counts.
|
||||
assert_eq!(listed(doc, &filter(FilterBy::Mode, &[], "", BlendMode::Multiply)), ["Ink"]);
|
||||
assert_eq!(listed(doc, &filter(FilterBy::Mode, &[], "", BlendMode::PassThrough)), ["Sheets"]);
|
||||
assert_eq!(listed(doc, &filter(FilterBy::Mode, &[], "", BlendMode::Normal)), ["ink notes", "Paper", "Background"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_criterion_turns_kind_and_name_on_while_mode_always_filters() {
|
||||
let kinds_left_on = filter(FilterBy::Name, &["pixel"], "", BlendMode::Multiply);
|
||||
assert!(!kinds_left_on.active(), "the other types' criteria don't apply");
|
||||
assert!(!filter(FilterBy::Name, &[], " ", BlendMode::Normal).active(), "spaces are no criterion");
|
||||
assert!(!filter(FilterBy::Kind, &[], "ink", BlendMode::Normal).active());
|
||||
assert!(filter(FilterBy::Mode, &[], "", BlendMode::Normal).active(), "Mode filters by Normal at first, like Photoshop");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_settings_without_the_new_fields_still_load() {
|
||||
let mut saved = serde_json::to_value(UiState::default()).unwrap();
|
||||
let fields = saved.as_object_mut().unwrap();
|
||||
for key in ["layer_filter_by", "layer_filter_name", "layer_filter_mode"] {
|
||||
assert!(fields.remove(key).is_some(), "{key} is saved");
|
||||
}
|
||||
let ui: UiState = serde_json::from_value(saved).unwrap();
|
||||
assert_eq!((ui.layer_filter_by, ui.layer_filter_name.as_str(), ui.layer_filter_mode), (FilterBy::Kind, "", BlendMode::Normal));
|
||||
let round = serde_json::to_value(UiState { layer_filter_by: FilterBy::Mode, ..UiState::default() }).unwrap();
|
||||
assert_eq!(round["layer_filter_by"], "mode");
|
||||
}
|
||||
|
||||
fn harness() -> Harness<'static, PhotocraftApp> {
|
||||
let session = session();
|
||||
let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| {
|
||||
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
|
||||
PhotocraftApp::new(session, crate::Services::default())
|
||||
});
|
||||
h.run_steps(8);
|
||||
h
|
||||
}
|
||||
|
||||
/// The names of the rows the Layers panel drew, top to bottom.
|
||||
fn drawn(h: &Harness<'_, PhotocraftApp>) -> Vec<String> {
|
||||
let doc = &h.state().session.active().unwrap().doc;
|
||||
let mut rows = crate::layer_row_ui::recorded(&h.ctx);
|
||||
rows.sort_by(|a, b| a.row.top().total_cmp(&b.row.top()));
|
||||
rows.iter().filter_map(|r| doc.walk().into_iter().find(|(_, _, l)| l.id.0 == r.layer).map(|(_, _, l)| l.name.clone())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dropdown_switches_the_panel_between_filter_types() {
|
||||
let mut h = harness();
|
||||
assert_eq!(drawn(&h), ["ink notes", "Sheets", "Ink", "Paper", "Background"]);
|
||||
// The type is a real dropdown now: open it and pick Name.
|
||||
// A dropdown shows its choice as the combo box's value.
|
||||
h.get_by_value("Kind").click();
|
||||
h.run_steps(4);
|
||||
h.query_all_by_label("Name").last().expect("Name in the open list").click();
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().ui.layer_filter_by, FilterBy::Name);
|
||||
assert_eq!(drawn(&h), ["ink notes", "Sheets", "Ink", "Paper", "Background"], "no text yet: every layer");
|
||||
h.state_mut().ui.layer_filter_name = "ink".into();
|
||||
h.run_steps(4);
|
||||
assert_eq!(drawn(&h), ["ink notes", "Ink"]);
|
||||
// Mode starts at Normal; the kind toggles left on under Kind don't leak into it.
|
||||
h.state_mut().ui.layer_filter = vec!["type".into()];
|
||||
h.state_mut().ui.layer_filter_by = FilterBy::Mode;
|
||||
h.run_steps(4);
|
||||
assert_eq!(drawn(&h), ["ink notes", "Paper", "Background"]);
|
||||
h.state_mut().ui.layer_filter_mode = BlendMode::Multiply;
|
||||
h.run_steps(4);
|
||||
assert_eq!(drawn(&h), ["Ink"]);
|
||||
// Back to Kind: its own criterion applies again.
|
||||
h.state_mut().ui.layer_filter_by = FilterBy::Kind;
|
||||
h.run_steps(4);
|
||||
assert_eq!(drawn(&h), ["ink notes"]);
|
||||
}
|
||||
@@ -39,7 +39,7 @@ pub fn display_rows(doc: &Document, show_all: bool) -> Vec<(usize, &Layer)> {
|
||||
/// Mask session's working text, which is no layer to the user: Photoshop shows only the mask
|
||||
/// overlay while you type (#3036).
|
||||
pub fn panel_rows<'a>(app: &PhotocraftApp, doc: &'a Document) -> Vec<(usize, &'a Layer)> {
|
||||
let mut rows = display_rows(doc, !app.ui.layer_filter.is_empty());
|
||||
let mut rows = display_rows(doc, crate::layer_filter_ui::Filter::of(&app.ui).active());
|
||||
if let Some(working) = app.ui.text_edit.as_ref().filter(|ed| ed.mask).map(|ed| ed.layer) {
|
||||
rows.retain(|(_, l)| l.id.0 != working);
|
||||
}
|
||||
|
||||
@@ -108,6 +108,7 @@ pub mod jobs_ui;
|
||||
pub mod kys_import;
|
||||
pub mod lasso_ui;
|
||||
pub(crate) mod last_brush;
|
||||
pub mod layer_filter_ui;
|
||||
pub mod layer_menu_ui;
|
||||
pub mod layer_pick_ui;
|
||||
pub mod layer_picker;
|
||||
@@ -1713,6 +1714,12 @@ impl PhotocraftApp {
|
||||
}
|
||||
|
||||
impl eframe::App for PhotocraftApp {
|
||||
fn on_exit(&mut self) {
|
||||
if let Err(err) = tool_memory::save_on_exit(self) {
|
||||
log::warn!("Preferences: could not save the final tool selection: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language));
|
||||
// Caps Lock state read from the OS once per frame (see `Services::caps_lock`): the canvas
|
||||
|
||||
@@ -167,7 +167,7 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
|
||||
/// [`invoke`] without the unsaved-changes prompt, for once the user has already answered it.
|
||||
pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {
|
||||
if let Some(tool) = crate::tool_shortcuts::tool(id) {
|
||||
app.ui.tool = tool;
|
||||
crate::tool_memory::select(app, tool);
|
||||
return Ok(json!({"tool": tool}));
|
||||
}
|
||||
if id == "ui.symmetryTransform" {
|
||||
|
||||
@@ -167,16 +167,16 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
paint_toolbar_flyout_indicator(ui, &t, &resp);
|
||||
}
|
||||
if resp.clicked() && ui.data(|d| d.get_temp::<egui::Id>(held_id)) != Some(key) {
|
||||
app.ui.tool = tool;
|
||||
crate::tool_memory::select(app, tool);
|
||||
}
|
||||
// Double-clicking the Hand tool fits the image on screen (Photoshop).
|
||||
if resp.double_clicked() && tool == Tool::Hand {
|
||||
app.ui.tool = tool;
|
||||
crate::tool_memory::select(app, tool);
|
||||
// With no document open there is nothing to fit.
|
||||
let _ = app.run("view.fitOnScreen", json!({}));
|
||||
}
|
||||
if resp.double_clicked() && tool == Tool::Zoom {
|
||||
app.ui.tool = tool;
|
||||
crate::tool_memory::select(app, tool);
|
||||
let _ = app.run("view.actualPixels", json!({}));
|
||||
}
|
||||
// Right-click or long-press opens the flyout (Photoshop).
|
||||
@@ -206,7 +206,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
if slot.len() > 1 && long_press {
|
||||
// Holding a tool button selects the tool it shows, as a click would (#4453).
|
||||
app.ui.tool = tool;
|
||||
crate::tool_memory::select(app, tool);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
if let Some((open_key, anchor)) = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id))
|
||||
@@ -268,7 +268,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
);
|
||||
}
|
||||
if ir.clicked() {
|
||||
app.ui.tool = item;
|
||||
crate::tool_memory::select(app, item);
|
||||
ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id));
|
||||
}
|
||||
}
|
||||
@@ -2198,31 +2198,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
|
||||
let t = Tokens::get(ui.ctx());
|
||||
if t.pro {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
let (r, _) = ui.allocate_exact_size(vec2(64.0, 22.0), Sense::hover());
|
||||
ui.painter().rect_filled(r, t.radius_sm, t.field);
|
||||
ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
|
||||
icons::paint(ui, Rect::from_center_size(r.left_center() + vec2(11.0, 0.0), vec2(14.0, 14.0)), "search", 11.0, t.text_faint);
|
||||
ui.painter().text(r.left_center() + vec2(22.0, 0.0), Align2::LEFT_CENTER, tl!("Kind"), egui::FontId::proportional(11.5), t.text_dim);
|
||||
ui.add_space(4.0);
|
||||
for (kind, icon, tip) in [
|
||||
("pixel", "image", tl!("Filter for pixel layers")),
|
||||
("adjustment", "adjustment-layer", tl!("Filter for adjustment layers")),
|
||||
("type", "type", tl!("Filter for type layers")),
|
||||
("shape", "square", tl!("Filter for shape layers")),
|
||||
("smart", "app-window", tl!("Filter for smart objects")),
|
||||
] {
|
||||
let on = app.ui.layer_filter.iter().any(|k| k == kind);
|
||||
if icons::button(ui, icon, 22.0, on, tip).clicked() {
|
||||
if on {
|
||||
app.ui.layer_filter.retain(|k| k != kind);
|
||||
} else {
|
||||
app.ui.layer_filter.push(kind.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
crate::layer_filter_ui::bar(app, ui);
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
if let Some(l) = active_layer {
|
||||
@@ -2347,7 +2323,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
ui.scroll_with_delta(vec2(0.0, delta));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
let filter = app.ui.layer_filter.clone();
|
||||
let filter = crate::layer_filter_ui::Filter::of(&app.ui);
|
||||
let fx_collapsed = app.session.active().map(|d| d.fx_collapsed.clone()).unwrap_or_default();
|
||||
crate::layer_row_ui::begin(ui.ctx());
|
||||
// The drawn rows, top to bottom (#1721): the space between them and below the last
|
||||
@@ -2358,18 +2334,8 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
if !photocraft_engine::select_extra_cmds::isolation_shows(&doc, &isolated, l.id) {
|
||||
continue;
|
||||
}
|
||||
if !filter.is_empty() {
|
||||
let kind = match &l.content {
|
||||
LayerContent::Raster(_) => "pixel",
|
||||
LayerContent::Adjustment(_) | LayerContent::Fill(_) => "adjustment",
|
||||
LayerContent::Text(_) => "type",
|
||||
LayerContent::Shape(_) => "shape",
|
||||
LayerContent::Smart(_) => "smart",
|
||||
LayerContent::Group(_) => "",
|
||||
};
|
||||
if !filter.iter().any(|k| k == kind) {
|
||||
continue;
|
||||
}
|
||||
if !filter.shows(l) {
|
||||
continue;
|
||||
}
|
||||
let row = RowSel { selected: selection.contains(&l.id), primary: active == Some(l.id), multi: selection.len() > 1 };
|
||||
let top = ui.cursor().top();
|
||||
|
||||
@@ -52,6 +52,7 @@ pub struct Runtime {
|
||||
show_rulers: Option<bool>,
|
||||
/// Tool options as last remembered in the preferences (see `tool_memory`).
|
||||
pub(crate) tool_options: Option<crate::state::ToolOptions>,
|
||||
pub(crate) selected_tool: Option<crate::state::Tool>,
|
||||
}
|
||||
|
||||
/// The GPU canvas colours from Preferences › Transparency & Gamut.
|
||||
@@ -2828,6 +2829,110 @@ mod tests {
|
||||
assert!(app3.ui.brush_picker_list.show_name && app3.ui.brush_picker_list.show_stroke && app3.ui.brush_picker_list.show_tip);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_tool_survives_a_restart_without_option_changes() {
|
||||
use crate::state::Tool;
|
||||
let (mut app, store) = app_with_store();
|
||||
let ctx = egui::Context::default();
|
||||
tick(&mut app, &ctx);
|
||||
assert_eq!(app.ui.tool, Tool::Brush);
|
||||
// Every tool, including flyout-only tools, can be restored. Return to Brush last to
|
||||
// prove selecting the default overwrites a previously remembered nondefault tool.
|
||||
for tool in Tool::ALL.into_iter().chain([Tool::Brush]) {
|
||||
app.ui.tool = tool;
|
||||
crate::tool_memory::persist(&mut app, &ctx);
|
||||
tick(&mut app, &ctx);
|
||||
assert_eq!(stored(&store)["selectedTool"], serde_json::to_value(tool).unwrap());
|
||||
let (app2, _) = app_with_saved(store.lock().unwrap().clone());
|
||||
assert_eq!(app2.ui.tool, tool, "restored before the first frame");
|
||||
assert_eq!(app2.ui.group_tool(tool.key()), Some(tool));
|
||||
assert_eq!(app2.ui.tool_options, crate::state::ToolOptions::default());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_tool_is_flushed_on_exit_without_another_frame() {
|
||||
let (mut app, store) = app_with_store();
|
||||
app.ui.tool = crate::state::Tool::Move;
|
||||
crate::tool_memory::save_on_exit(&mut app).unwrap();
|
||||
let (app2, _) = app_with_saved(store.lock().unwrap().clone());
|
||||
assert_eq!(app2.ui.tool, crate::state::Tool::Move);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_tool_explicit_eraser_survives_exit_during_temporary_switches() {
|
||||
use crate::state::Tool;
|
||||
for spring in [false, true] {
|
||||
for menu in [false, true] {
|
||||
let (mut app, store) = app_with_store();
|
||||
app.stylus.tool_before_eraser = Some(Tool::Zoom);
|
||||
app.ui.tool = Tool::Eraser;
|
||||
if spring {
|
||||
crate::spring_tools::pressed(&mut app, 'E', Tool::Zoom, true, 0.0);
|
||||
}
|
||||
if menu {
|
||||
crate::menus::invoke(&mut app, &egui::Context::default(), "tools.select.eraser", json!({})).unwrap();
|
||||
} else {
|
||||
crate::tool_memory::select(&mut app, Tool::Eraser);
|
||||
}
|
||||
assert_eq!(app.stylus.tool_before_eraser, None);
|
||||
assert!(app.ui.spring.is_none());
|
||||
crate::tool_memory::save_on_exit(&mut app).unwrap();
|
||||
let (restored, _) = app_with_saved(store.lock().unwrap().clone());
|
||||
assert_eq!(restored.ui.tool, Tool::Eraser);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_selected_tool_preserves_other_preferences() {
|
||||
for bad in [json!(null), json!("FutureTool"), json!(42), json!({}), json!([])] {
|
||||
let (app, _) = app_with_saved(Some(
|
||||
json!({
|
||||
"selectedTool": bad, "toolOptions": {"feather": 12.0}
|
||||
})
|
||||
.to_string(),
|
||||
));
|
||||
assert_eq!(app.ui.tool, crate::state::Tool::Brush, "{bad}");
|
||||
assert_eq!(app.ui.tool_options.feather, 12.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_tool_excludes_temporary_switches() {
|
||||
use crate::state::Tool;
|
||||
let (mut app, store) = app_with_store();
|
||||
let ctx = egui::Context::default();
|
||||
app.ui.tool = Tool::Move;
|
||||
crate::tool_memory::persist(&mut app, &ctx);
|
||||
tick(&mut app, &ctx);
|
||||
app.tool_override = Some(Tool::Hand);
|
||||
crate::tool_memory::persist(&mut app, &ctx);
|
||||
tick(&mut app, &ctx);
|
||||
assert_eq!(stored(&store)["selectedTool"], json!("Move"));
|
||||
app.tool_override = None;
|
||||
app.ui.tool = Tool::Zoom;
|
||||
crate::spring_tools::pressed(&mut app, 'Z', Tool::Move, true, 0.0);
|
||||
crate::tool_memory::persist(&mut app, &ctx);
|
||||
tick(&mut app, &ctx);
|
||||
assert_eq!(stored(&store)["selectedTool"], json!("Move"));
|
||||
// A quick tap commits the choice after spring_tools clears the pending switch.
|
||||
crate::spring_tools::tick(&mut app, &ctx);
|
||||
crate::tool_memory::persist(&mut app, &ctx);
|
||||
tick(&mut app, &ctx);
|
||||
assert_eq!(stored(&store)["selectedTool"], json!("Zoom"));
|
||||
app.stylus.tool_before_eraser = Some(Tool::Zoom);
|
||||
app.ui.tool = Tool::Eraser;
|
||||
crate::tool_memory::persist(&mut app, &ctx);
|
||||
tick(&mut app, &ctx);
|
||||
assert_eq!(stored(&store)["selectedTool"], json!("Zoom"));
|
||||
// An explicit selection during a temporary switch takes precedence.
|
||||
app.ui.tool = Tool::PolygonLasso;
|
||||
crate::tool_memory::persist(&mut app, &ctx);
|
||||
tick(&mut app, &ctx);
|
||||
assert_eq!(stored(&store)["selectedTool"], json!("PolygonLasso"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_options_survive_a_restart() {
|
||||
let (mut app, store) = app_with_store();
|
||||
|
||||
@@ -1004,7 +1004,7 @@ fn tool_id(t: Tool) -> String {
|
||||
pub fn select_tool_preset(app: &mut PhotocraftApp, name: &str) {
|
||||
let Some(r) = run(app, "tool.presets.select", json!({"preset": name})) else { return };
|
||||
if let Some(tool) = r["tool"].as_str().and_then(Tool::from_name) {
|
||||
app.ui.tool = tool;
|
||||
crate::tool_memory::select(app, tool);
|
||||
// Each tool keeps its own brush (#218), so switch it in before the preset's brush lands
|
||||
// on it, and re-apply the brush the command just set for the old tool.
|
||||
crate::paint_mouse::sync_tool_brush(app);
|
||||
|
||||
@@ -628,6 +628,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
// `consume_key` ignores extra ⇧ and ⌥: a ⇧/⌥ switch is never spring-loaded.
|
||||
let (plain, now) = ctx.input(|i| (!cycle_shift && !i.modifiers.shift && !i.modifiers.alt, i.time));
|
||||
crate::spring_tools::pressed(app, t.key(), before, plain, now);
|
||||
if app.ui.spring.is_none() {
|
||||
// Permanent key choices own the tool; held-key switches keep the pen marker.
|
||||
app.stylus.tool_before_eraser = None;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -741,6 +741,10 @@ fn default_brush_tool() -> Tool {
|
||||
Tool::Brush
|
||||
}
|
||||
|
||||
fn default_layer_filter_mode() -> photocraft_color::BlendMode {
|
||||
photocraft_color::BlendMode::Normal
|
||||
}
|
||||
|
||||
fn one_u32() -> u32 {
|
||||
1
|
||||
}
|
||||
@@ -1140,6 +1144,15 @@ pub struct UiState {
|
||||
/// Layers panel kind filter ("pixel", "adjustment", "type", "shape", "smart"); empty = all.
|
||||
#[serde(default)]
|
||||
pub layer_filter: Vec<String>,
|
||||
/// Layers panel filter type (#5048): kind (above), name or blend mode.
|
||||
#[serde(default)]
|
||||
pub layer_filter_by: crate::layer_filter_ui::FilterBy,
|
||||
/// Layers panel name filter: part of a layer name, ignoring case; empty = all.
|
||||
#[serde(default)]
|
||||
pub layer_filter_name: String,
|
||||
/// Layers panel blend-mode filter.
|
||||
#[serde(default = "default_layer_filter_mode")]
|
||||
pub layer_filter_mode: photocraft_color::BlendMode,
|
||||
/// Actions panel: which row is selected and which are expanded. The list lives on the session.
|
||||
#[serde(default)]
|
||||
pub actions: crate::actions::ActionsUi,
|
||||
@@ -1307,6 +1320,9 @@ impl Default for UiState {
|
||||
artboard_tool: Default::default(),
|
||||
shell: Default::default(),
|
||||
layer_filter: Vec::new(),
|
||||
layer_filter_by: Default::default(),
|
||||
layer_filter_name: String::new(),
|
||||
layer_filter_mode: default_layer_filter_mode(),
|
||||
pen: None,
|
||||
stroke_editor: None,
|
||||
direct_selection: Default::default(),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Tool options remembered between launches (#2814), as Photoshop keeps each tool's options-bar
|
||||
//! settings across sessions.
|
||||
//! Selected tool and tool options remembered between launches, as in Photoshop (#2814).
|
||||
//!
|
||||
//! `Preferences::tool_options` holds the [`ToolOptions`] fields that differ from their defaults,
|
||||
//! so a default changed in a later release still reaches users who never touched that option.
|
||||
@@ -10,7 +9,28 @@
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::state::ToolOptions;
|
||||
use crate::state::{Tool, ToolOptions};
|
||||
|
||||
/// Explicit choices override temporary pen and held-key tools, even when selecting the same tool.
|
||||
pub(crate) fn select(app: &mut PhotocraftApp, tool: Tool) {
|
||||
app.stylus.tool_before_eraser = None;
|
||||
app.ui.spring = None;
|
||||
app.ui.tool = tool;
|
||||
}
|
||||
|
||||
/// Temporary canvas overrides do not change `ui.tool`. Spring-loaded letters and the pen's
|
||||
/// eraser end do, so remember the tool they will return to instead. A different explicit choice
|
||||
/// (or beginning a type edit) owns the tool and stands, just as in `spring_tools::tick`.
|
||||
fn selected(app: &PhotocraftApp) -> Tool {
|
||||
let tool = if app.ui.tool == Tool::Eraser { app.stylus.tool_before_eraser.unwrap_or(app.ui.tool) } else { app.ui.tool };
|
||||
if let Some(s) = &app.ui.spring
|
||||
&& tool == s.tool
|
||||
&& app.ui.text_edit.is_none()
|
||||
{
|
||||
return s.previous;
|
||||
}
|
||||
tool
|
||||
}
|
||||
|
||||
/// The options that differ from the defaults, as JSON (`Null` when none do).
|
||||
fn changed(o: &ToolOptions) -> Value {
|
||||
@@ -21,11 +41,24 @@ fn changed(o: &ToolOptions) -> Value {
|
||||
if diff.is_empty() { Value::Null } else { Value::Object(diff) }
|
||||
}
|
||||
|
||||
/// Remember the tool options in the preferences once the user lets go of the pointer. Cheap
|
||||
/// when nothing changed: one struct compare per frame. Run every frame, so options set by the
|
||||
/// control channel or a tool preset are remembered too.
|
||||
/// Remember the selected tool and its options once the user lets go of the pointer. Run every
|
||||
/// frame, so choices made through the control channel or a tool preset are remembered too.
|
||||
pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
if ctx.input(|i| i.pointer.any_down()) || app.prefs_rt.tool_options.as_ref() == Some(&app.ui.tool_options) {
|
||||
if ctx.input(|i| i.pointer.any_down()) {
|
||||
return;
|
||||
}
|
||||
let tool = selected(app);
|
||||
if app.prefs_rt.selected_tool != Some(tool) {
|
||||
app.prefs_rt.selected_tool = Some(tool);
|
||||
if let Ok(now) = serde_json::to_value(tool)
|
||||
&& app.session.prefs().selected_tool != now
|
||||
{
|
||||
app.session.prefs.edit(|p| p.selected_tool = now);
|
||||
// prefs_ui::tick ran before the panels; ensure it can flush this new revision.
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
if app.prefs_rt.tool_options.as_ref() == Some(&app.ui.tool_options) {
|
||||
return;
|
||||
}
|
||||
app.prefs_rt.tool_options = Some(app.ui.tool_options.clone());
|
||||
@@ -35,8 +68,25 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore the remembered tool options at launch, field by field over the current ones.
|
||||
/// Flush the final choice on normal exit, even if no further frame ran after the tool changed.
|
||||
pub(crate) fn save_on_exit(app: &mut PhotocraftApp) -> Result<(), String> {
|
||||
persist(app, &egui::Context::default());
|
||||
crate::prefs_ui::save_preferences(app)
|
||||
}
|
||||
|
||||
/// Restore the selected tool before the first frame and its options field by field.
|
||||
pub fn restore(app: &mut PhotocraftApp) {
|
||||
let saved = app.session.prefs().selected_tool.clone();
|
||||
if !saved.is_null() {
|
||||
match serde_json::from_value::<Tool>(saved) {
|
||||
Ok(tool) => {
|
||||
app.ui.tool = tool;
|
||||
app.ui.remember_group_tool();
|
||||
}
|
||||
Err(err) => log::warn!("Preferences: ignoring the remembered selected tool: {err}"),
|
||||
}
|
||||
}
|
||||
app.prefs_rt.selected_tool = Some(app.ui.tool);
|
||||
let saved = app.session.prefs().tool_options.clone();
|
||||
if let Some(saved) = saved.as_object()
|
||||
&& let Ok(Value::Object(mut cur)) = serde_json::to_value(&app.ui.tool_options)
|
||||
|
||||
@@ -195,7 +195,8 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String>
|
||||
if matches!(layer.content, LayerContent::Adjustment(_)) && layer.mask.is_none() {
|
||||
return Err("Adjustment layers have nothing to transform".into());
|
||||
}
|
||||
let b = photocraft_engine::transform_cmds::transform_bounds(&doc, layer);
|
||||
// With a selection the box is the selection's (#5297).
|
||||
let b = photocraft_engine::transform_cmds::transform_frame(&doc, layer);
|
||||
if b.is_empty() {
|
||||
return Err("Could not transform: the layer is empty".into());
|
||||
}
|
||||
@@ -410,7 +411,7 @@ fn fold_made(app: &mut PhotocraftApp, document: DocId, made: MadeLayer) {
|
||||
}
|
||||
|
||||
/// Free Transform of a targeted unlinked layer mask, alpha channel or Quick Mask by itself: the
|
||||
/// box frames its content (within the selection) and previews the moving values in grey over the
|
||||
/// box frames its content (or the selection) and previews the moving values in grey over the
|
||||
/// document with them vacated.
|
||||
fn begin_lone(
|
||||
app: &mut PhotocraftApp,
|
||||
@@ -420,7 +421,7 @@ fn begin_lone(
|
||||
target: serde_json::Value,
|
||||
) -> Result<(), String> {
|
||||
use photocraft_engine::transform_cmds as tc;
|
||||
let b = tc::target_bounds(&doc, &surf);
|
||||
let b = tc::target_frame(&doc, &surf);
|
||||
if b.is_empty() {
|
||||
return Err("Could not transform: nothing is selected".into());
|
||||
}
|
||||
@@ -2166,6 +2167,72 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform
|
||||
}
|
||||
}
|
||||
|
||||
/// Applying the open box moves the selection outline with it: `edit.transform` and
|
||||
/// `edit.transform.warp` map it like the pixels. Not Transform Selection (its ants are hidden), a
|
||||
/// path, Content-Aware Scale or a type layer's Warp Text, which leave the selection alone.
|
||||
fn carries_selection(app: &PhotocraftApp, t: &TransformSession) -> bool {
|
||||
!t.selection && t.path.is_none() && t.content_aware.is_none() && !(t.warp.is_some() && warps_type(app))
|
||||
}
|
||||
|
||||
/// A transform of `document` is open that carries its selection along (#5297): the canvas traces
|
||||
/// the whole outline, not only the part in view where it started, for [`draw_selection`].
|
||||
pub(crate) fn carries_selection_of(app: &PhotocraftApp, document: DocId) -> bool {
|
||||
matches!((&app.ui.transform, &app.transform_preview), (Some(t), Some(pv)) if pv.doc.id == document && carries_selection(app, t))
|
||||
}
|
||||
|
||||
/// The marching ants where the open box puts them (#5297): the selection follows a move, scale,
|
||||
/// rotation, skew, distort, perspective or warp while it is made, to where applying it leaves it.
|
||||
/// `segs` is the outline of `document`'s selection at rest. False when no open transform carries
|
||||
/// that selection: the caller draws it where it is.
|
||||
pub(crate) fn draw_selection(
|
||||
app: &PhotocraftApp,
|
||||
painter: &egui::Painter,
|
||||
xf: &ViewXform,
|
||||
document: DocId,
|
||||
segs: &[crate::outline::Segment],
|
||||
time: f64,
|
||||
) -> bool {
|
||||
let Some(t) = app.ui.transform.as_ref().filter(|_| carries_selection_of(app, document)) else { return false };
|
||||
let scr = |(x, y): (f64, f64)| xf.to_screen(x as f32, y as f32);
|
||||
let doc = |p: [i32; 2]| [f64::from(p[0]), f64::from(p[1])];
|
||||
let along = |a: [f64; 2], b: [f64; 2], k: f64| [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k];
|
||||
if let Some(w) = &t.warp {
|
||||
// A warp bends the outline's straight runs: each is drawn in pieces about 8 points long.
|
||||
let piece = (8.0 / f64::from(xf.zoom.max(1e-3))).max(1.0);
|
||||
let lines = segs.iter().flat_map(|(a, b)| {
|
||||
let (a, b) = (doc(*a), doc(*b));
|
||||
let n = (((b[0] - a[0]).abs() + (b[1] - a[1]).abs()) / piece).ceil().clamp(1.0, 256.0) as usize;
|
||||
let at = move |i: usize| {
|
||||
let p = along(a, b, i as f64 / n as f64);
|
||||
scr(w.map(p[0], p[1]))
|
||||
};
|
||||
(0..n).map(move |i| (at(i), at(i + 1)))
|
||||
});
|
||||
crate::canvas::marching_ants_lines(painter, lines, time);
|
||||
} else if let Some(h) = Homography::rect_to_quad(t.rect, t.quad) {
|
||||
// Past a Distort's horizon the outline has no place, like the pixels (#4863): a run that
|
||||
// crosses it stops short of it, where its points are still a finite way off.
|
||||
let front = h.front_side(t.rect);
|
||||
let depth = |p: [f64; 2]| front * h.w(p[0], p[1]);
|
||||
let near = corners(t.rect).iter().map(|c| depth(*c)).fold(0.0, f64::max) * 1e-3;
|
||||
let lines = segs.iter().filter_map(|(a, b)| {
|
||||
let (mut a, mut b) = (doc(*a), doc(*b));
|
||||
let (da, db) = (depth(a), depth(b));
|
||||
if da < near && db < near {
|
||||
return None;
|
||||
}
|
||||
if da < near {
|
||||
a = along(a, b, (near - da) / (db - da));
|
||||
} else if db < near {
|
||||
b = along(b, a, (near - db) / (da - db));
|
||||
}
|
||||
Some((scr(h.apply(a[0], a[1])), scr(h.apply(b[0], b[1]))))
|
||||
});
|
||||
crate::canvas::marching_ants_lines(painter, lines, time);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// What the styled preview of the moving layer is drawn from (transform_fx.rs), at `zoom` screen
|
||||
/// pixels per document pixel. `None` for a layer without a style (also once it is switched off
|
||||
/// while the box is open) or a hidden one: the bare pixels are drawn instead. The style, opacity
|
||||
@@ -3995,6 +4062,123 @@ mod tests {
|
||||
assert_eq!((t.layer, t.rect), (second.0, [40.0, 40.0, 56.0, 60.0]), "the next box is on the selected layer");
|
||||
}
|
||||
|
||||
/// The screen rectangle the marching ants cover as [`draw_selection`] paints them over the
|
||||
/// active document's selection; `None` when it leaves them to the canvas.
|
||||
fn ants_bounds(app: &PhotocraftApp, xf: &ViewXform) -> Option<egui::Rect> {
|
||||
let st = app.session.active().unwrap();
|
||||
let sel = st.doc.selection.as_ref().unwrap();
|
||||
let segs = crate::outline::outline(sel, sel.content_bounds());
|
||||
let ctx = egui::Context::default();
|
||||
let mut drawn = false;
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| {
|
||||
let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("ants-test")));
|
||||
drawn = draw_selection(app, &painter, xf, st.doc.id, &segs, 0.0);
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
// The ants are a mesh of straight dashes and line shapes for the slanted ones.
|
||||
let ants = output.shapes.iter().filter(|s| matches!(s.shape, egui::Shape::Mesh(_) | egui::Shape::LineSegment { .. }));
|
||||
drawn.then(|| ants.map(|s| s.shape.visual_bounding_rect()).fold(egui::Rect::NOTHING, egui::Rect::union))
|
||||
}
|
||||
|
||||
/// The screen rectangle around document points.
|
||||
fn screen_bounds(xf: &ViewXform, points: &[[f64; 2]]) -> egui::Rect {
|
||||
egui::Rect::from_points(&points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
fn rects_match(a: egui::Rect, b: egui::Rect) -> bool {
|
||||
(a.min - b.min).abs().max_elem() <= 2.0 && (a.max - b.max).abs().max_elem() <= 2.0
|
||||
}
|
||||
|
||||
/// #5297: with a selection, Free Transform's box is the selection's own rectangle (wider here
|
||||
/// than the pixels it holds), and the marching ants stay on the box through a move, a scale, a
|
||||
/// rotation and a distort, before anything is applied. Applying leaves them there.
|
||||
#[test]
|
||||
fn the_box_is_the_selection_and_the_ants_follow_it() {
|
||||
let ctx = gpu_ctx();
|
||||
let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24));
|
||||
let xf = ViewXform {
|
||||
rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)),
|
||||
zoom: 2.0,
|
||||
center: [32.0, 32.0],
|
||||
flip: false,
|
||||
rotation: 0.0,
|
||||
aspect: 1.0,
|
||||
};
|
||||
app.run("select.rect", json!({"x": 4, "y": 4, "width": 30, "height": 26})).unwrap();
|
||||
assert_eq!(ants_bounds(&app, &xf), None, "no box open: the canvas draws them where they are");
|
||||
begin(&mut app, &ctx).unwrap();
|
||||
let rest = corners([4.0, 4.0, 34.0, 30.0]);
|
||||
assert_eq!(app.ui.transform.as_ref().unwrap().quad, rest, "the box is the selection, not the 16 px square in it");
|
||||
assert!(rects_match(ants_bounds(&app, &xf).unwrap(), screen_bounds(&xf, &rest)), "untouched, the ants are where they were");
|
||||
|
||||
let on_the_box = |app: &PhotocraftApp, what: &str| {
|
||||
let quad = app.ui.transform.as_ref().unwrap().quad;
|
||||
let (ants, boxed) = (ants_bounds(app, &xf).unwrap(), screen_bounds(&xf, &quad));
|
||||
assert!(rects_match(ants, boxed), "{what}: ants {ants:?}, box {boxed:?}");
|
||||
};
|
||||
if let Some(t) = app.ui.transform.as_mut() {
|
||||
t.quad = t.quad.map(|[x, y]| [x + 20.0, y + 10.0]);
|
||||
t.pivot = [t.pivot[0] + 20.0, t.pivot[1] + 10.0];
|
||||
}
|
||||
on_the_box(&app, "moved");
|
||||
let moved = app.ui.transform.as_ref().unwrap().quad;
|
||||
scale_about_pivot(&mut app, 0.5, 1.5);
|
||||
on_the_box(&app, "scaled");
|
||||
rotate_about_pivot(&mut app, 0.6);
|
||||
on_the_box(&app, "rotated");
|
||||
if let Some(t) = app.ui.transform.as_mut() {
|
||||
t.quad[2] = [t.quad[2][0] + 9.0, t.quad[2][1] + 13.0];
|
||||
}
|
||||
on_the_box(&app, "distorted");
|
||||
|
||||
// Applied as moved only: the outline is where the ants showed it.
|
||||
if let Some(t) = app.ui.transform.as_mut() {
|
||||
t.quad = moved;
|
||||
}
|
||||
commit(&mut app);
|
||||
assert!(app.ui.transform.is_none());
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), photocraft_geom::Rect::new(24, 14, 54, 40));
|
||||
assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(), photocraft_geom::Rect::new(28, 18, 44, 34));
|
||||
}
|
||||
|
||||
/// #5297: in Warp mode the ants bend with the mesh, and past a Distort's horizon they stop
|
||||
/// rather than run off to infinity.
|
||||
#[test]
|
||||
fn the_ants_follow_a_warp_and_stop_at_a_distorts_horizon() {
|
||||
let ctx = gpu_ctx();
|
||||
let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 56, 56));
|
||||
let xf = ViewXform {
|
||||
rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)),
|
||||
zoom: 2.0,
|
||||
center: [32.0, 32.0],
|
||||
flip: false,
|
||||
rotation: 0.0,
|
||||
aspect: 1.0,
|
||||
};
|
||||
app.run("select.rect", json!({"x": 12, "y": 12, "width": 40, "height": 40})).unwrap();
|
||||
begin(&mut app, &ctx).unwrap();
|
||||
let rest = corners([12.0, 12.0, 52.0, 52.0]);
|
||||
|
||||
// Two corners dragged across each other put half the box past the horizon.
|
||||
if let Some(t) = app.ui.transform.as_mut() {
|
||||
t.quad = [[12.0, 12.0], [52.0, 12.0], [20.0, 40.0], [44.0, 40.0]];
|
||||
}
|
||||
let ants = ants_bounds(&app, &xf).unwrap();
|
||||
assert!(ants == egui::Rect::NOTHING || (ants.is_finite() && ants.width() < 1e5 && ants.height() < 1e5), "{ants:?}");
|
||||
|
||||
if let Some(t) = app.ui.transform.as_mut() {
|
||||
t.quad = rest;
|
||||
}
|
||||
enter_warp(&mut app, &ctx);
|
||||
let arc = Warp::preset(WarpStyle::Arc, 50.0, [12.0, 12.0, 52.0, 52.0]);
|
||||
app.ui.transform.as_mut().unwrap().warp = Some(arc.clone());
|
||||
let ants = ants_bounds(&app, &xf).unwrap();
|
||||
assert!(!rects_match(ants, screen_bounds(&xf, &rest)), "the outline left its place: {ants:?}");
|
||||
let warped: Vec<[f64; 2]> = rest.iter().map(|p| arc.map(p[0], p[1])).map(|(x, y)| [x, y]).collect();
|
||||
assert!(ants.expand(2.0).contains_rect(screen_bounds(&xf, &warped)), "the warped corners are on it: {ants:?}");
|
||||
}
|
||||
|
||||
/// Transform Selection moves the selection outline, not a layer: selecting a layer keeps it open.
|
||||
#[test]
|
||||
fn selecting_another_layer_keeps_a_transform_selection_open() {
|
||||
|
||||
@@ -343,3 +343,46 @@ fn the_first_drag_from_the_move_tools_controls_undoes() {
|
||||
key(&mut h, Modifiers::COMMAND, Key::Z);
|
||||
assert!(close(quad(&h), [[100.0, 100.0], [200.0, 100.0], [200.0, 160.0], [100.0, 160.0]]), "{:?}", quad(&h));
|
||||
}
|
||||
|
||||
/// #3402's layer-switch case (#5297): selected pixels moved with the Move tool, then moved again
|
||||
/// in the Free Transform box, land where the box left them when another layer is picked.
|
||||
#[test]
|
||||
fn picking_another_layer_applies_the_transform_of_moved_selected_pixels() {
|
||||
let mut h = harness();
|
||||
let layer = h.state().session.active().unwrap().active_layer.unwrap();
|
||||
h.state_mut().run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap();
|
||||
drag(&mut h, [150.0, 130.0], [250.0, 180.0]);
|
||||
begin(&mut h);
|
||||
// Away from the centre, where a press would take the reference point instead.
|
||||
drag(&mut h, [220.0, 165.0], [240.0, 175.0]);
|
||||
assert_eq!(quad(&h), [[220.0, 160.0], [320.0, 160.0], [320.0, 220.0], [220.0, 220.0]]);
|
||||
let other = h.state().session.active().unwrap().doc.layers.iter().map(|l| l.id).find(|id| *id != layer).unwrap();
|
||||
h.state_mut().run("layer.select", json!({"layer": other.0})).unwrap();
|
||||
crate::transform_tool::end_if_left(h.state_mut());
|
||||
h.run_steps(3);
|
||||
assert!(h.state().ui.transform.is_none(), "picking another layer applies the transform");
|
||||
let st = h.state().session.active().unwrap();
|
||||
let landed = photocraft_geom::Rect::new(220, 160, 320, 220);
|
||||
let (pixels, selection) = (st.doc.layer(layer).unwrap().surface().unwrap().content_bounds(), st.doc.selection.as_ref().map(|s| s.content_bounds()));
|
||||
assert_eq!((pixels, selection), (landed, Some(landed)));
|
||||
}
|
||||
|
||||
/// #5297 through the real canvas: ⌘T with a selection wider than the layer opens the box on the
|
||||
/// selection, and dragging it moves the selected pixels and the selection together.
|
||||
#[test]
|
||||
fn free_transform_opens_on_the_selection_and_moves_it_with_the_pixels() {
|
||||
let mut h = harness();
|
||||
let layer = h.state().session.active().unwrap().active_layer.unwrap();
|
||||
// The left 60 px of the red rectangle, and empty layer to its left, above and below.
|
||||
h.state_mut().run("select.rect", json!({"x": 60, "y": 80, "width": 100, "height": 120})).unwrap();
|
||||
begin(&mut h);
|
||||
assert_eq!(quad(&h), [[60.0, 80.0], [160.0, 80.0], [160.0, 200.0], [60.0, 200.0]]);
|
||||
drag(&mut h, [80.0, 100.0], [130.0, 130.0]);
|
||||
assert_eq!(quad(&h), [[110.0, 110.0], [210.0, 110.0], [210.0, 230.0], [110.0, 230.0]]);
|
||||
key(&mut h, Modifiers::NONE, Key::Enter);
|
||||
assert!(h.state().ui.transform.is_none());
|
||||
let st = h.state().session.active().unwrap();
|
||||
assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), photocraft_geom::Rect::new(110, 110, 210, 230));
|
||||
// What stayed (160..200 × 100..160) and what moved (to 150..210 × 130..190).
|
||||
assert_eq!(st.doc.layer(layer).unwrap().surface().unwrap().content_bounds(), photocraft_geom::Rect::new(150, 100, 210, 190));
|
||||
}
|
||||
@@ -985,6 +985,11 @@ fn form(app: &mut PhotocraftApp, command: &str, label: &str, fields: Value, choi
|
||||
app.ui.open_dialog(DialogKind::Command, f)
|
||||
}
|
||||
|
||||
/// The Batch and Image Processor dialogs' "Include All Subfolders" checkbox reads as Photoshop's.
|
||||
fn subfolders_label() -> Value {
|
||||
json!({"includeSubfolders": tl!("Include All Subfolders")})
|
||||
}
|
||||
|
||||
/// Alt+Cancel (Reset): restore the `__form` params captured at open.
|
||||
pub fn reset_form(f: &mut Map<String, Value>) {
|
||||
if !f.contains_key("__form") {
|
||||
@@ -1322,7 +1327,7 @@ fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value)
|
||||
),
|
||||
"file.scripts.imageProcessor" => dialog(
|
||||
app,
|
||||
json!({"input": dir, "output": format!("{dir}/processed"), "format": "jpg", "quality": 8, "width": 0, "height": 0, "convertToSrgb": true}),
|
||||
json!({"input": dir, "includeSubfolders": false, "__labels": subfolders_label(), "output": format!("{dir}/processed"), "format": "jpg", "quality": 8, "width": 0, "height": 0, "convertToSrgb": true}),
|
||||
json!({"format": ["jpg", "png", "psd", "tiff", "webp"]}),
|
||||
),
|
||||
"file.automate.batch" => {
|
||||
@@ -1333,7 +1338,7 @@ fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value)
|
||||
let name = action.name.clone();
|
||||
dialog(
|
||||
app,
|
||||
json!({"action": name, "steps": steps, "input": dir, "output": format!("{dir}/batch"), "format": "same", "quality": null, "__batchQuality": 8, "naming": "", "startingSerial": 1}),
|
||||
json!({"action": name, "steps": steps, "input": dir, "includeSubfolders": false, "__labels": subfolders_label(), "output": format!("{dir}/batch"), "format": "same", "quality": null, "__batchQuality": 8, "naming": "", "startingSerial": 1}),
|
||||
json!({"format": ["same", "png", "jpg", "psd", "tiff", "webp"]}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -359,6 +359,32 @@ fn lookup_export_dialog_uses_the_current_adjustment_selection() {
|
||||
assert!(direct["cube"].as_str().unwrap().contains("LUT_3D_SIZE 3"));
|
||||
}
|
||||
|
||||
/// Batch and Image Processor carry Photoshop's "Include All Subfolders" checkbox (AUTO-219-5,
|
||||
/// #3753): off by default, and confirming it on processes a subfolder's images too.
|
||||
#[test]
|
||||
fn batch_dialogs_include_all_subfolders() {
|
||||
let (mut app, ctx) = app_with(1);
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-ui-batch-subfolders-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("in/sub")).unwrap();
|
||||
let input = dir.join("in").to_string_lossy().into_owned();
|
||||
app.run("file.saveACopy", json!({"path": dir.join("in/sub/a.png").to_string_lossy()})).unwrap();
|
||||
app.session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Invert", vec![("image.adjustments.invert".into(), json!({}))]));
|
||||
for (id, out) in [("file.automate.batch", "batch"), ("file.scripts.imageProcessor", "processed")] {
|
||||
let d = menu(&mut app, &ctx, id, json!({})).unwrap()["dialog"].as_u64().unwrap();
|
||||
let fields = &mut app.ui.dialog_mut(d).unwrap().fields;
|
||||
assert_eq!(fields["includeSubfolders"], json!(false), "{id}");
|
||||
assert_eq!(fields["__labels"]["includeSubfolders"], json!("Include All Subfolders"), "{id}");
|
||||
fields.insert("input".into(), json!(input));
|
||||
fields.insert("output".into(), json!(dir.join(out).to_string_lossy()));
|
||||
fields.insert("includeSubfolders".into(), json!(true));
|
||||
let r = crate::dialogs::confirm(&mut app, d).unwrap();
|
||||
assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{id}: {r}");
|
||||
assert!(dir.join(out).join("sub").is_dir(), "{id} keeps the subfolder: {r}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Float in Window takes the document and the screen position a dragged-off tab was dropped at
|
||||
/// (#3733); bad params are errors, not panics.
|
||||
#[test]
|
||||
|
||||
@@ -53,6 +53,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
|
||||
- `ui.set` also accepts `gradientBlendMode` (a layer blend mode name, such as `Difference`) and `gradientClassic` (boolean) for the Gradient tool options bar.
|
||||
- `ui.set` also accepts `camTransformOnDrop` (boolean), the Content-Aware Move tool's Transform On Drop checkbox: a drop then puts a scale/rotate box on the patch (`ui.inspect` › `camTransform`: its document/revision, drag `offset` and `frame`), driven with `ui.pointer` (handles as Free Transform's; outside the box rotates), committed with `ui.key Enter` (one `paint.contentAwareMove` with `scaleX`, `scaleY`, `rotate`) or dropped with `Escape`.
|
||||
- `ui.set` also accepts `tileGrid` (boolean), a developer overlay of the active layer's storage tiles: the tile grid over the document, every stored tile filled and labelled `tx,ty`, tiles with identical pixels in a shared colour and unique ones in blue. It has no menu item and View › Extras doesn't hide it. `ui.inspect` reports it as `view.tile_grid`.
|
||||
- `ui.set` also accepts `layerFilter` (#5048), the Layers panel filter row: `{by?, kinds?, name?, mode?}`, any subset. `by` is `kind`, `name` or `mode` (the filter-type dropdown); `kinds` lists the Kind toggles that are on (`pixel`, `adjustment`, `type`, `shape`, `smart`); `name` matches part of a layer name, ignoring case; `mode` is a blend mode name (`Multiply`, `Pass Through`). Kind and Name filter only once a kind is on or text is typed; Mode always filters, by Normal at first, as in Photoshop. Fields left out keep their value; a bad one is an error and changes nothing.
|
||||
- Each painting tool keeps its own brush, as in Photoshop: `tools.setBrush` and `ui.set {brushSize}` change the active tool's brush, and switching tools swaps in that tool's own (size, hardness, mode, opacity, flow, dynamics, smoothing). A tool used for the first time starts from the brush in hand. The colours, the erase flag and the stroke seed stay shared. So `ui.set {tool: "eraser", brushSize: 12}` sets the Eraser's size, and `ui.set {tool: "brush"}` afterwards brings the Brush's own size back.
|
||||
- `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer}` returns the colour such a sample picks.
|
||||
- `ui.set` also accepts the Crop tool's overlay menu (#1919): `cropOverlay` (`thirds`, `grid`, `diagonal`, `triangle`, `goldenRatio`, `goldenSpiral`), `cropOverlayShow` (`auto`: only while the crop box is dragged, Photoshop's default; `always`; `never`) and `cropOverlayOrientation` (0..3; Triangle has two orientations and Golden Spiral four, the others ignore it). `ui.inspect` reports them under `toolOptions` (`crop_overlay`, `crop_overlay_show`, `crop_overlay_orientation`). In the app, O cycles the overlay and ⇧O its orientation while the Crop tool shows a box.
|
||||
|
||||
+4
-3
@@ -1,6 +1,6 @@
|
||||
# Where PhotoCraft falls short of Photoshop
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (G10: a TIFF's first alpha channel opens and saves, #5301; earlier: G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (G10: a TIFF's first alpha channel opens and saves, #5301; earlier: G11: Batch Include All Subfolders landed; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **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
|
||||
@@ -92,8 +92,8 @@ what an agent can't finish alone.
|
||||
- **2026-10-13 evidence:** Batch supports [output naming templates](batch-naming.md) using
|
||||
`{name}`, `{serial}` and a captured UTC `{date}`, with a starting serial number. Colliding
|
||||
names remain errors; custom output names cannot replace inputs. AUTO-219-5 stays partial.
|
||||
- **Missing:** document-independent action recording (AUTO-219-1), Batch recursion, open-document inputs, progress/cancel and an error-log file
|
||||
(AUTO-219-5), ExtendScript/UXP compatibility. `.atn` steps outside the
|
||||
- **Missing:** document-independent action recording (AUTO-219-1), Batch open-document inputs, progress/cancel and an error-log file
|
||||
(AUTO-219-5; Include All Subfolders landed 2026-10-11, #3753), ExtendScript/UXP compatibility. `.atn` steps outside the
|
||||
mapped events (paths, scripts, Generative Fill, Filter Gallery effects other than Spatter,
|
||||
Duplicate Layers into a new document, Bitmap halftone screens…) load as kept Photoshop steps
|
||||
that fail at playback by name.
|
||||
@@ -287,6 +287,7 @@ what an agent can't finish alone.
|
||||
| 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 |
|
||||
| 2026-10-11 | minor | G8: Character panel OpenType buttons landed (TYPE-218-5, #3752); Numerals and Stylistic Sets submenus still missing |
|
||||
| 2026-10-11 | minor | G11: Batch and Image Processor gained Include All Subfolders (AUTO-219-5 stays partial; #3753) |
|
||||
| 2026-10-10 | minor | G2: recorded Tilt-Shift computation/filtered-proxy measurements and limits; gap and estimate remain open |
|
||||
| 2026-10-10 | minor | Checked against the alpha gate (no alpha blockers); #2374 marked closed |
|
||||
| 2026-10-10 | major | First version, from the full re-measure against Photoshop 2026 27.11.0 and the open issues |
|
||||
+3
-3
@@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
|
||||
| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) |
|
||||
| [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 241/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 149/256, round trip ≥ 258/256 |
|
||||
| [Tools](#tools) | 29 | 13 | 1 | |
|
||||
| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 159 (target 0) |
|
||||
| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 160 (target 0) |
|
||||
| [Type](#type) | 4 | 3 | 2 | |
|
||||
| [Automation](#automation) | 5 | 2 | 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 |
|
||||
@@ -176,7 +176,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
|
||||
|
||||
## Workspace and UI
|
||||
|
||||
**Settings that do nothing: 26 of 159** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
|
||||
**Settings that do nothing: 26 of 160** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
|
||||
|
||||
Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`.
|
||||
|
||||
@@ -231,7 +231,7 @@ Menu wiring (`docs/parity-checklist.md`): 631 of 631 menu items live (100.0%). T
|
||||
| AUTO-219-2 | Actions panel: step and dialog toggles, reorder, delete a step, Stop, sets, .atn import | done | [#219](https://github.com/storytold/photocraft/issues/219) | 2026-10-12: set folders (collapsible, drag between sets, actions.assignSet), dialog toggle column (playback opens the step's dialog seeded with its values and resumes on OK; actions.dialog), Insert Stop… (actions.insert), step toggles, reorder, delete a step; 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 and file_cmds/batch_naming.rs: folder/array input, per-file errors, {name}/{serial}/{date} output templates and starting serial; no recursion, open-documents source, cancel or error-log file |
|
||||
| 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 and file_cmds/batch_naming.rs: folder/array input, per-file errors, {name}/{serial}/{date} output templates and starting serial, Include All Subfolders (includeSubfolders: depth/loop/file-count bounded, results keep their subfolder; Batch and Image Processor dialogs, #3753); no open-documents source, cancel or error-log file |
|
||||
| AUTO-219-6 | Plug-in ABI v2: panel kind, progress/cancel calls, read other layers, Last Filter repeats | missing | [#219](https://github.com/storytold/photocraft/issues/219) | runtime.rs:15 ABI_VERSION = 1; manifest.rs:18 Kind::Filter only |
|
||||
| AUTO-219-7 | Local ONNX models behind a flag, managed in Preferences; subject select, background removal | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No ONNX runtime dependency |
|
||||
| AUTO-219-8 | xtask check that every panel button routes through a command id | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No such xtask check |
|
||||
|
||||
+7
-1
@@ -1,6 +1,6 @@
|
||||
# UI parity: tools, handles, modifiers and feel
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the
|
||||
handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,
|
||||
@@ -53,6 +53,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
|
||||
| Group remembers the last tool used | partial | L always resets to Lasso (#2608) |
|
||||
| Press-and-hold or click-drag opens the flyout | missing | right-click only (#2301) |
|
||||
| Edit Toolbar customization | done | `edit.toolbar` |
|
||||
| Last selected tool restored after quitting and relaunching; temporary tool switches excluded | done | `tool_memory.rs`; `prefs_ui::tests::selected_tool_survives_a_restart_without_option_changes`, `selected_tool_excludes_temporary_switches` |
|
||||
|
||||
## Free Transform (⌘T) and transform handles
|
||||
|
||||
@@ -66,6 +67,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
|
||||
| ⌘-corner distort, ⌘-edge skew, ⌘⌥⇧ perspective, ⇧ rotate in 15° steps | done | |
|
||||
| Warp: presets, bend, split crosswise/vertical/horizontal, 3×3–5×5 and custom grids | done | |
|
||||
| Options bar X/Y, W/H % with link, angle | done | |
|
||||
| With a selection, the box is the selection's rectangle and the marching ants follow the box live | done | `transform_frame`, `transform_tool.rs` (`draw_selection`): move, scale, rotate, skew, distort, perspective and warp, before the transform is applied; also the Move tool's Show Transform Controls (#5297) |
|
||||
| Options bar H/V skew fields | done | `transform_tool.rs` (`Parts`, `skew_about_pivot`): W/H, angle and skew read as Photoshop decomposes the box; `skew_fields_lean_the_box_about_the_reference_point` |
|
||||
| Interpolation in the options bar | partial | Bicubic/Bilinear/Nearest; no Bicubic Smoother/Sharper/Automatic, Preserve Details |
|
||||
| Commit/cancel buttons in the options bar | missing | #2442 |
|
||||
@@ -210,6 +212,7 @@ Paragraph; the rest open as in-app floating windows.
|
||||
| Themes: Photoshop's four greys | partial | five themes; #2661 |
|
||||
| Document tabs: overflow, context menu, reorder | done | UI-217-6; middle-click close #2570 |
|
||||
| Layers panel: wheel steps blend modes, drop on New/Trash | partial | UI-217-14 |
|
||||
| Layers panel filter-type dropdown (Kind, Name, Effect, Mode, Attribute, Color, Smart Object, Selected, Artboard) | partial | Kind, Name and Mode; the other six missing. `layer_filter_ui.rs`, `ui.set {layerFilter}` (#5048) |
|
||||
| Smart filter rows: click selects, drag onto another smart object moves, ⌥-drag copies, drag onto Delete removes | done | `smart_ui.rs`, `layer.smartFilter.transfer` (#4271) |
|
||||
| Smart filter rows: drag up or down the stack to reorder (a line marks the drop; the bottom filter is applied first) | done | `smart_ui.rs` `reorder_drop`, `layer.smartFilter.move` |
|
||||
|
||||
@@ -217,6 +220,7 @@ Paragraph; the rest open as in-app floating windows.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-13 | minor | Layers panel filter row: Kind is a real dropdown with Kind, Name and Mode filters, drivable by `ui.set {layerFilter}` (#5048); row added as partial |
|
||||
| 2026-10-13 | minor | Stale "missing tool" rows corrected against main: Color Replacement (`paint.colorReplacement`), Red Eye (`paint.redEye`) and Add/Delete Anchor Point (the P flyout cycle) are live toolbar tools, so only Art History Brush is missing; no percentage or estimate changed |
|
||||
| 2026-10-13 | minor | Smart object perspective (non-affine) corrected to done: #426 landed four-corner placements with PSD round trip; scorecard FILE-215-6 flipped |
|
||||
| 2026-10-10 | major | First version, from a source audit against Photoshop 2026 27.11.0's shortcuts file and the open issues |
|
||||
@@ -234,3 +238,5 @@ Paragraph; the rest open as in-app floating windows.
|
||||
| 2026-10-12 | minor | Smart filter rows can be selected, and dragged (⌥: copied) onto another smart object or onto Delete (#4271) |
|
||||
| 2026-10-12 | minor | Free Transform options bar: H and V skew fields; a sheared box reads as skew instead of a taller H |
|
||||
| 2026-10-13 | minor | Smart filter rows can be dragged up or down their stack to reorder the filters |
|
||||
| 2026-10-14 | minor | Last selected tool restored across launches; temporary overrides excluded, explicit Eraser choices retained, and final selection flushed on normal exit |
|
||||
| 2026-10-13 | minor | Free Transform with a selection: the box is the selection's rectangle, and the marching ants follow it while it is transformed (#5297) |
|
||||
@@ -44,7 +44,7 @@ id = "AUTO-219-5"
|
||||
target = "Batch: subfolders, open documents, naming template, progress/cancel, error log, stop"
|
||||
status = "partial"
|
||||
issue = 219
|
||||
note = "file_cmds.rs and file_cmds/batch_naming.rs: folder/array input, per-file errors, {name}/{serial}/{date} output templates and starting serial; no recursion, open-documents source, cancel or error-log file"
|
||||
note = "file_cmds.rs and file_cmds/batch_naming.rs: folder/array input, per-file errors, {name}/{serial}/{date} output templates and starting serial, Include All Subfolders (includeSubfolders: depth/loop/file-count bounded, results keep their subfolder; Batch and Image Processor dialogs, #3753); no open-documents source, cancel or error-log file"
|
||||
|
||||
[[item]]
|
||||
id = "AUTO-219-6"
|
||||
|
||||
Reference in new issue
Block a user