PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Merge upstream/main into revive/4330-jpeg-options
Higgs3258492d1ff42f9c6
diff --cc apps/photocraft-cli/src/lib.rsindex e79e63a70,0e3429d07..4d3e67858--- a/apps/photocraft-cli/src/lib.rs+++ b/apps/photocraft-cli/src/lib.rs@@@ -15,22 -15,21 +15,24 @@@ pub const USAGE: &str = "photocraft-cli: headless PhotoCraftUSAGE:- photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--jpeg-format <baseline|optimized|progressive>]- photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression <none|bc1|bc2|bc3>] [--dds-mipmaps]++ photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression <none|bc1|bc2|bc3>] [--dds-mipmaps] [--jpeg-format <baseline|optimized|progressive>]Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …).TIFF output is flat unless --tiff-layers keeps the layers (Photoshop layer data).--quality sets the JPEG or WebP quality; a WebP written with a quality is lossy, without one lossless.--tga-bits sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) asits alpha, 24 none. Without it: 32 with an alpha channel or transparency, else 24.--dpx-bits sets a DPX's bits per sample. Without it: 8 for an 8-bit document, else 16.+ --dds-compression sets a DDS texture's compression: none (uncompressed, the default), bc1+ (DXT1: alpha on or off), bc2 (DXT3) or bc3 (DXT5). --dds-mipmaps also writes the full mip chain.+ --jpeg-format picks a JPEG's scans, as JPEG Options does: baseline (the default), optimized+ (Huffman tables fitted to the image; RGB is written 4:2:0 and keeps the standard tables, so+ only Gray and CMYK shrink) or progressive.photocraft-cli info <file> [--compact]Print the document as JSON (size, mode, depth, layer tree).- photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--jpeg-format <baseline|optimized|progressive>]- photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression <none|bc1|bc2|bc3>] [--dds-mipmaps]++ photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression <none|bc1|bc2|bc3>] [--dds-mipmaps] [--jpeg-format <baseline|optimized|progressive>]Open a file, run engine commands in order, save the result. Each --paramsapplies to the preceding --cmd. Prints each command's JSON result.- photocraft-cli batch --actions <actions.json|set.atn> [--action <name>] --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--jpeg-format <baseline|optimized|progressive>]- photocraft-cli batch --actions <actions.json|set.atn> [--action <name>] --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression <none|bc1|bc2|bc3>] [--dds-mipmaps]++ photocraft-cli batch --actions <actions.json|set.atn> [--action <name>] --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression <none|bc1|bc2|bc3>] [--dds-mipmaps] [--jpeg-format <baseline|optimized|progressive>]Apply an action list to every image in a directory. A Photoshop Actions file (.atn) is aset: its action --action names plays, as below. JSON steps are [id, params] pairs,{\"command\": id, \"params\": {…}} objects or bare ids, as a recorded action or droplet stores them@@@ -72,18 -71,23 +74,23 @@@ struct Subcommand}const SUBCOMMANDS: &[Subcommand] = &[- Subcommand { name: "convert", values: &["--format", "--quality", "--tga-bits", "--dpx-bits", "--jpeg-format"], bare: &["--tiff-layers"], run: convert },+ Subcommand {+ name: "convert",- values: &["--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"],++ values: &["--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression", "--jpeg-format"],+ bare: &["--tiff-layers", "--dds-mipmaps"],+ run: convert,+ },Subcommand { name: "info", values: &[], bare: &["--compact"], run: |a, out, _| info(a, out) },Subcommand {name: "run",- values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--jpeg-format"],- bare: &["--tiff-layers"],- values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"],++ values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression", "--jpeg-format"],+ bare: &["--tiff-layers", "--dds-mipmaps"],run: run_cmds,},Subcommand {name: "batch",- values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--jpeg-format"],- bare: &["--in-place", "--tiff-layers"],- values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"],++ values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression", "--jpeg-format"],+ bare: &["--in-place", "--tiff-layers", "--dds-mipmaps"],run: batch,},Subcommand { name: "droplet", values: &["--out"], bare: &[], run: droplet },@@@ -222,10 -226,11 +229,15 @@@ fn export_opts(a: &Args) -> Result<Expoo.encode.dpx_bits =Some(b.parse().ok().and_then(photocraft_io::DpxBits::from_bits).ok_or_else(|| format!("bad --dpx-bits `{b}`: expected 8, 10, 12 or 16"))?);}+ if let Some(f) = a.get("--jpeg-format") {+ o.encode.jpeg_format =+ photocraft_codecs::JpegFormat::parse(f).ok_or_else(|| format!("bad --jpeg-format `{f}`: expected baseline, optimized or progressive"))?;+ }+ if let Some(c) = a.get("--dds-compression") {+ o.encode.dds.compression =+ photocraft_io::DdsCompression::from_name(c).ok_or_else(|| format!("bad --dds-compression `{c}`: expected none, bc1, bc2 or bc3"))?;+ }+ o.encode.dds.mipmaps = a.has("--dds-mipmaps");Ok(o)}diff --cc book/src/formats/raster-formats.mdindex 4411a0b45,c333cbc73..8733da8b2--- a/book/src/formats/raster-formats.md+++ b/book/src/formats/raster-formats.md@@@ -19,7 -19,7 +19,8 @@@ Every route that writes a document to- Formats without transparency (JPEG, Radiance HDR) get the image composited over white, as Export As and Quick Export do; in CMYK, white is no ink.- Formats that can't embed an ICC profile (GIF, BMP, TGA, QOI, ICO, Netpbm/PFM) get RGB documents in another profile (linear light, Display P3, …) converted to sRGB through the colour engine (perceptual intent), since an untagged file is read as sRGB. OpenEXR and Radiance HDR get linear sRGB instead (linear gray for a grayscale OpenEXR), which is how they are tagged when opened.- TGA, as Photoshop's Targa: an RGB Targa is 24 or 32 bits per pixel. Save As and Save a Copy ask (Targa Options, starting at 32 with an alpha channel, else 24); Export As has a Resolution choice (Auto, 24 or 32 bits/pixel); scripts pass `tgaBits` (`--tga-bits` on the CLI). At 32 bits the document's alpha channel is the file's alpha when it has exactly one (spot channels don't count; with several, none is used), and the colours are written exactly, never premultiplied or cleared where the alpha is 0, so a game texture's mask and its colours both survive. Without a usable alpha channel the layers' transparency is the alpha (opaque without any). 24 bits write no alpha, compositing transparency over white. Without a choice: 32 with an alpha channel or transparency, else 24. A 32-bit Targa opens as an opaque Background with its alpha as "Alpha 1", so it round-trips. Grayscale Targas are 8-bit.+- JPEG, as Photoshop's JPEG Options: Save As and Save a Copy ask for the Quality on Photoshop's 0–12 scale (with its Low, Medium, High and Maximum presets) and a Format Option: Baseline ("Standard"), Baseline Optimized (Huffman tables fitted to the image) or Progressive. The quality starts at the opened JPEG's own quality, else at the Export preference's JPEG quality; left there, an opened JPEG is written at exactly its own quality. Scripts pass `"quality": 0..12` and `"jpegFormat": "baseline" | "optimized" | "progressive"` (on the CLI, `--quality` on the encoder's 1–100 scale and `--jpeg-format`) and aren't asked; recorded actions replay the answer. The scale maps onto the encoder's 1–100 as `round(q / 12 × 99 + 1)`. RGB JPEGs are written 4:2:0, where Baseline Optimized keeps the standard tables for now (Gray and CMYK, written 4:4:4, get fitted ones). Matte and the file-size preview aren't offered.+ - DDS, for game and 3D textures: Save As and Save a Copy ask (DDS Options) for the compression (None, uncompressed and lossless; BC1/DXT1, whose alpha is on or off; BC2/DXT3; BC3/DXT5) and whether to generate mipmaps (the full chain down to 1×1, each level a box filter of the one above). Scripts pass `ddsCompression` (`none`, `bc1`, `bc2`, `bc3`) and `ddsMipmaps` (`--dds-compression`, `--dds-mipmaps` on the CLI). Opening one reads its top mip level.Flat TIFF and JPEG exports of composited CMYK documents convert the RGB composite back throughthe document's CMYK ICC profile (relative colorimetric with black point compensation) and embeddiff --cc crates/codecs/src/lib.rsindex a6f25007b,a5675c982..6a52c5585--- a/crates/codecs/src/lib.rs+++ b/crates/codecs/src/lib.rs@@@ -38,7 -38,9 +38,9 @@@ pub use crate::format::{ASYMMETRIC_EXCEpub use crate::image::{ChannelLayout, CryptomatteBuffer, CryptomatteLayer, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, Image, Metadata, SampleType,};- pub use crate::options::{DecodeOptions, DpxBits, EncodeOptions, ExrCompression, JpegFormat, Limits, PngCompression, PngStereo, TiffCompression};+ pub use crate::options::{- DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, Limits, PngCompression, PngStereo, TiffCompression,++ DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, JpegFormat, Limits, PngCompression, PngStereo, TiffCompression,+ };pub use crate::orientation::{exif_orientation, upright_exif, upright_xmp};pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution};pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding};diff --cc crates/engine/src/file_cmds.rsindex 396d22157,f9cee9e21..671dbf95c--- a/crates/engine/src/file_cmds.rs+++ b/crates/engine/src/file_cmds.rs@@@ -288,8 -288,8 +288,8 @@@ pub(crate) fn import(name: &str, bytesOk(r.document)}- /// What a headless save writes beyond the format: JPEG quality and format, TIFF layers, Targa bits,- /// PSD previews and the PSD merged image.-/// What a headless save writes beyond the format: JPEG quality, TIFF layers, Targa bits, DPX-/// bits, DDS compression and mipmaps, PSD previews and the PSD merged image.++/// What a headless save writes beyond the format: JPEG quality and format, TIFF layers, Targa++/// bits, DPX bits, DDS compression and mipmaps, PSD previews and the PSD merged image.#[derive(Debug, Clone, Copy)]pub(crate) struct SaveOpts {/// Photoshop's 0–12 JPEG scale.@@@ -418,8 -423,9 +447,9 @@@ pub(crate) fn encode(doc: &Document, pa// lossy or lossless as it was), as Photoshop's Save does.photocraft_io::apply_file_encoding(doc, &mut opts.encode);opts.encode.dpx_bits = save.dpx_bits;+ opts.encode.dds = save.dds;if let Some(q) = save.quality {- let q = (q.clamp(0.0, 12.0) / 12.0 * 99.0 + 1.0).round() as u8;+ let q = jpeg_quality(q);opts.encode.jpeg_quality = q;// A quality on a WebP save asks for the lossy encoder; the default WebP stays lossless.opts.encode.webp_quality = q;@@@ -1685,7 -1688,7 +1715,7 @@@ pub fn specs() -> Vec<CommandSpec>"Save a Copy…",&["File"],Some("Cmd+Alt+S"),- r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)}"##,- r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"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)}"##,++ r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"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)}"##,native_doc,save_a_copy),@@@ -1748,7 -1751,7 +1778,7 @@@"Batch…",&["File", "Automate"],None,- 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?,"jpegFormat":"baseline|optimized|progressive"?,"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,"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,"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),"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?,"jpegFormat":"baseline|optimized|progressive"?,"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,"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),"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),@@@ -1757,7 -1760,7 +1787,7 @@@"Image Processor…",&["File", "Scripts"],None,- 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,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"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,"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),"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,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":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),"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),@@@ -1785,7 -1788,7 +1815,7 @@@"Layers to Files…",&["File", "Export"],None,- r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)} → {files}"##,- r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"tiffLayers":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)} → {files}"##,++ r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":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)} → {files}"##,native_doc,layers_to_files),diff --cc crates/ui-egui/src/control.rsindex fe6692bde,321c73ec6..fba1bbff8--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@@ -2441,54 -2441,37 +2441,85 @@@ mod testsassert_eq!(written.borrow().len(), 3, "a bad tgaBits writes nothing");}+ /// `app.save` takes JPEG Options (`quality` 0–12, `jpegFormat`) and never stops at the prompt;+ /// a value it can't read is an error that writes nothing.+ #[test]+ fn automation_save_passes_jpeg_options_without_asking() {+ use photocraft_codecs::JpegFormat;+ use std::cell::RefCell;+ use std::rc::Rc;+ // The JPEG quality (1–100) and format each export was asked for.+ type Asked = Rc<RefCell<Vec<(Option<u8>, JpegFormat)>>>;+ let asked: Asked = Rc::default();+ let written: Rc<RefCell<Vec<String>>> = Rc::default();+ let (a, w) = (asked.clone(), written.clone());+ let services = crate::Services {+ export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| {+ a.borrow_mut().push((s.jpeg_quality, s.jpeg_format));+ Ok((b"out".to_vec(), Vec::new()))+ })),+ automation_write: Some(Box::new(move |path: &str, _b: &[u8]| {+ w.borrow_mut().push(path.to_string());+ Ok(())+ })),+ ..Default::default()+ };+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);+ let ctx = egui::Context::default();+ app.run("file.new", json!({"width": 8, "height": 8})).unwrap();+ for params in [+ json!({"path": "a.jpg"}),+ json!({"path": "b.jpg", "quality": 12, "jpegFormat": "progressive"}),+ json!({"path": "c.jpg", "jpegFormat": "optimized"}),+ ] {+ let r = call(&mut app, &ctx, "app.save", params.clone());+ assert_eq!(r["result"]["path"], params["path"], "{r}");+ assert!(app.jpeg_options.is_none(), "automation saves never prompt");+ }+ assert_eq!(*asked.borrow(), [(None, JpegFormat::Baseline), (Some(100), JpegFormat::Progressive), (None, JpegFormat::Optimized)]);+ for bad in [+ json!({"path": "d.jpg", "quality": 13}),+ json!({"path": "d.jpg", "quality": "high"}),+ json!({"path": "d.jpg", "jpegFormat": "fast"}),+ json!({"path": "d.jpg", "jpegFormat": 2}),+ ] {+ let r = call(&mut app, &ctx, "app.save", bad.clone());+ assert!(r["error"].is_string(), "{bad}: {r}");+ }+ assert_eq!(written.borrow().len(), 3, "a bad JPEG option writes nothing");+ }++ /// `app.save` takes the DDS options (`ddsCompression`, `ddsMipmaps`) and never stops at DDS+ /// Options.+ #[test]+ fn automation_save_passes_dds_options_without_asking() {+ use photocraft_io::{DdsCompression, DdsOptions};+ use std::cell::RefCell;+ use std::rc::Rc;+ let asked: Rc<RefCell<Vec<DdsOptions>>> = Rc::default();+ let a = asked.clone();+ let services = crate::Services {+ export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| {+ a.borrow_mut().push(s.dds);+ Ok((b"out".to_vec(), Vec::new()))+ })),+ automation_write: Some(Box::new(|_: &str, _: &[u8]| Ok(()))),+ ..Default::default()+ };+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);+ let ctx = egui::Context::default();+ app.run("file.new", json!({"width": 8, "height": 8})).unwrap();+ for params in [json!({"path": "a.dds"}), json!({"path": "b.dds", "ddsCompression": "bc1", "ddsMipmaps": true})] {+ let r = call(&mut app, &ctx, "app.save", params.clone());+ assert_eq!(r["result"]["path"], params["path"], "{r}");+ assert!(app.dds_options.is_none(), "automation saves never prompt");+ }+ assert_eq!(*asked.borrow(), [DdsOptions::default(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }]);+ let r = call(&mut app, &ctx, "app.save", json!({"path": "c.dds", "ddsCompression": "bc9"}));+ assert!(r["error"].as_str().unwrap().contains("ddsCompression"), "{r}");+ assert_eq!(asked.borrow().len(), 2, "a bad ddsCompression writes nothing");+ }+#[test]fn automation_open_and_save_use_the_roots_and_reply_with_warnings() {use photocraft_color::{ColorMode, SampleType};diff --cc crates/ui-egui/src/dds_options_ui.rsindex 000000000,c795643a7..3216b51a3mode 000000,100644..100644--- a/crates/ui-egui/src/dds_options_ui.rs+++ b/crates/ui-egui/src/dds_options_ui.rs@@@ -1,0 -1,148 +1,148 @@@+ //! DDS Options: the compression and mip chain File › Save As and Save a Copy ask for before+ //! writing a DirectDraw Surface texture (#1327). Photoshop has no DDS writer of its own (a plug-in+ //! adds one), so this follows the texture tools' usual choices: uncompressed, or BC1/BC2/BC3+ //! (DXT1/DXT3/DXT5), and whether to generate mipmaps (see `photocraft_io::DdsOptions`).+ //!+ //! The save is parked in [`Prompt`] while the modal is up (egui is immediate-mode) and written+ //! once answered. Cancel drops the save. Scripts skip the prompt by passing `ddsCompression` or+ //! `ddsMipmaps`.++ use photocraft_io::{DdsCompression, DdsOptions};++ use crate::{ExportSettings, PhotocraftApp};++ /// A save waiting on the DDS Options answer.+ pub struct Prompt {+ /// The document that requested the save, even if tabs change while this is open.+ doc: photocraft_doc::DocId,+ /// Where the texture goes.+ pub path: String,+ /// The options chosen, starting uncompressed without mipmaps.+ pub options: DdsOptions,+ /// Save a Copy: the document keeps its path and unsaved changes.+ pub copy: bool,+ /// The step the answered save is recorded as (`file.saveAs` or `file.saveACopy`), so an+ /// action being recorded keeps it; `file.save` when File › Save confirmed the document's own+ /// texture (#3531), which plays back on the file the action is played on.+ pub record: &'static str,+ }++ /// `true` when `path` names a DDS texture.+ pub fn wants_prompt(path: &str) -> bool {+ photocraft_engine::file_cmds::extension(path).and_then(|e| photocraft_codecs::from_extension(&e)) == Some(photocraft_codecs::Format::Dds)+ }++ /// The DDS options a command or control call asks for (`"ddsCompression"`, `"ddsMipmaps"`),+ /// which skip the prompt.+ pub fn options_param(params: &serde_json::Value, cmd: &str) -> Result<Option<DdsOptions>, String> {+ photocraft_engine::file_cmds::dds_param(params, cmd).map_err(|e| e.to_string())+ }++ /// The params a save with `options` is recorded with.+ pub fn record(options: DdsOptions, step: &mut serde_json::Value) {+ step["ddsCompression"] = options.compression.name().into();+ step["ddsMipmaps"] = options.mipmaps.into();+ }++ /// Parks the save behind the prompt. A prompt already waiting is never replaced.+ pub fn park(app: &mut PhotocraftApp, path: String, copy: bool, record: &'static str) -> Result<(), String> {+ if app.save_options_open() {- return Err("Answer the TIFF, Targa or DDS Options before starting another save".into());++ return Err(crate::SAVE_OPTIONS_OPEN.into());+ }+ let doc = app.active_doc_id()?;+ app.dds_options = Some(Prompt { doc, path, options: DdsOptions::default(), copy, record });+ Ok(())+ }++ /// The block compressions go by their format names, which stay untranslated like other+ /// technology names.+ fn label(c: DdsCompression) -> &'static str {+ match c {+ DdsCompression::None => tl!("None"),+ DdsCompression::Bc1 => "BC1 / DXT1",+ DdsCompression::Bc2 => "BC2 / DXT3",+ DdsCompression::Bc3 => "BC3 / DXT5",+ }+ }++ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {+ let Some(p) = &mut app.dds_options else { return };+ let (mut ok, mut cancel) = (false, false);+ let mut options = p.options;+ let modal = egui::Modal::new(egui::Id::new("dds-options")).show(ctx, |ui| {+ ui.set_max_width(340.0);+ ui.label(egui::RichText::new(tl!("DDS Options")).font(crate::theme::semibold(15.0)));+ ui.add_space(4.0);+ crate::widgets::hairline(ui);+ ui.add_space(8.0);+ crate::widgets::section_label(ui, tl!("Compression"));+ for c in DdsCompression::ALL {+ ui.radio_value(&mut options.compression, c, label(c));+ }+ ui.add_space(8.0);+ crate::widgets::checkbox(ui, &mut options.mipmaps, tl!("Generate Mipmaps"));+ ui.add_space(12.0);+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ ui.spacing_mut().item_spacing.x = 10.0;+ ok = crate::widgets::primary_button(ui, tl!("OK"), 84.0).clicked();+ cancel = crate::widgets::secondary_button(ui, tl!("Cancel"), 84.0).clicked();+ });+ });+ cancel |= modal.should_close();+ p.options = options;+ // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels.+ if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) {+ let Some(p) = app.dds_options.take() else { return };+ let settings = ExportSettings { dds: p.options, ..app.save_settings() };+ let mut step = if p.record == "file.save" { serde_json::json!({}) } else { serde_json::json!({"path": p.path}) };+ record(p.options, &mut step);+ let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.copy));+ if written.is_ok() {+ // An action being recorded keeps the Save As or Save a Copy with this answer.+ app.session.journal.push((p.record.into(), step));+ }+ match written {+ Err(e) => {+ app.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]);+ app.ui.status_error = true;+ }+ Ok(Some(_)) if !p.copy => crate::discard_ui::saved_document(app, ctx, p.doc),+ // A background save releases the close prompt when it finishes (`jobs_ui`).+ Ok(_) => {}+ }+ } else if cancel {+ app.dds_options = None;+ app.ui.status = tl!("Save cancelled").into();+ app.ui.status_error = false;+ }+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ #[test]+ fn dds_names() {+ assert!(wants_prompt("a.dds"));+ assert!(wants_prompt("dir/sub/a.DDS"));+ assert!(wants_prompt("C:\\x\\y.dds"));+ assert!(!wants_prompt("a.dds.psd"));+ assert!(!wants_prompt(".dds"));+ assert!(!wants_prompt("a.png"));+ }++ #[test]+ fn options_params() {+ use serde_json::json;+ assert_eq!(options_param(&json!({}), "file.saveAs"), Ok(None));+ assert_eq!(options_param(&json!({"ddsCompression": "bc3"}), "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::Bc3, mipmaps: false })));+ assert_eq!(options_param(&json!({"ddsMipmaps": true}), "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::None, mipmaps: true })));+ for bad in [json!({"ddsCompression": "bc7"}), json!({"ddsCompression": 3}), json!({"ddsMipmaps": "yes"})] {+ assert!(options_param(&bad, "file.saveAs").is_err(), "{bad}");+ }+ let mut step = json!({"path": "a.dds"});+ record(DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }, &mut step);+ assert_eq!(step, json!({"path": "a.dds", "ddsCompression": "bc1", "ddsMipmaps": true}));+ assert_eq!(options_param(&step, "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::Bc1, mipmaps: true })));+ }+ }diff --cc crates/ui-egui/src/discard_ui.rsindex 455ccbef5,e9b5504be..c14a62df3--- a/crates/ui-egui/src/discard_ui.rs+++ b/crates/ui-egui/src/discard_ui.rs@@@ -959,8 -959,8 +959,10 @@@ mod tests#[path = "targa_tests.rs"]mod targa_tests;+ #[path = "jpeg_tests.rs"]+ mod jpeg_tests;+ #[path = "dds_tests.rs"]+ mod dds_tests;/// One frame with the window's close button pressed; the commands the guard sent.fn window_close_commands(app: &mut PhotocraftApp) -> Vec<egui::ViewportCommand> {diff --cc crates/ui-egui/src/disk_change_prompt.rsindex 9025d2226,b65985cd4..34d83075e--- a/crates/ui-egui/src/disk_change_prompt.rs+++ b/crates/ui-egui/src/disk_change_prompt.rs@@@ -20,7 -20,7 +20,7 @@@ pub fn owns(fields: &Map<String, Value>/// Opens the prompt instead of saving `doc` to its own file at `path` when another app changed/// that file; `None` saves as usual. `flat` is a flat file confirmed in the Save dialog, which/// is saved (and recorded) the way [`PhotocraftApp::save_dialog_flow`] does it.- pub(crate) fn intercept(app: &mut PhotocraftApp, doc: DocId, path: &str, flat: bool, choices: crate::SaveChoices) -> Option<Result<Value, String>> {-pub(crate) fn intercept(app: &mut PhotocraftApp, doc: DocId, path: &str, flat: bool) -> Option<Result<Value, String>> {++pub(crate) fn intercept(app: &mut PhotocraftApp, doc: DocId, path: &str, flat: bool, choices: crate::FormatChoices) -> Option<Result<Value, String>> {if !app.changed_on_disk(doc, path) {return None;}@@@ -29,9 -29,7 +29,9 @@@}let name = crate::file_open::display_name(path);let message = crate::i18n::fmt(tl!("{name} was changed by another app after it was opened or saved here."), &[("name", name.as_str())]);- let fields = json!({MARK: true, "__label": "Save", "message": message, "document": doc.0, "path": path, "flat": flat});+ let mut fields = json!({MARK: true, "__label": "Save", "message": message, "document": doc.0, "path": path, "flat": flat});- // A script's TIFF, Targa or JPEG answer is kept for the save Replace writes.++ // A script's Targa, DDS or JPEG answer is kept for the save Replace writes.+ choices.record(&mut fields);let id = app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap_or_default());Some(Ok(json!({"dialog": id, "confirmationPending": true})))}@@@ -47,10 -45,9 +47,10 @@@ pub fn confirm(app: &mut PhotocraftApplet doc = fields.get("document").and_then(Value::as_u64).map(DocId).ok_or(tl!("The document is closed"))?;let path = fields.get("path").and_then(Value::as_str).unwrap_or_default().to_string();let flat = fields.get("flat").and_then(Value::as_bool) == Some(true);- let choices = crate::SaveChoices::from_step(&Value::Object(fields.clone()), "file.save")?;++ let choices = crate::FormatChoices::from_step(&Value::Object(fields.clone()), "file.save")?;app.with_document(doc, |app| {if flat {- let r = app.save_to(path.clone(), crate::FormatChoices::default())?;+ let r = app.save_to(path.clone(), choices)?;app.journal_as_plain_save(&path);Ok(r)} else {diff --cc crates/ui-egui/src/jpeg_options_ui.rsindex a6bd37fb4,000000000..97b4f4564mode 100644,000000..100644--- a/crates/ui-egui/src/jpeg_options_ui.rs+++ b/crates/ui-egui/src/jpeg_options_ui.rs@@@ -1,349 -1,0 +1,350 @@@+//! JPEG Options: the quality and format File › Save As and Save a Copy ask for before writing a+//! JPEG, as Photoshop's JPEG Options does. Quality is Photoshop's 0–12 scale (Low 0–4, Medium 5–7,+//! High 8–9, Maximum 10–12), mapped to the encoder's 1–100 by+//! `photocraft_engine::file_cmds::jpeg_quality`; Format Options are Baseline ("Standard"),+//! Baseline Optimized and Progressive. Matte and the size preview aren't offered yet. Re-saving an+//! opened JPEG starts at the file's own quality, as File › Save keeps it (#4032).+//!+//! The save is parked in [`Prompt`] while the modal is up (egui is immediate-mode) and written+//! once answered. Cancel drops the save. Scripts skip the prompt by passing `quality` or+//! `jpegFormat`.+//!+//! Any save can ask: check [`wants_prompt`], then [`park`] (which starts where+//! [`Start::for_active`] says) or [`park_at`] with a [`Start`] of its own, and return. The answer+//! is written by [`confirm`] and journalled as the `record` command passed to `park`: with its+//! path, `quality` (0–12, left out when the file's own quality was kept) and `jpegFormat`, or+//! without the path for a plain `file.save`, which writes whichever file an action is played on+//! ([`plain_save_step`]).++use photocraft_codecs::JpegFormat;+use serde_json::Value;++use crate::{ExportSettings, PhotocraftApp};++/// The highest quality on Photoshop's JPEG scale.+pub const MAX_QUALITY: u8 = 12;++/// A JPEG Options answer, from the prompt or from a command's `quality` and `jpegFormat`.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct JpegChoice {+ /// Photoshop's 0–12 scale; `None` keeps the quality the save would use anyway (the opened+ /// file's own, else the encoder's default).+ pub quality: Option<u8>,+ pub format: JpegFormat,+}++impl JpegChoice {+ /// `settings` writing this choice.+ pub fn apply(self, settings: ExportSettings) -> ExportSettings {+ ExportSettings {+ jpeg_quality: self.quality.map(|q| photocraft_engine::file_cmds::jpeg_quality(f64::from(q))).or(settings.jpeg_quality),+ jpeg_format: self.format,+ ..settings+ }+ }++ /// Adds `quality` and `jpegFormat` to a recorded save step, so replaying it doesn't ask again.+ pub fn record(self, step: &mut Value) {+ if let Some(q) = self.quality {+ step["quality"] = q.into();+ }+ step["jpegFormat"] = self.format.name().into();+ }+}++/// The JPEG Options a command or control call gives (`"quality": 0..12`, `"jpegFormat"`), which+/// skip the prompt. Neither given: `None`. A quality that isn't a number from 0 to 12, or a+/// format other than the three names, is an error.+pub fn choice_param(params: &Value, cmd: &str) -> Result<Option<JpegChoice>, String> {+ let format = photocraft_engine::file_cmds::jpeg_format_param(params, cmd).map_err(|e| e.to_string())?;+ let quality = match params.get("quality") {+ None | Some(Value::Null) => None,+ Some(v) => Some(+ v.as_f64()+ .filter(|q| (0.0..=f64::from(MAX_QUALITY)).contains(q))+ .map(|q| q.round() as u8)+ .ok_or_else(|| format!("{cmd}: `quality` must be a number from 0 to 12 (Photoshop's JPEG scale), got {v}"))?,+ ),+ };+ Ok((quality.is_some() || format.is_some()).then(|| JpegChoice { quality, format: format.unwrap_or_default() }))+}++/// The params of a recorded plain `file.save` (which writes whichever file an action is played+/// on): none, unless JPEG Options changed something, so that a replay writes it too without+/// asking. `quality` is left out when the file's own quality was kept, and `jpegFormat` when it+/// is Baseline, the default.+pub fn plain_save_step(choice: Option<JpegChoice>) -> Value {+ let mut step = Value::Object(Default::default());+ if let Some(c) = choice {+ if let Some(q) = c.quality {+ step["quality"] = q.into();+ }+ if c.format != JpegFormat::Baseline {+ step["jpegFormat"] = c.format.name().into();+ }+ }+ step+}++/// The JPEG Options in a recorded save step, which replays without asking. A `file.saveACopy`+/// step from the engine command keeps its params as they were given, and the engine clamps a+/// `quality` to 0–12 and ignores one that isn't a number, so the replay reads it the same way. A+/// format other than the three names is still an error, as it is for the engine.+pub fn recorded_choice(params: &Value, cmd: &str) -> Result<Option<JpegChoice>, String> {+ let format = photocraft_engine::file_cmds::jpeg_format_param(params, cmd).map_err(|e| e.to_string())?;+ let quality = params.get("quality").and_then(Value::as_f64).filter(|q| q.is_finite()).map(|q| q.clamp(0.0, f64::from(MAX_QUALITY)).round() as u8);+ Ok((quality.is_some() || format.is_some()).then(|| JpegChoice { quality, format: format.unwrap_or_default() }))+}++/// Photoshop's name for a quality, in the UI language: Low, Medium, High or Maximum.+pub fn quality_label(q: u8) -> &'static str {+ match q {+ 0..=4 => tl!("Low"),+ 5..=7 => tl!("Medium"),+ 8..=9 => tl!("High"),+ _ => tl!("Maximum"),+ }+}++/// The 0–12 quality nearest an encoder quality (1–100), the inverse of the engine's mapping.+pub fn quality_from_percent(q: u32) -> u8 {+ let q = f64::from(q.clamp(1, 100));+ ((q - 1.0) / 99.0 * f64::from(MAX_QUALITY)).round() as u8+}++/// Where the prompt starts.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Start {+ /// Quality on the 0–12 scale.+ pub quality: u8,+ /// The opened file's own encoder quality (1–100) that `quality` was rounded from. Left on+ /// that step, OK writes it exactly and records no `quality`, so a replay keeps it too.+ pub own_quality: Option<u8>,+ pub format: JpegFormat,+}++impl Start {+ /// Starts at an opened JPEG's own encoder quality (1–100; out of range is clamped).+ pub fn own(quality: u8) -> Self {+ let q = quality.clamp(1, 100);+ Start { quality: quality_from_percent(u32::from(q)), own_quality: Some(q), format: JpegFormat::Baseline }+ }++ /// Starts at an encoder quality (1–100) that isn't the file's own, such as a preference.+ pub fn percent(quality: u32) -> Self {+ Start { quality: quality_from_percent(quality), own_quality: None, format: JpegFormat::Baseline }+ }++ /// For the active document: its opened JPEG's own quality (`Document::file_encoding`), or+ /// else the Export preferences' JPEG quality (the one Quick Export uses).+ pub fn for_active(app: &PhotocraftApp) -> Self {+ match app.session.active().and_then(|st| st.doc.file_encoding.jpeg_quality) {+ Some(q) => Start::own(q),+ None => Start::percent(app.session.prefs().export.jpeg_quality),+ }+ }+}++/// A save waiting on the JPEG Options answer.+pub struct Prompt {+ /// The document that requested the save, even if tabs change while this is open.+ doc: photocraft_doc::DocId,+ /// Where the document goes.+ pub path: String,+ /// Quality, 0–12.+ pub quality: u8,+ pub format: JpegFormat,+ /// See [`Start::own_quality`].+ pub own_quality: Option<u8>,+ /// Save a Copy: the document keeps its path and unsaved changes.+ pub copy: bool,+ /// The step the answered save is recorded as, so an action being recorded keeps it:+ /// `file.saveAs` for Save As (#2032), `file.saveACopy` for Save a Copy (#4373), and+ /// `file.save` (with no params) for File › Save writing the document's own file (#3531).+ pub record: &'static str,+}++/// `true` when `path` names a JPEG (`.jpg`, `.jpeg`, `.jpe`, …).+pub fn is_jpeg_path(path: &str) -> bool {+ photocraft_engine::file_cmds::extension(path).and_then(|e| photocraft_codecs::from_extension(&e)) == Some(photocraft_codecs::Format::Jpeg)+}++/// Whether saving the active document to `path` asks for JPEG Options.+pub fn wants_prompt(app: &PhotocraftApp, path: &str) -> bool {+ is_jpeg_path(path) && app.session.active().is_some()+}++/// Parks the save of the active document to `path` behind the prompt, starting at+/// [`Start::for_active`]. A prompt already waiting is never replaced.+pub fn park(app: &mut PhotocraftApp, path: String, copy: bool, record: &'static str) -> Result<(), String> {+ let start = Start::for_active(app);+ park_at(app, path, copy, record, start)+}++/// [`park`], starting at `start`.+pub fn park_at(app: &mut PhotocraftApp, path: String, copy: bool, record: &'static str, start: Start) -> Result<(), String> {+ if app.save_options_open() {+ return Err(crate::SAVE_OPTIONS_OPEN.into());+ }+ let doc = app.active_doc_id()?;+ let Start { quality, own_quality, format } = start;+ app.jpeg_options = Some(Prompt { doc, path, quality: quality.min(MAX_QUALITY), format, own_quality, copy, record });+ Ok(())+}++pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {+ let Some(p) = &mut app.jpeg_options else { return };+ let (mut ok, mut cancel) = (false, false);+ let (mut quality, mut format) = (p.quality, p.format);+ let modal = egui::Modal::new(egui::Id::new("jpeg-options")).show(ctx, |ui| {+ ui.set_max_width(360.0);+ ui.label(egui::RichText::new(tl!("JPEG Options")).font(crate::theme::semibold(15.0)));+ ui.add_space(4.0);+ crate::widgets::hairline(ui);+ ui.add_space(8.0);+ crate::widgets::section_label(ui, tl!("Image Options"));+ ui.horizontal(|ui| {+ ui.label(tl!("Quality"));+ ui.add(egui::DragValue::new(&mut quality).range(0..=MAX_QUALITY).speed(0.1));+ // Photoshop's presets: picking one sets the quality it starts at.+ egui::ComboBox::from_id_salt("jpeg-quality-preset").selected_text(quality_label(quality)).show_ui(ui, |ui| {+ for q in [3, 5, 8, 10] {+ if ui.selectable_label(quality_label(quality) == quality_label(q), quality_label(q)).clicked() {+ quality = q;+ }+ }+ });+ });+ ui.add(egui::Slider::new(&mut quality, 0..=MAX_QUALITY).show_value(false));+ ui.add_space(8.0);+ crate::widgets::section_label(ui, tl!("Format Options"));+ ui.radio_value(&mut format, JpegFormat::Baseline, tl!("Baseline (\"Standard\")"));+ ui.radio_value(&mut format, JpegFormat::Optimized, tl!("Baseline Optimized"));+ ui.radio_value(&mut format, JpegFormat::Progressive, tl!("Progressive"));+ ui.add_space(12.0);+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ ui.spacing_mut().item_spacing.x = 10.0;+ ok = crate::widgets::primary_button(ui, tl!("OK"), 84.0).clicked();+ cancel = crate::widgets::secondary_button(ui, tl!("Cancel"), 84.0).clicked();+ });+ });+ cancel |= modal.should_close();+ p.quality = quality.min(MAX_QUALITY);+ p.format = format;- if ok || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {++ // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels.++ if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) {+ confirm(app, ctx);+ } else if cancel {+ app.jpeg_options = None;+ app.ui.status = tl!("Save cancelled").into();+ app.ui.status_error = false;+ }+}++/// OK: writes the waiting save with the prompt's quality and format, and journals it.+pub fn confirm(app: &mut PhotocraftApp, ctx: &egui::Context) {+ let Some(p) = app.jpeg_options.take() else { return };+ // Left where it started, an opened JPEG keeps its own quality exactly rather than the nearest+ // step on the 0–12 scale (95 would be written as 92). The recorded step then leaves the+ // quality out, so a replay keeps the file's own quality too, as File › Save does (#4032).+ let own = p.own_quality.filter(|&q| quality_from_percent(u32::from(q)) == p.quality);+ let choice = JpegChoice { quality: own.is_none().then_some(p.quality), format: p.format };+ let step = if p.record == "file.save" {+ // A plain Save writes whichever file the action is played on (#3531), with the answer.+ plain_save_step(Some(choice))+ } else {+ let mut step = serde_json::json!({"path": p.path});+ choice.record(&mut step);+ step+ };+ let mut settings = choice.apply(app.save_settings());+ if own.is_some() {+ settings.jpeg_quality = own;+ }+ app.write_answered_save(ctx, p.doc, p.path, &settings, p.copy, (p.record, step));+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn jpeg_names() {+ for p in ["a.jpg", "dir/sub/a.JPEG", "C:\\x\\y.jpe", "a.jpg.jpg"] {+ assert!(is_jpeg_path(p), "{p}");+ }+ for p in ["a.jpg.psd", ".jpg", "jpg", "a.png", "a.jp2", ""] {+ assert!(!is_jpeg_path(p), "{p}");+ }+ }++ #[test]+ fn choice_params() {+ let base = JpegFormat::Baseline;+ assert_eq!(choice_param(&json!({}), "file.saveAs"), Ok(None));+ assert_eq!(choice_param(&json!({"quality": null, "jpegFormat": null}), "file.saveAs"), Ok(None));+ assert_eq!(choice_param(&json!({"quality": 12}), "file.saveAs"), Ok(Some(JpegChoice { quality: Some(12), format: base })));+ assert_eq!(choice_param(&json!({"quality": 7.6}), "file.saveAs"), Ok(Some(JpegChoice { quality: Some(8), format: base })));+ assert_eq!(choice_param(&json!({"jpegFormat": "progressive"}), "file.saveAs"), Ok(Some(JpegChoice { quality: None, format: JpegFormat::Progressive })));+ for bad in [+ json!({"quality": 13}),+ json!({"quality": -1}),+ json!({"quality": 1e300}),+ json!({"quality": "8"}),+ json!({"quality": true}),+ json!({"quality": [8]}),+ json!({"jpegFormat": "Optimized"}),+ json!({"jpegFormat": 1}),+ json!({"quality": 8, "jpegFormat": ""}),+ ] {+ assert!(choice_param(&bad, "file.saveAs").is_err(), "{bad}");+ }+ }++ #[test]+ fn recorded_steps_read_like_the_engine() {+ let base = JpegFormat::Baseline;+ assert_eq!(recorded_choice(&json!({"path": "a.jpg"}), "file.saveACopy"), Ok(None));+ assert_eq!(recorded_choice(&json!({"quality": 90}), "file.saveACopy"), Ok(Some(JpegChoice { quality: Some(12), format: base })));+ assert_eq!(recorded_choice(&json!({"quality": -3}), "file.saveACopy"), Ok(Some(JpegChoice { quality: Some(0), format: base })));+ assert_eq!(recorded_choice(&json!({"quality": "8"}), "file.saveACopy"), Ok(None), "a quality that isn't a number is ignored");+ assert_eq!(+ recorded_choice(&json!({"quality": 7.6, "jpegFormat": "optimized"}), "file.saveAs"),+ Ok(Some(JpegChoice { quality: Some(8), format: JpegFormat::Optimized }))+ );+ assert!(recorded_choice(&json!({"jpegFormat": "fast"}), "file.saveACopy").is_err());+ }++ #[test]+ fn quality_scale() {+ assert_eq!([0, 4, 5, 7, 8, 9, 10, 12].map(quality_label), ["Low", "Low", "Medium", "Medium", "High", "High", "Maximum", "Maximum"]);+ // The prompt's starting quality maps back to the encoder quality it came from, near enough.+ for q in 0..=MAX_QUALITY {+ assert_eq!(quality_from_percent(u32::from(photocraft_engine::file_cmds::jpeg_quality(f64::from(q)))), q);+ }+ assert_eq!((quality_from_percent(0), quality_from_percent(85), quality_from_percent(1000)), (0, 10, 12));+ }++ #[test]+ fn starts() {+ assert_eq!(Start::own(95), Start { quality: 11, own_quality: Some(95), format: JpegFormat::Baseline });+ assert_eq!(Start::own(0), Start { quality: 0, own_quality: Some(1), format: JpegFormat::Baseline });+ assert_eq!(Start::own(255).own_quality, Some(100));+ assert_eq!(Start::percent(85), Start { quality: 10, own_quality: None, format: JpegFormat::Baseline });+ assert_eq!(Start::percent(u32::MAX).quality, MAX_QUALITY);+ }++ #[test]+ fn choices_apply_and_record() {+ let c = JpegChoice { quality: Some(10), format: JpegFormat::Optimized };+ let s = c.apply(ExportSettings::default());+ assert_eq!((s.jpeg_quality, s.jpeg_format), (Some(84), JpegFormat::Optimized));+ let mut step = json!({"path": "a.jpg"});+ c.record(&mut step);+ assert_eq!(step, json!({"path": "a.jpg", "quality": 10, "jpegFormat": "optimized"}));+ assert_eq!(choice_param(&step, "file.saveAs"), Ok(Some(c)), "a recorded step replays the same answer");+ let unset = JpegChoice { quality: None, format: JpegFormat::Progressive }.apply(ExportSettings { jpeg_quality: Some(95), ..ExportSettings::default() });+ assert_eq!(unset.jpeg_quality, Some(95), "no quality keeps the quality the save had");+ }+}diff --cc crates/ui-egui/src/lib.rsindex ad5a147c8,3e3b1d2e5..acea03687--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -253,49 -253,6 +254,63 @@@ pub use file_dialog::{FileDialogAnswerpub use file_open::OsEvent;pub use state::{Tool, UiState};+/// The error a save gets while another save waits on its format prompt.- pub(crate) const SAVE_OPTIONS_OPEN: &str = "Answer TIFF, Targa or JPEG Options before starting another save";++pub(crate) const SAVE_OPTIONS_OPEN: &str = "Answer the TIFF, Targa, DDS or JPEG Options before starting another save";+- /// What a save was told beyond its path, so it skips the prompts that would ask: Targa bits- /// (`tgaBits`) and JPEG Options (`quality` 0–12, `jpegFormat`).++/// The format answers a save takes instead of asking: the Targa bits per pixel (`"tgaBits"`),++/// the DDS options (`"ddsCompression"`, `"ddsMipmaps"`) and JPEG Options (`"quality"` 0–12,++/// `"jpegFormat"`). `None` asks in Save As and takes the default in automation saves, which never++/// prompt.+#[derive(Clone, Copy, Debug, Default, PartialEq)]- pub struct SaveChoices {++pub struct FormatChoices {+ pub tga_bits: Option<photocraft_io::TgaBits>,++ pub dds: Option<photocraft_io::DdsOptions>,+ pub jpeg: Option<jpeg_options_ui::JpegChoice>,+}+- impl SaveChoices {- /// The choices in command or control call `cmd`'s params; one it can't read is an error.++impl FormatChoices {++ /// The answers in command or control call `cmd`'s params; a bad value is an error.+ pub fn from_params(params: &Value, cmd: &str) -> Result<Self, String> {- Ok(SaveChoices { tga_bits: targa_options_ui::bits_param(params, cmd)?, jpeg: jpeg_options_ui::choice_param(params, cmd)? })++ Ok(FormatChoices {++ tga_bits: targa_options_ui::bits_param(params, cmd)?,++ dds: dds_options_ui::options_param(params, cmd)?,++ jpeg: jpeg_options_ui::choice_param(params, cmd)?,++ })+ }+- /// The choices in a recorded save step, read as leniently as the engine command that may have++ /// The answers in a recorded save step, read as leniently as the engine command that may have+ /// recorded it (see [`jpeg_options_ui::recorded_choice`]).- fn from_step(params: &Value, cmd: &str) -> Result<Self, String> {- Ok(SaveChoices { tga_bits: targa_options_ui::bits_param(params, cmd)?, jpeg: jpeg_options_ui::recorded_choice(params, cmd)? })++ pub(crate) fn from_step(params: &Value, cmd: &str) -> Result<Self, String> {++ Ok(FormatChoices {++ tga_bits: targa_options_ui::bits_param(params, cmd)?,++ dds: dds_options_ui::options_param(params, cmd)?,++ jpeg: jpeg_options_ui::recorded_choice(params, cmd)?,++ })+ }+- /// `settings` writing these choices.++ /// The export settings with these answers applied.+ pub fn apply(self, settings: ExportSettings) -> ExportSettings {- let settings = ExportSettings { tga_bits: self.tga_bits.or(settings.tga_bits), ..settings };++ let settings = ExportSettings { tga_bits: self.tga_bits.or(settings.tga_bits), dds: self.dds.unwrap_or(settings.dds), ..settings };+ match self.jpeg {+ Some(j) => j.apply(settings),+ None => settings,+ }+ }+- /// Adds the choices to a recorded save step.- fn record(self, step: &mut Value) {++ /// Adds the answers to a recorded save step.++ pub(crate) fn record(self, step: &mut Value) {+ if let Some(bits) = self.tga_bits {+ step["tgaBits"] = bits.bits().into();+ }++ if let Some(dds) = self.dds {++ dds_options_ui::record(dds, step);++ }+ if let Some(j) = self.jpeg {+ j.record(step);+ }+ }+}+/// Decode a file: (document, warnings about anything approximated or dropped).pub type ImportFn = Box<dyn Fn(&str, &[u8], usize) -> Result<(Document, Vec<String>), String>>;/// Encoder settings chosen in Export As (the file format comes from the name's extension).@@@ -888,8 -877,8 +908,10 @@@ pub struct PhotocraftApppub(crate) disk_stamps: HashMap<photocraft_doc::DocId, (String, FileStamp)>,/// A save to an RGB Targa parked behind the Targa Options prompt (see `targa_options_ui`).pub(crate) targa_options: Option<targa_options_ui::Prompt>,+ /// A save to a JPEG parked behind the JPEG Options prompt (see `jpeg_options_ui`).+ pub(crate) jpeg_options: Option<jpeg_options_ui::Prompt>,+ /// A save to a DDS texture parked behind the DDS Options prompt (see `dds_options_ui`).+ pub(crate) dds_options: Option<dds_options_ui::Prompt>,/// Files read but not opened yet: the first waits on its profile prompt, the rest behind it/// (see `open_prompt`).pub(crate) held_opens: std::collections::VecDeque<open_prompt::Held>,@@@ -1041,7 -1030,7 +1063,8 @@@ impl PhotocraftAppsave_dirs: HashMap::new(),disk_stamps: HashMap::new(),targa_options: None,+ jpeg_options: None,+ dds_options: None,held_opens: Default::default(),allow_close: false,stylus: Default::default(),@@@ -1493,22 -1482,22 +1516,22 @@@/// continues on a later frame, see `file_dialog`). Returns `{"path", "warnings"}` (the export/// warnings are also shown to the user).pub fn save_as(&mut self, path: Option<String>) -> Result<Value, String> {- self.save_as_with(path, SaveChoices::default())+ self.save_as_with(path, FormatChoices::default())}- /// [`Self::save_as`], writing a Targa or DDS texture with the `choices` given instead of- /// asking for them (no Targa or DDS Options prompt): `file.save` and `file.saveAs` with- /// `tgaBits`, `ddsCompression` or `ddsMipmaps`.+ /// [`Self::save_as`] with the format choices already made, which skip their prompts:- /// `file.save` and `file.saveAs` with `tgaBits` (no Targa Options), or `quality` or- /// `jpegFormat` (no JPEG Options).- pub fn save_as_with(&mut self, path: Option<String>, choices: SaveChoices) -> Result<Value, String> {++ /// `file.save` and `file.saveAs` with `tgaBits` (no Targa Options), `ddsCompression` or++ /// `ddsMipmaps` (no DDS Options), or `quality` or `jpegFormat` (no JPEG Options).+ pub fn save_as_with(&mut self, path: Option<String>, choices: FormatChoices) -> Result<Value, String> {self.save_dialog_flow(path, choices, false)}/// [`Self::save_as_with`]. `plain_save` marks File › Save that had to ask for a file name/// (a flat file): confirming the document's own file is recorded as a `file.save` step,/// which writes whichever file the action is played on, not as a Save As to a fixed path.- pub(crate) fn save_dialog_flow(&mut self, path: Option<String>, choices: SaveChoices, plain_save: bool) -> Result<Value, String> {+ pub(crate) fn save_dialog_flow(&mut self, path: Option<String>, choices: FormatChoices, plain_save: bool) -> Result<Value, String> {if self.save_options_open() {- return Err("Answer the TIFF, Targa or DDS Options before starting another save".into());+ return Err(SAVE_OPTIONS_OPEN.into());}// Edit Contents documents save back into their smart object.if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") {@@@ -1566,20 -1555,20 +1589,26 @@@}/// [`Self::save_as_with`] once the path is known.- pub(crate) fn save_to(&mut self, path: String, choices: SaveChoices) -> Result<Value, String> {- // An RGB Targa asks for its bits per pixel, and a JPEG for its quality and format, unless- // the caller chose them; the save continues from the prompt (still a copy when it would- // be one without the prompt), which records the step once answered.+ pub(crate) fn save_to(&mut self, path: String, choices: FormatChoices) -> Result<Value, String> {- // An RGB Targa asks for its bits per pixel, and a DDS texture for its compression, unless- // the caller chose them; the save continues from the prompt (still a copy when it would- // be one without the prompt), which records the step once answered.++ // An RGB Targa asks for its bits per pixel, a DDS texture for its compression, and a JPEG++ // for its quality and format, unless the caller chose them; the save continues from the++ // prompt (still a copy when it would be one without the prompt), which records the step++ // once answered.if choices.tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) {let copy = self.saves_copy(&path, None)?;targa_options_ui::park(self, path.clone(), copy, "file.saveAs")?;return Ok(serde_json::json!({"path": path, "warnings": []}));}+ if choices.dds.is_none() && dds_options_ui::wants_prompt(&path) {+ let copy = self.saves_copy(&path, None)?;+ dds_options_ui::park(self, path.clone(), copy, "file.saveAs")?;+ return Ok(serde_json::json!({"path": path, "warnings": []}));+ }+ if choices.jpeg.is_none() && jpeg_options_ui::wants_prompt(self, &path) {+ let copy = self.saves_copy(&path, None)?;+ jpeg_options_ui::park(self, path.clone(), copy, "file.saveAs")?;+ return Ok(serde_json::json!({"path": path, "warnings": []}));+ }// A layered TIFF asks about its layers first (Preferences › File Handling); the save// continues from the prompt, which records the step once answered.if tiff_options_ui::wants_prompt(self, &path) {@@@ -1589,29 -1578,22 +1618,25 @@@self.save_as_step(path, None, choices)}- /// File › Save back to the document's own layered file, recorded as a `file.save` step.- pub(crate) fn save_in_place(&mut self, path: String) -> Result<Value, String> {- self.save_in_place_with(path, SaveChoices::default())- }-- /// [`Self::save_in_place`] with JPEG Options already answered (a replayed or scripted Save),- /// recorded with them ([`jpeg_options_ui::plain_save_step`]).- pub(crate) fn save_in_place_with(&mut self, path: String, choices: SaveChoices) -> Result<Value, String> {+ /// File › Save back to the document's own file, recorded as a `file.save` step with the- /// Targa or DDS answer in `choices` (a replayed Save of a flat file brings its own).++ /// Targa, DDS or JPEG answer in `choices` (a replayed or scripted Save of a flat file brings++ /// its own).+ pub(crate) fn save_in_place(&mut self, path: String, choices: FormatChoices) -> Result<Value, String> {if self.save_options_open() {- return Err("Answer the TIFF, Targa or DDS Options before starting another save".into());+ return Err(SAVE_OPTIONS_OPEN.into());}let r = self.write_save(path, None, choices)?;- let mut step = Value::Object(Default::default());- choices.record(&mut step);++ // JPEG Options are recorded only where they change something++ // ([`jpeg_options_ui::plain_save_step`]); the Targa and DDS answers as given.+ let mut step = jpeg_options_ui::plain_save_step(choices.jpeg);- if let Some(bits) = choices.tga_bits {- step["tgaBits"] = bits.bits().into();- }++ FormatChoices { jpeg: None, ..choices }.record(&mut step);self.session.journal.push(("file.save".into(), step));Ok(r)}/// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF,- /// Targa or JPEG answer), so an action being recorded keeps it (#2032).- fn save_as_step(&mut self, path: String, tiff_layers: Option<bool>, choices: SaveChoices) -> Result<Value, String> {- /// Targa or DDS answer), so an action being recorded keeps it (#2032).++ /// Targa, DDS or JPEG answer), so an action being recorded keeps it (#2032).+ fn save_as_step(&mut self, path: String, tiff_layers: Option<bool>, choices: FormatChoices) -> Result<Value, String> {let r = self.write_save(path.clone(), tiff_layers, choices)?;let mut step = serde_json::json!({"path": path});if let Some(layers) = tiff_layers {@@@ -1622,38 -1604,40 +1647,46 @@@Ok(r)}- /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]).- /// A JPEG save still waiting on JPEG Options is recorded as File › Save once answered.+ /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]),- /// keeping its Targa or DDS answer so playback writes the file the same way. A save parked- /// behind Targa or DDS Options hasn't been journaled yet: it is recorded as File › Save once- /// answered.++ /// keeping its Targa, DDS or JPEG answer so playback writes the file the same way. A save++ /// parked behind Targa, DDS or JPEG Options hasn't been journaled yet: it is recorded as++ /// File › Save once answered.pub(crate) fn journal_as_plain_save(&mut self, path: &str) {- if let Some(p) = self.jpeg_options.as_mut()- && p.path == path- {- p.record = "file.save";- let parked = [self.targa_options.as_mut().map(|p| (&p.path, &mut p.record)), self.dds_options.as_mut().map(|p| (&p.path, &mut p.record))];++ let parked = [++ self.targa_options.as_mut().map(|p| (&p.path, &mut p.record)),++ self.dds_options.as_mut().map(|p| (&p.path, &mut p.record)),++ self.jpeg_options.as_mut().map(|p| (&p.path, &mut p.record)),++ ];+ if let Some((_, record)) = parked.into_iter().flatten().find(|(p, record)| p.as_str() == path && **record == "file.saveAs") {+ *record = "file.save";return;}- // Only the path goes: a script's JPEG or Targa answer stays, so a replay writes the file- // it is played on the same way. Any other answer (TIFF layers) keeps the Save As.++ // Only the path goes: a script's format answer stays, so a replay writes the file it is++ // played on the same way. Any other answer (TIFF layers) keeps the Save As.if let Some(last) = self.session.journal.last_mut()&& last.0 == "file.saveAs"&& last.1.get("path").and_then(Value::as_str) == Some(path)&& let Some(step) = last.1.as_object()- && step.keys().all(|k| matches!(k.as_str(), "path" | "quality" | "jpegFormat" | "tgaBits"))- && step.keys().all(|k| matches!(k.as_str(), "path" | "tgaBits" | "ddsCompression" | "ddsMipmaps"))++ && step.keys().all(|k| matches!(k.as_str(), "path" | "tgaBits" | "ddsCompression" | "ddsMipmaps" | "quality" | "jpegFormat")){- let step: serde_json::Map<String, Value> = step.iter().filter(|(k, _)| k.as_str() != "path").map(|(k, v)| (k.clone(), v.clone())).collect();+ let mut step = step.clone();+ step.remove("path");*last = ("file.save".into(), Value::Object(step));}}- /// Replays a recorded `file.save` / `file.saveAs` / `file.saveACopy` step: no dialog or prompt, and the- /// recorded TIFF, Targa or DDS answer (if any) stands in for the TIFF, Targa or DDS Options prompt.+ /// Replays a recorded `file.save` / `file.saveAs` / `file.saveACopy` step: no dialog or- /// prompt, and the recorded TIFF, Targa or JPEG answer (if any) stands in for its prompt.++ /// prompt, and the recorded TIFF, Targa, DDS or JPEG answer (if any) stands in for its prompt.pub(crate) fn replay_save(&mut self, id: &str, params: &Value) -> Result<Value, String> {if self.save_options_open() {- return Err("Answer the TIFF, Targa or DDS Options before starting another save".into());+ return Err(SAVE_OPTIONS_OPEN.into());}if id == "file.save" {// The file the action is played on: one that holds the whole document, or a flat// file a recorded Save confirmed in the dialog while the document is still a plain- // raster, so it is never flattened over (#3531, #3806).- // raster, so it is never flattened over (#3531, #3806). A flat file's recorded Targa- // or DDS answer stands in for the prompt.- let choices = FormatChoices::from_params(params, id)?;++ // raster, so it is never flattened over (#3531, #3806). A flat file's recorded Targa,++ // DDS or JPEG answer writes the same way, without asking.++ let choices = FormatChoices::from_step(params, id)?;let st = self.session.active().ok_or("no document")?;let flat_own = |p: &str| {!photocraft_engine::file_cmds::saves_in_place(p)@@@ -1663,11 -1647,10 +1696,10 @@@let path = st.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p) || flat_own(p)).ok_or("Save writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file (OpenRaster only when it holds everything), or to its own flat file while the document is a single plain layer",)?;- // A recorded JPEG Options answer writes the same way, without asking.- return self.save_in_place_with(path, SaveChoices::from_step(params, id)?);+ return self.save_in_place(path, choices);}let path = params.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).ok_or("Save As needs a `path`")?;- let choices = SaveChoices::from_step(params, id)?;- let choices = FormatChoices::from_params(params, id)?;++ let choices = FormatChoices::from_step(params, id)?;if id == "file.saveACopy" {// A copy: the document keeps its own file and unsaved state, as when recorded (#4373).let doc = self.session.active().ok_or("no document")?.doc.clone();@@@ -1713,9 -1696,9 +1745,10 @@@}/// Writes the active document to a known path. `tiff_layers` is the TIFF Options answer:- /// `Some(false)` discards the layers and saves a copy. `choices` are the Targa bits per- /// pixel (`None`: 32 with an alpha channel or transparency, else 24) and the DDS options.+ /// `Some(false)` discards the layers and saves a copy. `choices` are the Targa bits per pixel- /// (`None`: 32 with an alpha channel or transparency, else 24) and the JPEG Options.- fn write_save(&mut self, path: String, tiff_layers: Option<bool>, choices: SaveChoices) -> Result<Value, String> {++ /// (`None`: 32 with an alpha channel or transparency, else 24), the DDS options and the JPEG++ /// Options.+ fn write_save(&mut self, path: String, tiff_layers: Option<bool>, choices: FormatChoices) -> Result<Value, String> {let copy = self.saves_copy(&path, tiff_layers)?;let settings = choices.apply(ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), ..self.save_settings() });match self.write_document(path.clone(), &settings, copy)? {@@@ -1823,30 -1806,9 +1856,30 @@@own == path && self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)).is_some_and(|now| now != *then)}- /// TIFF, Targa or JPEG Options is waiting on an answer before a save is written.- /// TIFF, Targa or DDS Options is waiting on an answer before a save is written.++ /// TIFF, Targa, DDS or JPEG Options is waiting on an answer before a save is written.pub(crate) fn save_options_open(&self) -> bool {- self.tiff_options.is_some() || self.targa_options.is_some() || self.jpeg_options.is_some()- self.tiff_options.is_some() || self.targa_options.is_some() || self.dds_options.is_some()++ self.tiff_options.is_some() || self.targa_options.is_some() || self.dds_options.is_some() || self.jpeg_options.is_some()+ }+- /// Writes a save that waited on a format prompt (Targa or JPEG Options) once answered:++ /// Writes a save that waited on a format prompt (Targa, DDS or JPEG Options) once answered:+ /// journals `step` as its command (`file.saveAs` for Save As, `file.saveACopy` for Save a+ /// Copy, `file.save` for a plain Save), so an action being recorded keeps it with this answer+ /// (#2032, #4373), reports a failure in the status bar, and releases a close prompt waiting on+ /// the save.+ pub(crate) fn write_answered_save(&mut self, ctx: &egui::Context, doc: DocId, path: String, settings: &ExportSettings, copy: bool, step: (&str, Value)) {+ let written = self.with_document(doc, |app| app.write_document(path, settings, copy));+ if written.is_ok() {+ self.session.journal.push((step.0.into(), step.1));+ }+ match written {+ Err(e) => {+ self.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]);+ self.ui.status_error = true;+ }+ Ok(Some(_)) if !copy => crate::discard_ui::saved_document(self, ctx, doc),+ // A background save releases the close prompt when it finishes (`jobs_ui`).+ Ok(_) => {}+ }}/// A print worker may still be handing a job to the system queue.@@@ -1863,12 -1825,13 +1896,13 @@@/// picker or ambient writer is reachable from this path. Returns the path/// written and the export warnings (also shown to the user).pub fn save_automation(&mut self, path: Option<String>) -> Result<Value, String> {- self.save_automation_with(path, SaveChoices::default())+ self.save_automation_with(path, FormatChoices::default())}- /// [`Self::save_automation`] with the Targa bits per pixel (`None`: 32 with an alpha channel- /// or transparency, else 24) and JPEG Options in `choices`. Automation saves never prompt.- pub fn save_automation_with(&mut self, path: Option<String>, choices: SaveChoices) -> Result<Value, String> {- /// [`Self::save_automation`] writing a Targa or DDS texture with the `choices` given (a- /// Targa's `None`: 32 with an alpha channel or transparency, else 24; a DDS texture's:- /// uncompressed without mipmaps). Automation saves never prompt.++ /// [`Self::save_automation`] writing with the format `choices` given (a Targa's `None`: 32++ /// with an alpha channel or transparency, else 24; a DDS texture's: uncompressed without++ /// mipmaps; a JPEG's: the file's own quality, Baseline). Automation saves never prompt.+ pub fn save_automation_with(&mut self, path: Option<String>, choices: FormatChoices) -> Result<Value, String> {let target = {let state = self.session.active().ok_or("no document")?;// As File › Save: without `path` only a layered file is written back (#416).@@@ -2191,7 -2154,7 +2225,8 @@@ impl eframe::App for PhotocraftAppdiscard_ui::show(self, &ctx);tiff_options_ui::show(self, &ctx);targa_options_ui::show(self, &ctx);+ jpeg_options_ui::show(self, &ctx);+ dds_options_ui::show(self, &ctx);distort_ui::show(self, &ctx);camera_raw_ui::show(self, &ctx);wide_angle_ui::show(self, &ctx);diff --cc crates/ui-egui/src/menus.rsindex dc1ab9012,79632791d..490d8f3c6--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -240,8 -240,8 +240,8 @@@ pub(crate) fn invoke_unguarded(app: &muSome((true, path, d)) => {// Another app changed the file since it was opened or saved: ask first (#6596).let doc = d.doc.id;- crate::disk_change_prompt::intercept(app, doc, &path, false, crate::SaveChoices::default())- .unwrap_or_else(|| app.save_in_place(path))- crate::disk_change_prompt::intercept(app, doc, &path, false)++ crate::disk_change_prompt::intercept(app, doc, &path, false, crate::FormatChoices::default())+ .unwrap_or_else(|| app.save_in_place(path, crate::FormatChoices::default()))}Some((false, path, d)) if photocraft_engine::file_cmds::saves_in_place(&path) => {// Its own file is layered but can't hold what the document has now.diff --cc crates/ui-egui/src/targa_options_ui.rsindex 8abb64e90,5a8b47d58..446bd0cb7--- a/crates/ui-egui/src/targa_options_ui.rs+++ b/crates/ui-egui/src/targa_options_ui.rs@@@ -76,11 -77,26 +77,14 @@@ pub fn show(app: &mut PhotocraftApp, ct});cancel |= modal.should_close();p.bits = bits;- if ok || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {+ // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels.+ if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) {let Some(p) = app.targa_options.take() else { return };let settings = ExportSettings { tga_bits: Some(p.bits), ..app.save_settings() };- let step = serde_json::json!({"path": p.path, "tgaBits": p.bits.bits()});++ // A plain Save writes whichever file the action is played on (#3531): no path.+ let mut step = if p.record == "file.save" { serde_json::json!({}) } else { serde_json::json!({"path": p.path}) };+ step["tgaBits"] = p.bits.bits().into();- let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.copy));- if written.is_ok() {- // An action being recorded keeps the Save As or Save a Copy with this answer (#2032).- app.session.journal.push((p.record.into(), step));- }- match written {- Err(e) => {- app.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]);- app.ui.status_error = true;- }- Ok(Some(_)) if !p.copy => crate::discard_ui::saved_document(app, ctx, p.doc),- // A background save releases the close prompt when it finishes (`jobs_ui`).- Ok(_) => {}- }+ app.write_answered_save(ctx, p.doc, p.path, &settings, p.copy, (p.record, step));} else if cancel {app.targa_options = None;app.ui.status = tl!("Save cancelled").into();diff --cc crates/ui-egui/src/view_cmds.rsindex 445d82b3d,ae19bfa6a..2ad08df08--- a/crates/ui-egui/src/view_cmds.rs+++ b/crates/ui-egui/src/view_cmds.rs@@@ -1442,17 -1442,17 +1442,21 @@@ fn save_a_copy(app: &mut PhotocraftApplet suggested = format!("{stem} copy.psd");// The copy is of the document as it was when asked.app.pick_save(&suggested, move |app, path| {- // An RGB Targa asks for its bits per pixel first, and a JPEG for its JPEG Options; the- // copy is written from the prompt.- // An RGB Targa asks for its bits per pixel first, and a DDS texture for its compression;- // the copy is written from the prompt.++ // An RGB Targa asks for its bits per pixel first, a DDS texture for its compression, and++ // a JPEG for its JPEG Options; the copy is written from the prompt.let parked = app.with_document(doc.id, |app| {if crate::targa_options_ui::wants_prompt(app, &path) {crate::targa_options_ui::park(app, path.clone(), true, "file.saveACopy")?;return Ok(true);}+ if crate::dds_options_ui::wants_prompt(&path) {+ crate::dds_options_ui::park(app, path.clone(), true, "file.saveACopy")?;+ return Ok(true);+ }+ if crate::jpeg_options_ui::wants_prompt(app, &path) {+ crate::jpeg_options_ui::park(app, path.clone(), true, "file.saveACopy")?;+ return Ok(true);+ }Ok(false)})?;if parked {@@@ -1465,8 -1465,8 +1469,9 @@@}/// Writes `doc` to `path` as a copy (Save a Copy, and its replayed action step): the document's- /// path and saved state are untouched. `choices` are the Targa and JPEG answers, when there are any.- pub(crate) fn write_copy(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, path: &str, choices: crate::SaveChoices) -> Result<Value, String> {-/// path and saved state are untouched. `choices` are the Targa and DDS answers, when there are any.++/// path and saved state are untouched. `choices` are the Targa, DDS and JPEG answers, when there++/// are any.+ pub(crate) fn write_copy(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, path: &str, choices: crate::FormatChoices) -> Result<Value, String> {let settings = choices.apply(app.save_settings());let export = app.services.export.as_ref().ok_or("no exporter configured")?;let (bytes, warnings) = export(doc, path, &settings)?;diff --cc docs/control-protocol.mdindex 2551b86bf,918a9f811..72981a5a0--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@@ -88,7 -88,7 +88,7 @@@ The transport is `apps/photocraft/src/cbase64 PNG data; a path is relative to the automation write root. Raises the window first(default) because occluded macOS windows stop rendering- `ui.focus`: bring the main window to the front- - `app.open {path}` / `app.save {path?, tgaBits?, quality?, jpegFormat?}` (JPEG: `quality` on the 0–12 scale, `jpegFormat` `baseline`, `optimized` or `progressive`; automation never shows JPEG Options): relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. Automation saves never show TGA or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands))-- `app.open {path}` / `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. `ddsCompression` (`none`, `bc1`, `bc2` or `bc3`) and `ddsMipmaps` (bool) set a DDS texture's compression and mip chain; without them, uncompressed without mipmaps. Automation saves never show TGA, DDS or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands))++- `app.open {path}` / `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?, quality?, jpegFormat?}` (JPEG: `quality` on the 0–12 scale, `jpegFormat` `baseline`, `optimized` or `progressive`; automation never shows JPEG Options): relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. `ddsCompression` (`none`, `bc1`, `bc2` or `bc3`) and `ddsMipmaps` (bool) set a DDS texture's compression and mip chain; without them, uncompressed without mipmaps. Automation saves never show TGA, DDS, JPEG or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands))- `app.quit`## Engine commandsdiff --cc docs/file-format-parity.mdindex 001cac406,938a723b6..0a95c6ef1--- a/docs/file-format-parity.md+++ b/docs/file-format-parity.md@@@ -1,6 -1,6 +1,6 @@@# File-format parity- > **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-19 · **Change:** minor (JPEG Options on Save As and Save a Copy, FILE-215-19; PNG `sTER` stereo pairing kept on save, #6063; earlier: PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); earlier: PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026++> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-19 · **Change:** minor (JPEG Options on Save As and Save a Copy, FILE-215-19; earlier: DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PNG `sTER` stereo pairing kept on save, #6063; earlier: PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity andtests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write@@@ -142,8 -142,9 +142,10 @@@ remaining gaps in #1606 stay tracked wi| Date | Change | Summary ||---|---|---|+| 2026-10-19 | minor | JPEG Options on Save As and Save a Copy (FILE-215-19) |+ | 2026-10-15 | minor | DDS textures save (#1327): uncompressed or BC1/BC2/BC3 (DXT1/3/5) from a clean-room block encoder, optional box-filtered mip chain, legacy header; DDS Options in Save As and Save a Copy, `ddsCompression`/`ddsMipmaps` for scripts, the CLI and MCP || 2026-10-15 | minor | PNG: a stereo PNG's `sTER` pairing (PNG Extensions 1.4.0 §3.6) is read on open and written back on save, so the file still says it is a stereo pair (#6063) |+ | 2026-10-15 | minor | PSD guides: image resource 1092 (guides v2) gives guides their own colours on import; 1092 and 1097 (guide GUIDs) are written back only while they still describe the document's guides, so an edit no longer leaves Photoshop a stale second guide list (#5966) || 2026-10-14 | minor | PSD smart filter masks: Photoshop stores a smart object's filtered pixels without its filter mask and mixes the unfiltered ones (`FEid`) back in; import now mixes them and export writes them that way, so sf-filter-mask-hard, -gradient and sf-stack-blend-and-mask pass; Photoshop-oracle floor 185 → 188 of 258 || 2026-10-13 | minor | Lossy DNG (compression 34892) decodes: 8-bit baseline JPEG tiles and strips, CFA and LinearRaw, partial edge tiles; the stored values take the normal levels and LinearizationTable (FILE-215-11, lossy DNG part) || 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 |