Merge pull request #14007 from Bobderto/codex/13889-image-processor-formats

Export JPEG, PSD, and TIFF in one Image Processor run
This commit is contained in:
David Mann authored and GitHub committed 2026-11-14 01:38:13 +01:00
commit eb174cf122
8 files changed
+636 -58

No files matched your search

+1 -1
View File
@@ -377,7 +377,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Image Processor…",
&["File", "Scripts"],
None,
r##"{"source":"folder|current|open"="folder" (current processes a copy of the active document; open processes copies of all open documents, including unsaved edits; originals and history stay unchanged),"input":folder|[paths]? (required for folder source),"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,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it),"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##"{"source":"folder|current|open"="folder" (current processes a copy of the active document; open processes copies of all open documents, including unsaved edits; originals and history stay unchanged),"input":folder|[paths]? (required for folder source),"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,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false,"jpeg":{enabled?:bool=true,quality?:1..12=5,convertToSrgb?:bool=false,resize?:bool=false,width?:1..30000=1,height?:1..30000=1}|false?,"psd":{enabled?:bool=true,maximizeCompatibility?:bool=true,resize?:bool=false,width?:1..30000=1,height?:1..30000=1}|false?,"tiff":{enabled?:bool=true,lzw?:bool=false,resize?:bool=false,width?:1..30000=1,height?:1..30000=1}|false?} → {files, errors} (without format, supplying jpeg/psd/tiff selects per-format mode; omitted, null, false or disabled sections are skipped; at least one must be enabled. Errors in per-format mode identify the format.)"##,
native,
image_processor
),
@@ -0,0 +1,162 @@
use std::path::{Path, PathBuf};
use std::sync::Arc;
use photocraft_doc::{ColorMode, Document};
use serde_json::{Value, json};
use crate::Session;
const COMMAND: &str = "file.scripts.imageProcessor";
fn document(s: &mut Session, name: &str, depth: u32) -> crate::Result<()> {
s.execute("file.new", json!({"name": name, "width": 40, "height": 20, "depth": depth, "resolution": 300, "background": "#b05980"}))?;
s.execute("layer.new.layer", json!({"name": "Artwork"}))?;
Ok(())
}
fn paths(result: &Value) -> Result<Vec<PathBuf>, serde_json::Error> {
serde_json::from_value(result["files"].clone())
}
fn reopen(path: &Path) -> Result<Document, Box<dyn std::error::Error>> {
Ok(photocraft_io::import(&path.to_string_lossy(), &std::fs::read(path)?)?.document)
}
#[test]
fn one_run_reopens_three_independently_sized_formats() {
let dir = tempfile::tempdir().unwrap();
let mut s = Session::new();
document(&mut s, "Source", 16).unwrap();
s.execute("edit.assignProfile", json!({"profile": "display-p3"})).unwrap();
s.execute("select.all", json!({})).unwrap();
let before = s.active().unwrap();
let (doc, target, history, revision) = (before.doc.clone(), before.layer_target(), before.history.entries(), before.revision);
let result = s
.execute(
COMMAND,
json!({
"source": "current", "output": dir.path(),
"jpeg": {"quality": 7.6, "convertToSrgb": true, "resize": true, "width": 20, "height": 18},
"psd": {"resize": true, "width": 10, "height": 10},
"tiff": {"lzw": true, "resize": true, "width": 100, "height": 100}
}),
)
.unwrap();
assert_eq!(result["errors"], json!([]), "{result}");
let files = paths(&result).unwrap();
assert_eq!(files, ["Source.jpg", "Source.psd", "Source.tif"].map(|name| dir.path().join(name)));
let jpeg = reopen(&files[0]).unwrap();
let psd = reopen(&files[1]).unwrap();
let tiff = reopen(&files[2]).unwrap();
let tiff_info = photocraft_codecs::tiff_info(&std::fs::read(&files[2]).unwrap()).unwrap();
assert_eq!(tiff_info.pages[0].compression, 5, "TIFF uses LZW compression");
assert_eq!((jpeg.size.width, jpeg.size.height), (20, 10));
assert_eq!((psd.size.width, psd.size.height), (10, 5));
assert_eq!(tiff.size, doc.size);
assert_eq!(jpeg.depth, photocraft_color::SampleType::U8);
assert_eq!(jpeg.layers.len(), 1);
assert_eq!(jpeg.mode, ColorMode::Rgb);
assert!(jpeg.icc_profile.is_some());
assert_ne!(jpeg.icc_profile, doc.icc_profile);
assert_eq!(crate::color_cmds::document_profile(&jpeg).description, photocraft_cms::Builtin::Srgb.profile().description);
for output in [psd, tiff] {
assert_eq!(output.depth, doc.depth);
assert_eq!(output.mode, doc.mode);
assert_eq!(output.resolution_dpi, 300.0);
assert_eq!(output.icc_profile, doc.icc_profile);
assert_eq!(output.layers.iter().map(|layer| &layer.name).collect::<Vec<_>>(), doc.layers.iter().map(|layer| &layer.name).collect::<Vec<_>>());
}
let after = s.active().unwrap();
assert!(Arc::ptr_eq(&after.doc, &doc));
assert_eq!(after.layer_target(), target);
assert_eq!(after.history.entries(), history);
assert_eq!(after.revision, revision);
}
#[test]
fn every_nonempty_format_combination_processes_all_open_documents() {
let mut s = Session::new();
document(&mut s, "First", 8).unwrap();
document(&mut s, "Second", 8).unwrap();
let formats = [("jpeg", "jpg"), ("psd", "psd"), ("tiff", "tif")];
for mask in 1..8 {
let dir = tempfile::tempdir().unwrap();
let mut params = json!({"source": "open", "output": dir.path()});
let mut expected = Vec::new();
for (bit, (key, ext)) in formats.iter().enumerate() {
let enabled = (mask & (1 << bit)) != 0;
params[*key] = json!({"enabled": enabled});
if enabled {
expected.extend(["First", "Second"].map(|name| dir.path().join(format!("{name}.{ext}"))));
}
}
let result = s.execute(COMMAND, params).unwrap();
assert_eq!(result["errors"], json!([]), "{result}");
assert_eq!(paths(&result).unwrap(), expected, "mask {mask}");
}
}
#[test]
fn invalid_settings_fail_before_any_format_writes() {
let dir = tempfile::tempdir().unwrap();
let mut s = Session::new();
document(&mut s, "Source", 8).unwrap();
for settings in [
json!({"jpeg": false, "psd": {"enabled": false}, "tiff": null}),
json!({"jpeg": {}, "psd": 7}),
json!({"jpeg": {}, "tiff": {"lzw": "true"}}),
json!({"jpeg": {"quality": 0}}),
json!({"jpeg": {"quality": "5"}}),
json!({"jpeg": {}, "psd": {"resize": true, "width": 30001}}),
json!({"jpeg": {}, "tiff": {"resize": true, "height": 0}}),
] {
let mut params = settings;
params["source"] = json!("current");
params["output"] = json!(dir.path().join("out"));
assert!(s.execute(COMMAND, params.clone()).is_err(), "{params}");
assert!(!dir.path().join("out").exists());
}
}
#[test]
fn folder_errors_identify_the_format_and_do_not_replace_sources() {
let dir = tempfile::tempdir().unwrap();
let mut s = Session::new();
document(&mut s, "Source", 8).unwrap();
let source = dir.path().join("source.psd");
s.execute("file.saveACopy", json!({"path": source})).unwrap();
let original = std::fs::read(&source).unwrap();
let result = s
.execute(
COMMAND,
json!({
"input": [source], "output": dir.path(), "jpeg": {}, "psd": {}, "tiff": {"enabled": false}
}),
)
.unwrap();
assert_eq!(paths(&result).unwrap(), [dir.path().join("source.jpg")]);
assert_eq!(result["errors"].as_array().unwrap().len(), 1);
assert_eq!(result["errors"][0]["format"], "psd");
assert_eq!(std::fs::read(&source).unwrap(), original);
}
#[test]
fn legacy_format_and_resize_parameters_still_work() {
let dir = tempfile::tempdir().unwrap();
let mut s = Session::new();
document(&mut s, "Source", 8).unwrap();
let result = s
.execute(
COMMAND,
json!({
"source": "current", "output": dir.path(), "format": "png", "width": 20
}),
)
.unwrap();
assert_eq!(result["errors"], json!([]));
let files = paths(&result).unwrap();
assert_eq!(files, [dir.path().join("Source.png")]);
let png = reopen(&files[0]).unwrap();
assert_eq!((png.size.width, png.size.height), (20, 10));
}
+133 -5
View File
@@ -1,4 +1,4 @@
use super::batch_run::{batch_inputs_tree, process_document_copies, process_tree};
use super::batch_run::{BatchInput, batch_inputs_tree, process_document_copies, process_tree};
use super::open::import_opened;
use super::paths::{file_name, list_images, read_file, stem, untitled_name};
use super::save::SaveOpts;
@@ -7,6 +7,9 @@ use super::{
str_param,
};
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "image_processor_formats_tests.rs"]
mod image_processor_formats_tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "image_processor_tests.rs"]
mod image_processor_tests;
@@ -97,14 +100,17 @@ pub(super) fn parse_steps(v: &Value) -> Result<Vec<(String, Value)>> {
/// edits without modifying the original documents. Invalid parameters and missing documents
/// return an error; processing failures and output-name collisions appear in per-file errors.
pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "file.scripts.imageProcessor";
let cmd = IMAGE_PROCESSOR;
let source = match p.get("source") {
None | Some(Value::Null) => "folder",
Some(Value::String(source)) if matches!(source.as_str(), "folder" | "current" | "open") => source.as_str(),
_ => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "source must be folder, current or open".into() }),
};
let output = str_param(p, "output", cmd)?.to_string();
let format = p.get("format").and_then(Value::as_str).unwrap_or("jpg").to_string();
if p.get("format").is_none() && ["jpeg", "psd", "tiff"].iter().any(|key| p.get(key).is_some()) {
return image_processor_formats(s, p, source, &output);
}
let format = p.get("format").and_then(Value::as_str).unwrap_or("jpg");
// The format becomes a filename extension, never a path supplied by a caller.
if format.trim_start_matches('.').is_empty() || format.contains(['/', '\\']) || format.chars().any(char::is_control) {
return Err(EngineError::BadParams { cmd: cmd.into(), msg: "format must be a filename extension".into() });
@@ -126,17 +132,139 @@ pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
};
let r = if source == "folder" {
let inputs = batch_inputs_tree(p, cmd, &output)?;
process_tree(s, &inputs, &output, &format, save, "", &process)
process_tree(s, &inputs, &output, format, save, "", &process)
} else {
let documents = if source == "current" { vec![s.active().ok_or(EngineError::NoDocument)?] } else { s.documents().iter().collect() };
if documents.is_empty() {
return Err(EngineError::NoDocument);
}
process_document_copies(s, &documents, &output, &format, save, &process)
process_document_copies(s, &documents, &output, format, save, &process)
};
Ok(r)
}
const IMAGE_PROCESSOR: &str = "file.scripts.imageProcessor";
const IMAGE_PROCESSOR_NO_FORMAT: &str = "You must save to at least one file type.";
fn image_processor_param(message: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: IMAGE_PROCESSOR.into(), msg: message.into() }
}
struct ProcessorFormat {
extension: &'static str,
save: SaveOpts,
fit: Option<Value>,
srgb: bool,
}
fn processor_bool(options: &Value, key: &str, default: bool) -> Result<bool> {
match options.get(key) {
None => Ok(default),
Some(value) => value.as_bool().ok_or_else(|| image_processor_param(format!("{key} must be true or false"))),
}
}
fn processor_number(options: &Value, key: &str, default: f64, max: f64) -> Result<f64> {
match options.get(key) {
None => Ok(default),
Some(value) => {
value.as_f64().filter(|n| (1.0..=max).contains(n)).ok_or_else(|| image_processor_param(format!("{key} must be a number from 1 to {max}")))
}
}
}
fn processor_format(s: &Session, key: &str, extension: &'static str, options: &Value) -> Result<Option<ProcessorFormat>> {
if options.is_null() || options == &Value::Bool(false) {
return Ok(None);
}
if !options.is_object() {
return Err(image_processor_param(format!("{key} must be an object or false")));
}
if !processor_bool(options, "enabled", true)? {
return Ok(None);
}
let fit = if processor_bool(options, "resize", false)? {
let width = processor_number(options, "width", 1.0, 30_000.0)?;
let height = processor_number(options, "height", 1.0, 30_000.0)?;
Some(json!({"width": width, "height": height, "dontEnlarge": true}))
} else {
None
};
let (params, srgb) = match key {
"jpeg" => (json!({"quality": processor_number(options, "quality", 5.0, 12.0)?}), processor_bool(options, "convertToSrgb", false)?),
"psd" => (json!({"maximizeCompatibility": processor_bool(options, "maximizeCompatibility", true)?}), false),
_ => {
let compression = if processor_bool(options, "lzw", false)? { "lzw" } else { "none" };
(json!({"tiffLayers": true, "tiffCompression": compression}), false)
}
};
let save = SaveOpts::from_params(s, &params, IMAGE_PROCESSOR)?;
Ok(Some(ProcessorFormat { extension, save, fit, srgb }))
}
enum ProcessorInputs<'a> {
Folder(Vec<BatchInput>),
Documents(Vec<&'a crate::DocState>),
}
fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) -> Result<Value> {
// Resolve all settings and collect inputs before a format can write any files.
let mut formats = Vec::new();
for (key, extension) in [("jpeg", "jpg"), ("psd", "psd"), ("tiff", "tif")] {
if let Some(options) = p.get(key)
&& let Some(format) = processor_format(s, key, extension, options)?
{
formats.push(format);
}
}
if formats.is_empty() {
return Err(image_processor_param(IMAGE_PROCESSOR_NO_FORMAT));
}
let inputs = match source {
"folder" => ProcessorInputs::Folder(batch_inputs_tree(p, IMAGE_PROCESSOR, output)?),
"current" => ProcessorInputs::Documents(vec![s.active().ok_or(EngineError::NoDocument)?]),
_ if s.documents().is_empty() => return Err(EngineError::NoDocument),
_ => ProcessorInputs::Documents(s.documents().iter().collect()),
};
let mut files = Vec::new();
let mut errors = Vec::new();
for format in formats {
// The existing runners prepare fresh scratch documents for each output.
let process = |scratch: &mut Session, out: &str| {
if let ProcessorInputs::Folder(inputs) = &inputs
&& super::paths::is_file(out)
&& inputs.iter().any(|input| super::paths::same_file(&input.path, out))
{
return Err(EngineError::Other(format!("output would replace a source file: {out}")));
}
if let Some(fit) = &format.fit {
fit_image(scratch, fit)?;
}
if format.srgb {
scratch.execute("edit.convertToProfile", json!({"profile": "srgb", "flatten": true}))?;
}
Ok(false)
};
let mut result = match &inputs {
ProcessorInputs::Folder(inputs) => process_tree(s, inputs, output, format.extension, format.save, "", &process),
ProcessorInputs::Documents(documents) => process_document_copies(s, documents, output, format.extension, format.save, &process),
};
if let Some(Value::Array(written)) = result.get_mut("files").map(Value::take) {
files.extend(written);
}
if let Some(Value::Array(failed)) = result.get_mut("errors").map(Value::take) {
errors.extend(failed.into_iter().map(|mut failure| {
failure["format"] = json!(format.extension);
if let Some(Value::String(message)) = failure.get_mut("error") {
*message = format!("{}: {message}", format.extension);
}
failure
}));
}
}
Ok(json!({"files": files, "errors": errors}))
}
pub(super) fn load_files_into_stack(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "file.scripts.loadFilesIntoStack";
let paths: Vec<String> = match p.get("paths").or_else(|| p.get("input")) {
+10 -2
View File
@@ -563,7 +563,9 @@ fn button_row(
/// The default button's label: what OK means for this dialog.
fn ok_label(d: &Dialog) -> &'static str {
if d.kind == DialogKind::NewDocument {
if image_processor_ui::owns(&d.fields) {
tl!("Run")
} else if d.kind == DialogKind::NewDocument {
tl!("Create")
} else if crate::open_prompt::owns_memory(&d.fields) {
tl!("Open anyway")
@@ -632,6 +634,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
let mut drag = egui::Vec2::ZERO;
let mut close_clicked = false;
let mut sizing = false;
let mut processor_alert = None;
let mut fit_image_alert = None;
let area = match start {
Some(offset) => egui::Modal::default_area(id).anchor(egui::Align2::LEFT_TOP, offset),
@@ -725,7 +728,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
crate::widgets::hairline(ui);
ui.add_space(8.0);
crate::field_tab::begin(ui.ctx());
if fit_image_range::owns(&fields) {
if image_processor_ui::owns(&fields) {
processor_alert = image_processor_ui::body(ui, &mut fields);
} else if fit_image_range::owns(&fields) {
fit_image_alert = fit_image_range::body(ui, &mut fields);
} else {
outcome = dialog_body(app, ui, &d, &mut fields, id, interactive);
@@ -794,6 +799,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
{
outcome = Some(false);
}
outcome = image_processor_ui::finish(&mut app.ui, interactive, processor_alert, outcome);
outcome = fit_image_range::finish(&mut app.ui, interactive, fit_image_alert, outcome);
if let Some(dm) = app.ui.dialog_mut(d.id) {
dm.fields = fields;
@@ -1175,6 +1181,7 @@ fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result<Value, Str
pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
confirm_preflight(app, id)?;
image_processor_ui::preflight(&mut app.ui, id)?;
fit_image_range::preflight(&mut app.ui, id)?;
let d = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?;
match d.kind {
@@ -1331,6 +1338,7 @@ pub mod gallery_ui;
pub(crate) mod guide_edit;
pub mod guide_layout_ui;
pub mod history_options_ui;
mod image_processor_ui;
pub mod jpeg_options_ui;
#[cfg(test)]
mod label_column_tests;
@@ -0,0 +1,137 @@
//! File Type section of the Image Processor dialog.
use std::cell::Cell;
use serde_json::{Value, json};
use super::Fields;
use crate::{panels::options_bar::range_alert, state::UiState};
const FORMATS: [&str; 3] = ["jpeg", "psd", "tiff"];
const NO_FORMAT: &str = "You must save to at least one file type.";
pub(super) fn owns(fields: &Fields) -> bool {
fields.contains_key("__form") && fields.get("__command").and_then(Value::as_str) == Some("file.scripts.imageProcessor") && !fields.contains_key("format")
}
pub(super) fn preflight(ui: &mut UiState, id: u64) -> Result<(), String> {
if let Some(dialog) = ui.dialog_mut(id).filter(|dialog| owns(&dialog.fields))
&& !FORMATS.iter().any(|key| dialog.fields.get(*key).is_some_and(|options| options.is_object() && options.get("enabled") != Some(&Value::Bool(false))))
{
range_alert(ui, NO_FORMAT);
return Err(tl!(NO_FORMAT).into());
}
Ok(())
}
pub(super) fn finish(ui: &mut UiState, interactive: bool, alert: Option<&str>, outcome: Option<bool>) -> Option<bool> {
if interactive
&& outcome != Some(false)
&& let Some(alert) = alert
{
range_alert(ui, alert);
return None;
}
outcome
}
pub(super) fn body(ui: &mut egui::Ui, fields: &mut Fields) -> Option<&'static str> {
let height = (ui.ctx().content_rect().height() - super::DIALOG_CHROME).max(120.0);
egui::ScrollArea::vertical()
.id_salt("image-processor")
.max_height(height)
.show(ui, |ui| {
crate::view_cmds::form_body(ui, fields);
formats(ui, fields)
})
.inner
}
fn formats(ui: &mut egui::Ui, fields: &mut Fields) -> Option<&'static str> {
ui.add_space(8.0);
crate::widgets::hairline(ui);
ui.label(egui::RichText::new(tl!("File Type")).strong());
let mut alert = None;
for (key, label) in FORMATS.into_iter().zip([tl!("Save as JPEG"), tl!("Save as PSD"), tl!("Save as TIFF")]) {
let Some(options) = fields.get_mut(key).and_then(Value::as_object_mut) else { continue };
ui.push_id(key, |ui| {
let enabled = checkbox(ui, options, "enabled", label);
ui.indent("format-options", |ui| {
ui.add_enabled_ui(enabled, |ui| {
match key {
"jpeg" => {
ui.horizontal(|ui| number(ui, options, "quality", tl!("Quality"), 5.0, 12.0, &mut alert));
checkbox(ui, options, "convertToSrgb", tl!("Convert Profile to sRGB"));
}
"psd" => {
checkbox(ui, options, "maximizeCompatibility", tl!("Maximize Compatibility"));
}
_ => {
checkbox(ui, options, "lzw", tl!("LZW Compression"));
}
}
let resize = checkbox(ui, options, "resize", tl!("Resize to Fit"));
ui.add_enabled_ui(resize, |ui| {
ui.horizontal(|ui| {
number(ui, options, "width", tl!("W"), 1.0, 30_000.0, &mut alert);
number(ui, options, "height", tl!("H"), 1.0, 30_000.0, &mut alert);
ui.label(tl!("px"));
});
});
});
});
});
ui.add_space(4.0);
}
alert
}
fn checkbox(ui: &mut egui::Ui, options: &mut Fields, key: &str, label: &str) -> bool {
let mut enabled = options.get(key).and_then(Value::as_bool).unwrap_or(false);
if ui.checkbox(&mut enabled, label).changed() {
options.insert(key.into(), json!(enabled));
}
enabled
}
#[cfg(test)]
mod tests;
fn number(ui: &mut egui::Ui, options: &mut Fields, key: &str, label: &str, default: f64, max: f64, alert: &mut Option<&'static str>) {
let mut value = options.get(key).and_then(Value::as_f64).unwrap_or(default);
let warning = Cell::new(None);
ui.label(label);
if ui.is_enabled() {
crate::field_tab::register(ui.ctx(), ui.next_auto_id());
}
ui.add(egui::DragValue::new(&mut value).range(1.0..=max).max_decimals(if key == "quality" { 8 } else { 0 }).update_while_editing(false).custom_parser(
|text| {
let parsed = crate::widgets::parse_num(text);
warning.set(match parsed {
None => Some(invalid_entry(key)),
Some(value) if !(1.0..=max).contains(&value) => Some(closest_value(key)),
Some(_) => None,
});
parsed.map(|n| if key == "quality" { n } else { n.trunc() })
},
))
.accessible_name(label);
options.insert(key.into(), json!(value));
*alert = warning.get().or(*alert);
}
fn invalid_entry(key: &str) -> &'static str {
if key == "quality" {
"Invalid numeric entry. A value between 1 and 12 is required. Previous value inserted."
} else {
"Invalid numeric entry. A value between 1 and 30000 is required. Previous value inserted."
}
}
fn closest_value(key: &str) -> &'static str {
if key == "quality" {
"A value between 1 and 12 is required. Closest value inserted."
} else {
"A value between 1 and 30000 is required. Closest value inserted."
}
}
@@ -0,0 +1,146 @@
use egui::{Event, Key, Modifiers, accesskit::Role};
use egui_kittest::{
Harness,
kittest::{NodeT, Queryable},
};
use serde_json::{Value, json};
use crate::{PhotocraftApp, Services, state::DialogKind};
const COMMAND: &str = "file.scripts.imageProcessor";
fn open(gpu: bool) -> Result<(Harness<'static, PhotocraftApp>, u64), String> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
app.run("file.new", json!({"width": 40, "height": 20}))?;
let builder = Harness::builder().with_size(egui::vec2(1000.0, 920.0));
let builder = if gpu { builder.wgpu() } else { builder };
let mut h = builder.build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app);
PhotocraftApp::setup_context(&h.ctx, Default::default());
let ctx = h.ctx.clone();
let id = crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({}))?["dialog"].as_u64().ok_or("Image Processor did not open a dialog")?;
h.run_steps(4);
Ok((h, id))
}
fn field(h: &Harness<'_, PhotocraftApp>, id: u64, key: &str) -> Value {
h.state().ui.dialogs.iter().find(|dialog| dialog.id == id).and_then(|dialog| dialog.fields.get(key)).cloned().unwrap_or(Value::Null)
}
fn edit_number(h: &mut Harness<'static, PhotocraftApp>, label: &str, input: &str) {
h.get_by_role_and_label(Role::SpinButton, label).click();
h.run_steps(2);
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
if input.is_empty() {
h.key_press(Key::Backspace);
} else {
h.event(Event::Text(input.into()));
}
h.run_steps(1);
h.key_press(Key::Tab);
h.run_steps(4);
}
fn alert(h: &Harness<'_, PhotocraftApp>, message: &str) {
let dialog = h.state().ui.dialogs.last();
assert_eq!(dialog.map(|dialog| dialog.kind), Some(DialogKind::Error));
assert_eq!(dialog.and_then(|dialog| dialog.fields.get("message")).and_then(Value::as_str), Some(message));
}
fn dismiss(h: &mut Harness<'_, PhotocraftApp>) {
h.key_press(Key::Enter);
h.run_steps(4);
}
#[test]
fn defaults_and_no_format_alert_preserve_the_dialog() {
let (mut h, id) = open(false).unwrap();
assert_eq!(field(&h, id, "jpeg"), json!({"enabled": true, "quality": 5.0, "convertToSrgb": false, "resize": false, "width": 1.0, "height": 1.0}));
assert_eq!(field(&h, id, "psd"), json!({"enabled": false, "maximizeCompatibility": true, "resize": false, "width": 1.0, "height": 1.0}));
assert_eq!(field(&h, id, "tiff"), json!({"enabled": false, "lzw": false, "resize": false, "width": 1.0, "height": 1.0}));
assert!(!h.get_by_label("Convert Profile to sRGB").accesskit_node().is_disabled());
assert!(h.get_by_label("Maximize Compatibility").accesskit_node().is_disabled());
assert!(h.get_by_label("LZW Compression").accesskit_node().is_disabled());
assert!(h.query_all_by_role_and_label(Role::SpinButton, "W").all(|node| node.accesskit_node().is_disabled()));
h.get_by_role_and_label(Role::CheckBox, "Save as JPEG").click();
h.run_steps(4);
let output = field(&h, id, "output");
h.get_by_role_and_label(Role::Button, "Run").click();
h.run_steps(4);
alert(&h, super::NO_FORMAT);
assert_eq!(field(&h, id, "output"), output);
dismiss(&mut h);
assert_eq!(h.state().ui.dialogs.len(), 1);
assert_eq!(field(&h, id, "jpeg")["enabled"], false);
}
#[test]
fn run_dispatches_all_enabled_formats_with_their_own_dimensions() {
let (mut h, id) = open(false).unwrap();
let directory = tempfile::tempdir().unwrap();
let fields = &mut h.state_mut().ui.dialog_mut(id).unwrap().fields;
fields.insert("output".into(), json!(directory.path()));
fields.insert("jpeg".into(), json!({"enabled": true, "resize": true, "width": 20, "height": 20}));
fields.insert("psd".into(), json!({"enabled": true, "resize": true, "width": 10, "height": 10}));
fields.insert("tiff".into(), json!({"enabled": true}));
h.run_steps(4);
h.get_by_role_and_label(Role::Button, "Run").click();
h.run_steps(4);
assert!(h.state().ui.dialogs.is_empty());
let mut sizes: Vec<_> = std::fs::read_dir(directory.path())
.unwrap()
.map(|entry| {
let path = entry.unwrap().path();
let ext = path.extension().unwrap().to_str().unwrap().to_owned();
let bytes = std::fs::read(&path).unwrap();
let doc = photocraft_io::import(path.to_str().unwrap(), &bytes).unwrap().document;
(ext, doc.size.width, doc.size.height)
})
.collect();
sizes.sort();
assert_eq!(sizes, [("jpg".into(), 20, 10), ("psd".into(), 10, 5), ("tif".into(), 40, 20)]);
}
#[test]
fn numeric_fields_clamp_and_restore_the_last_value() {
let (mut h, id) = open(false).unwrap();
edit_number(&mut h, "Quality", "7.6");
assert_eq!(field(&h, id, "jpeg")["quality"].as_f64(), Some(7.6));
for (input, value, message) in [
("abc", 7.6, super::invalid_entry("quality")),
("", 7.6, super::invalid_entry("quality")),
("NaN", 7.6, super::invalid_entry("quality")),
("20", 12.0, super::closest_value("quality")),
("0", 1.0, super::closest_value("quality")),
] {
edit_number(&mut h, "Quality", input);
alert(&h, message);
assert_eq!(field(&h, id, "jpeg")["quality"].as_f64(), Some(value));
dismiss(&mut h);
}
// Only JPEG's resize checkbox is enabled. Click its first row.
h.query_all_by_label("Resize to Fit").next().unwrap().click();
h.run_steps(4);
let width = h.query_all_by_role_and_label(Role::SpinButton, "W").next().unwrap();
width.click();
h.run_steps(2);
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
h.event(Event::Text("40000".into()));
h.key_press(Key::Enter);
h.run_steps(4);
alert(&h, super::closest_value("width"));
assert_eq!(field(&h, id, "jpeg")["width"].as_f64(), Some(30_000.0));
assert_eq!(field(&h, id, "psd")["width"].as_f64(), Some(1.0));
assert_eq!(field(&h, id, "tiff")["width"].as_f64(), Some(1.0));
}
#[test]
fn image_processor_gpu_snapshots() {
let Some(path) = std::env::var_os("PHOTOCRAFT_PROCESSOR_SNAPSHOTS") else { return };
let path = std::path::PathBuf::from(path);
let _gpu = photocraft_testkit::gpu_lock();
let (mut h, _) = open(true).unwrap();
h.render().unwrap().save(path.join("dialog.png")).unwrap();
edit_number(&mut h, "Quality", "20");
alert(&h, super::closest_value("quality"));
h.render().unwrap().save(path.join("range-alert.png")).unwrap();
}
+16 -6
View File
@@ -138,7 +138,9 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
// Data-driven labels (a per-part checkbox shows the part's name, not a catalogue entry)
// come from `__labels` verbatim; everything else goes through the catalogue.
let labels = f.get("__labels").cloned().unwrap_or(Value::Null);
let file_info = f.get("__command").and_then(Value::as_str) == Some("file.fileInfo");
let command = f.get("__command").and_then(Value::as_str);
let file_info = command == Some("file.fileInfo");
let image_processor = command == Some("file.scripts.imageProcessor");
let label = |k: &str| {
if file_info {
match k {
@@ -154,7 +156,7 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
let mut browse: Option<String> = None;
egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {
for k in keys {
if f.get("__command").and_then(Value::as_str) == Some("file.scripts.imageProcessor")
if image_processor
&& f.get("source").and_then(Value::as_str).is_some_and(|source| source != "folder")
&& matches!(k.as_str(), "input" | "includeSubfolders")
{
@@ -230,7 +232,13 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
});
} else {
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0)).accessible_name(label(&k));
let field = ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0)).accessible_name(label(&k));
if image_processor && crate::dialogs::is_folder_field(&k) {
crate::field_tab::register(ui.ctx(), field.id);
if crate::field_tab::reached(ui.ctx(), field.id) {
crate::field_tab::select_all(ui.ctx(), field.id, &s);
}
}
// A folder field gets the system folder picker (#7942, #9357).
if crate::dialogs::is_folder_field(&k) && crate::widgets::secondary_button(ui, tl!("Browse…"), 0.0).clicked() {
browse = Some(k.clone());
@@ -567,11 +575,13 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para
json!({
"source": if doc.is_some() { "current" } else { "folder" },
"input": dir, "includeSubfolders": false, "output": format!("{dir}/processed"),
"format": "jpg", "quality": 8, "width": 0, "height": 0, "convertToSrgb": true,
"jpeg": {"enabled": true, "quality": 5, "convertToSrgb": false, "resize": false, "width": 1, "height": 1},
"psd": {"enabled": false, "maximizeCompatibility": true, "resize": false, "width": 1, "height": 1},
"tiff": {"enabled": false, "lzw": false, "resize": false, "width": 1, "height": 1},
"__labels": {"current": tl!("Current document"), "open": tl!("All open documents"), "folder": tl!("Folder"), "includeSubfolders": tl!("Include All Subfolders")},
"__order": ["source", "input", "includeSubfolders", "output", "format", "quality", "width", "height", "convertToSrgb"]
"__order": ["source", "input", "includeSubfolders", "output"]
}),
json!({"source": ["current", "open", "folder"], "format": ["jpg", "png", "psd", "tiff", "webp"]}),
json!({"source": ["current", "open", "folder"]}),
),
"file.automate.batch" => {
let Some(action) = crate::actions::selected_action(app) else {
+31 -44
View File
@@ -99,13 +99,14 @@ fn batch_menu_offers_quality() {
}
#[test]
fn image_processor_menu_offers_webp() {
fn image_processor_menu_offers_independent_file_types() {
let _gpu = photocraft_testkit::gpu_lock();
let mut h = harness();
open(&mut h, "file.scripts.imageProcessor");
open_format_choices(&mut h);
for label in ["Save as JPEG", "Save as PSD", "Save as TIFF"] {
h.get_by_role_and_label(egui::accesskit::Role::CheckBox, label);
}
evidence(&mut h, "image-processor-formats");
assert!(h.query_by_label("WebP").or_else(|| h.query_by_label("Webp")).is_some(), "Image Processor must offer the supported WebP output format");
}
struct Scratch(PathBuf);
@@ -207,7 +208,7 @@ fn batch_custom_quality_is_bounded_dialog_local_and_reversible() {
/// Actual folder-mode controls must pass both WebP quality endpoints to the encoder while
/// preserving the active document, history, preferences and recorded actions.
#[test]
fn batch_and_processor_real_controls_write_the_chosen_webp_quality() {
fn batch_real_controls_write_the_chosen_webp_quality() {
let _gpu = photocraft_testkit::gpu_lock();
let dir = Scratch::new();
let input = dir.0.join("input");
@@ -220,47 +221,33 @@ fn batch_and_processor_real_controls_write_the_chosen_webp_quality() {
let history = h.state().session.active().unwrap().history.entries();
let prefs = serde_json::to_value(h.state().session.prefs()).unwrap();
let actions = serde_json::to_value(&h.state().session.actions.list).unwrap();
for (command, prefix) in [("file.automate.batch", "batch"), ("file.scripts.imageProcessor", "processor")] {
let mut outputs = Vec::new();
for quality in [0, 12] {
let output = dir.0.join(format!("{prefix}-{quality}"));
open(&mut h, command);
if prefix == "batch" {
assert!(h.state().ui.dialogs.last().unwrap().fields["quality"].is_null());
h.get_by_label("Custom").click();
h.run_steps(3);
} else {
let fields = &h.state().ui.dialogs.last().unwrap().fields;
assert_eq!(fields["quality"], json!(8));
assert_eq!(fields["width"], json!(0));
assert_eq!(fields["height"], json!(0));
assert_eq!(fields["convertToSrgb"], json!(true));
h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Source").click();
h.run_steps(3);
h.get_by_label("Folder").click();
h.run_steps(3);
}
choose_webp(&mut h);
edit_path(&mut h, "Input", &input);
edit_path(&mut h, "Output", &output);
edit_quality(&mut h, &quality.to_string());
evidence(&mut h, &format!("{prefix}-webp-quality-{quality}"));
h.get_by_label("OK").click();
h.run_steps(5);
assert!(h.state().ui.dialogs.is_empty());
let bytes = std::fs::read(output.join("owned-pattern.webp")).expect("the actual dialog confirmation writes the selected WebP");
let decoded = photocraft_codecs::decode_as(Format::WebP, &bytes).unwrap();
assert_eq!(decoded.dimensions(), (64, 48));
assert_eq!(decoded.layout(), ChannelLayout::Rgb);
let (_, params) = h.state().session.journal.last().unwrap();
assert_eq!(params["format"], json!("webp"));
assert_eq!(params["quality"].as_f64(), Some(f64::from(quality)));
assert!(params.as_object().unwrap().keys().all(|k| !k.starts_with("__")), "private shell values never become command params");
outputs.push(bytes);
}
assert_ne!(outputs[0], outputs[1], "{command}: actual chosen quality reaches the encoder");
assert!(outputs[0].len() < outputs[1].len());
let mut outputs = Vec::new();
for quality in [0, 12] {
let output = dir.0.join(format!("batch-{quality}"));
open(&mut h, "file.automate.batch");
assert!(h.state().ui.dialogs.last().unwrap().fields["quality"].is_null());
h.get_by_label("Custom").click();
h.run_steps(3);
choose_webp(&mut h);
edit_path(&mut h, "Input", &input);
edit_path(&mut h, "Output", &output);
edit_quality(&mut h, &quality.to_string());
evidence(&mut h, &format!("batch-webp-quality-{quality}"));
h.get_by_label("OK").click();
h.run_steps(5);
assert!(h.state().ui.dialogs.is_empty());
let bytes = std::fs::read(output.join("owned-pattern.webp")).expect("the actual dialog confirmation writes the selected WebP");
let decoded = photocraft_codecs::decode_as(Format::WebP, &bytes).unwrap();
assert_eq!(decoded.dimensions(), (64, 48));
assert_eq!(decoded.layout(), ChannelLayout::Rgb);
let (_, params) = h.state().session.journal.last().unwrap();
assert_eq!(params["format"], json!("webp"));
assert_eq!(params["quality"].as_f64(), Some(f64::from(quality)));
assert!(params.as_object().unwrap().keys().all(|k| !k.starts_with("__")), "private shell values never become command params");
outputs.push(bytes);
}
assert_ne!(outputs[0], outputs[1], "actual chosen quality reaches the encoder");
assert!(outputs[0].len() < outputs[1].len());
let active = h.state().session.active().unwrap();
assert!(Arc::ptr_eq(&active.doc, &doc));
assert_eq!((active.revision, active.history.entries()), (revision, history));