Files
photocraft/crates/ui-egui/tests/it/batch_export_options.rs
FredApps 9f5d55c86c fix(engine): document pattern.import group in the dispatch schema
Opening a .pat file always sends group (the file stem), as the other
preset import commands do, but the schema only listed path and data, so
dispatch rejected the import. Document the key; the handler still puts
patterns in the library and does not create a group.

Also stop the shared batch/Image Processor WebP test from passing
Batch's steps to Image Processor, which does not take that parameter.
2026-11-22 23:54:33 +07:00

271 lines
12 KiB
Rust

//! #2399: batch conversion exposes the formats and quality its engine already supports.
//! The menu controls are exercised separately from the existing engine's decoded outputs.
use egui_kittest::kittest::Queryable;
use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image};
use photocraft_ui_egui::control::{ControlRequest, Reply, handle};
use photocraft_ui_egui::{PhotocraftApp, menus};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::Arc;
type Harness = egui_kittest::Harness<'static, Box<PhotocraftApp>>;
/// The open form's values as `ui.inspect` lists the top dialog's fields.
fn form_fields(h: &mut Harness) -> Value {
let ctx = h.ctx.clone();
let (req, _rx) = ControlRequest::new("ui.inspect", json!({}));
let Reply::Done(inspect) = handle(h.state_mut(), &ctx, &req) else { panic!("ui.inspect: expected an immediate reply") };
inspect["result"]["dialogs"].as_array().and_then(|d| d.last()).expect("a form is open")["fields"].clone()
}
fn harness() -> Harness {
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 760.0)).with_max_steps(64).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), Default::default());
app.session.prefs.edit(|p| p.interface.language = "en".into());
app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();
app.run("actions.record", json!({"name": "Invert"})).unwrap();
app.run("image.adjustments.invert", json!({})).unwrap();
app.run("actions.stop", json!({})).unwrap();
app
});
h.run_steps(4);
h
}
fn open(h: &mut Harness, command: &str) {
let ctx = h.ctx.clone();
menus::invoke(h.state_mut(), &ctx, command, json!({})).expect("open the real menu dialog");
h.run_steps(5);
}
fn evidence(h: &mut Harness, name: &str) {
if let Some(dir) = std::env::var_os("PHOTOCRAFT_BATCH_EVIDENCE_DIR") {
std::fs::create_dir_all(&dir).unwrap();
h.render().expect("offscreen UI render").save(Path::new(&dir).join(format!("{name}.png"))).unwrap();
}
}
fn open_format_choices(h: &mut Harness) {
// The caption is a separate Label node with the same text; the accessible ComboBox name
// identifies the actual form field without guessing from coordinates.
h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "File Type").click();
h.run_steps(3);
}
fn choose_webp(h: &mut Harness) {
open_format_choices(h);
h.query_by_label("WebP").or_else(|| h.query_by_label("Webp")).expect("WebP output choice").click();
h.run_steps(3);
}
fn replace_text(h: &mut Harness, value: &str) {
h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });
h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::COMMAND });
h.event(egui::Event::Text(value.into()));
h.run_steps(3);
}
fn edit_path(h: &mut Harness, name: &str, value: &Path) {
h.get_by_role_and_label(egui::accesskit::Role::TextInput, name).click();
h.run_steps(2);
replace_text(h, &value.to_string_lossy());
// Moving focus on commits the field without Enter confirming the dialog.
h.key_press(egui::Key::Tab);
h.run_steps(2);
}
#[test]
fn batch_menu_offers_webp() {
let mut h = harness();
open(&mut h, "file.automate.batch");
open_format_choices(&mut h);
evidence(&mut h, "batch-formats");
assert!(h.query_by_label("WebP").or_else(|| h.query_by_label("Webp")).is_some(), "Batch must offer the supported WebP output format");
}
#[test]
fn batch_menu_offers_quality() {
let mut h = harness();
open(&mut h, "file.automate.batch");
evidence(&mut h, "batch-quality");
assert!(h.query_by_role_and_label(egui::accesskit::Role::SpinButton, "Quality").is_some(), "Batch must expose its supported output quality");
}
#[test]
fn image_processor_menu_offers_independent_file_types() {
let mut h = harness();
open(&mut h, "file.scripts.imageProcessor");
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");
}
struct Scratch(PathBuf);
impl Scratch {
fn new() -> Self {
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let path = std::env::temp_dir().join(format!("photocraft-batch-options-{}-{now}", std::process::id()));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn pattern() -> Image {
let mut data = Vec::new();
for y in 0..48u32 {
for x in 0..64u32 {
data.extend([(x * 13 + y * 3) as u8, (y * 17 + x * 5) as u8, ((x ^ y) * 11) as u8]);
}
}
Image::from_u8(64, 48, ChannelLayout::Rgb, data).unwrap()
}
#[test]
fn existing_engine_batch_and_image_processor_support_webp_quality() {
let dir = Scratch::new();
let input = dir.0.join("owned-pattern.png");
let source = pattern();
std::fs::write(&input, photocraft_codecs::encode(&source, Format::Png, &EncodeOptions::default()).unwrap()).unwrap();
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
let doc = app.session.active().unwrap().doc.clone();
let revision = app.session.active().unwrap().revision;
let history = app.session.active().unwrap().history.entries();
let prefs = serde_json::to_value(app.session.prefs()).unwrap();
for (command, prefix) in [("file.automate.batch", "batch"), ("file.scripts.imageProcessor", "processor")] {
let expected: Vec<u8> = source.data().iter().map(|v| if prefix == "batch" { 255 - v } else { *v }).collect();
let mut outputs = Vec::new();
for quality in [Value::Null, json!(0), json!(12)] {
let out = dir.0.join(format!("{prefix}-{quality}"));
std::fs::create_dir(&out).unwrap();
let mut params = json!({"input": [input], "output": out, "format": "webp", "quality": quality});
if command == "file.automate.batch" {
params["steps"] = json!([["image.adjustments.invert", {}]]);
}
let result = app.run(command, params).unwrap();
assert_eq!(result["errors"], json!([]), "{command}: {result}");
let path = result["files"][0].as_str().unwrap();
assert!(path.ends_with(".webp"));
let bytes = std::fs::read(path).unwrap();
let decoded = photocraft_codecs::decode_as(Format::WebP, &bytes).unwrap();
assert_eq!(decoded.dimensions(), (64, 48));
assert_eq!(decoded.layout(), ChannelLayout::Rgb);
if quality.is_null() && prefix == "batch" {
assert_eq!(decoded.data(), expected, "default Batch WebP is lossless, and the action was applied");
}
outputs.push(bytes);
}
assert_ne!(outputs[1], outputs[2], "{command}: low and high quality must affect the encoder");
assert!(outputs[1].len() < outputs[2].len(), "{command}: this synthetic pattern grows at higher quality");
}
let active = app.session.active().unwrap();
assert!(Arc::ptr_eq(&active.doc, &doc), "batch commands leave the active document untouched");
assert_eq!(active.revision, revision);
assert_eq!(active.history.entries(), history);
assert_eq!(serde_json::to_value(app.session.prefs()).unwrap(), prefs);
}
#[test]
fn batch_naming_controls_export_the_requested_names_and_reset_on_cancel() {
let dir = Scratch::new();
let input = dir.0.join("input");
let output = dir.0.join("output");
std::fs::create_dir(&input).unwrap();
let source = pattern();
let bytes = photocraft_codecs::encode(&source, Format::Png, &EncodeOptions::default()).unwrap();
for name in ["first.png", "second.png"] {
std::fs::write(input.join(name), &bytes).unwrap();
}
let mut h = harness();
open(&mut h, "file.automate.batch");
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "File Naming").click();
h.run_steps(2);
replace_text(&mut h, "cancelled_{serial}");
h.get_by_label("Cancel").click();
h.run_steps(3);
assert!(!output.exists());
open(&mut h, "file.automate.batch");
let fields = form_fields(&mut h);
assert_eq!(fields["naming"], "");
assert_eq!(fields["startingSerial"], 1);
edit_path(&mut h, "Input Folder", &input);
edit_path(&mut h, "Output Folder", &output);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "File Naming").click();
h.run_steps(2);
replace_text(&mut h, "{serial}_{name}.{ext}");
h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Starting Serial Number").click();
h.run_steps(2);
h.event(egui::Event::Text("7".into()));
h.run_steps(3);
h.key_press(egui::Key::Tab);
h.run_steps(3);
assert_eq!(form_fields(&mut h)["startingSerial"], 7, "typing changes the starting serial");
evidence(&mut h, "batch-naming");
h.get_by_label("OK").click();
h.run_steps(5);
assert!(!h.state().dialog_open());
let expected: Vec<_> = source.data().iter().map(|v| 255 - v).collect();
for name in ["007_first.png", "008_second.png"] {
let bytes = std::fs::read(output.join(name)).expect("dialog naming reaches the exporter");
let decoded = photocraft_codecs::decode_as(Format::Png, &bytes).unwrap();
assert_eq!(decoded.data(), expected, "the recorded Invert action still runs");
}
assert!(!output.join("first.png").exists());
assert!(!output.join("second.png").exists());
}
#[test]
fn batch_default_quality_keeps_lossless_webp_and_existing_jpeg_bytes() {
let dir = Scratch::new();
let input = dir.0.join("input");
std::fs::create_dir(&input).unwrap();
let original = pattern();
std::fs::write(input.join("owned-pattern.png"), photocraft_codecs::encode(&original, Format::Png, &EncodeOptions::default()).unwrap()).unwrap();
let mut h = harness();
for format in ["webp", "jpg"] {
let output = dir.0.join(format!("ui-default-{format}"));
let reference = dir.0.join(format!("engine-existing-default-{format}"));
open(&mut h, "file.automate.batch");
if format == "webp" {
choose_webp(&mut h);
} else {
open_format_choices(&mut h);
h.get_by_label("JPEG").click();
h.run_steps(3);
}
edit_path(&mut h, "Input Folder", &input);
edit_path(&mut h, "Output Folder", &output);
assert!(form_fields(&mut h)["quality"].is_null());
evidence(&mut h, &format!("batch-default-{format}"));
h.get_by_label("OK").click();
h.run_steps(5);
let result = std::fs::read(output.join(format!("owned-pattern.{format}"))).unwrap();
let mut session = photocraft_engine::Session::new();
let r = session
.execute("file.automate.batch", json!({"input": input, "output": reference, "steps": [["image.adjustments.invert", {}]], "format": format}))
.unwrap();
assert_eq!(r["errors"], json!([]));
assert_eq!(
result,
std::fs::read(reference.join(format!("owned-pattern.{format}"))).unwrap(),
"{format}: UI default equals the command's existing unset quality"
);
if format == "webp" {
let decoded = photocraft_codecs::decode_as(Format::WebP, &result).unwrap();
let expected: Vec<u8> = original.data().iter().map(|v| 255 - v).collect();
assert_eq!(decoded.data(), expected, "default WebP remains lossless after the recorded action");
}
}
}