Merge current main and preserve Export As behavior while adding JPEG XL

This commit is contained in:
Nigel Ihza Firdausy committed 2026-10-14 21:33:26 +07:00
commit ce838d85d3
6 files changed
+428 -74

No files matched your search

Generated
+29 -29
View File
@@ -4613,7 +4613,7 @@ dependencies = [
[[package]]
name = "photocraft"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"arboard",
"async-io",
@@ -4657,7 +4657,7 @@ dependencies = [
[[package]]
name = "photocraft-affinity"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"crc32fast",
"flate2",
@@ -4667,7 +4667,7 @@ dependencies = [
[[package]]
name = "photocraft-algo"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4680,7 +4680,7 @@ dependencies = [
[[package]]
name = "photocraft-automation"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"base64 0.22.1",
"cap-std",
@@ -4702,7 +4702,7 @@ dependencies = [
[[package]]
name = "photocraft-cli"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"photocraft-automation",
"photocraft-codecs",
@@ -4716,7 +4716,7 @@ dependencies = [
[[package]]
name = "photocraft-cms"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"moxcms",
"rayon",
@@ -4724,7 +4724,7 @@ dependencies = [
[[package]]
name = "photocraft-codecs"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"exr",
"flate2",
@@ -4747,7 +4747,7 @@ dependencies = [
[[package]]
name = "photocraft-color"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"photocraft-cms",
"serde",
@@ -4755,7 +4755,7 @@ dependencies = [
[[package]]
name = "photocraft-compose"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"criterion",
"photocraft-color",
@@ -4770,7 +4770,7 @@ dependencies = [
[[package]]
name = "photocraft-doc"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4781,7 +4781,7 @@ dependencies = [
[[package]]
name = "photocraft-engine"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"blake3",
"craft-print",
@@ -4816,7 +4816,7 @@ dependencies = [
[[package]]
name = "photocraft-format"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"blake3",
"crc32fast",
@@ -4837,14 +4837,14 @@ dependencies = [
[[package]]
name = "photocraft-geom"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"serde",
]
[[package]]
name = "photocraft-gpu"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"half",
"log",
@@ -4861,14 +4861,14 @@ dependencies = [
[[package]]
name = "photocraft-heif"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"heic-rs",
]
[[package]]
name = "photocraft-io"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"blake3",
"crc32fast",
@@ -4897,14 +4897,14 @@ dependencies = [
[[package]]
name = "photocraft-ops"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"photocraft-doc",
]
[[package]]
name = "photocraft-paint"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4915,7 +4915,7 @@ dependencies = [
[[package]]
name = "photocraft-plugins"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4930,7 +4930,7 @@ dependencies = [
[[package]]
name = "photocraft-psd"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"flate2",
"photocraft-psd",
@@ -4941,7 +4941,7 @@ dependencies = [
[[package]]
name = "photocraft-raster"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"photocraft-color",
"photocraft-geom",
@@ -4951,7 +4951,7 @@ dependencies = [
[[package]]
name = "photocraft-raw"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"flate2",
"image",
@@ -4966,7 +4966,7 @@ dependencies = [
[[package]]
name = "photocraft-tablet"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"block2 0.6.2",
"objc2 0.6.4",
@@ -4978,7 +4978,7 @@ dependencies = [
[[package]]
name = "photocraft-testkit"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"memory-stats",
"photocraft-color",
@@ -4989,7 +4989,7 @@ dependencies = [
[[package]]
name = "photocraft-text"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"flate2",
"parley",
@@ -5003,7 +5003,7 @@ dependencies = [
[[package]]
name = "photocraft-ui-egui"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"base64 0.22.1",
"craft-print",
@@ -5044,7 +5044,7 @@ dependencies = [
[[package]]
name = "photocraft-vector"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"photocraft-color",
"photocraft-doc",
@@ -5055,7 +5055,7 @@ dependencies = [
[[package]]
name = "photocraft-web"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"eframe",
"egui",
@@ -8653,7 +8653,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xtask"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"serde",
"serde_json",
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"]
[workspace.package]
version = "0.8.2"
version = "0.9.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
+6 -1
View File
@@ -908,6 +908,7 @@ mod tests {
let mut app = launch(&recovery);
new_doc(&mut app, "#ff0000");
let revision = app.session.active().unwrap().revision;
assert_ne!(revision, 0, "a sidecar-less bundle lists as revision 0");
autosave(&mut app, &ctx);
let mut failed = false;
@@ -928,12 +929,16 @@ mod tests {
std::fs::remove_file(&recovery).unwrap();
std::fs::create_dir(&recovery).unwrap();
autosave(&mut app, &ctx);
// The worker commits the bundle's manifest before it publishes the sidecar, and
// `list_recovery` lists a committed sidecar-less bundle (revision 0) on its own, so
// the first non-empty listing can come from the middle of the write. Wait for the write
// to finish: the entry then carries the sidecar's revision.
let mut recovered = Vec::new();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while std::time::Instant::now() < deadline {
prefs_ui::tick(&mut app, &ctx);
recovered = list_recovery(&recovery);
if !recovered.is_empty() {
if recovered.iter().any(|e| e.info.revision == revision) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
+2 -8
View File
@@ -80,9 +80,7 @@ fn correct_16_bit_alpha_header(bytes: &[u8], width: u32, height: u32) -> Result<
&& read(bytes, &mut pos, 1) == Some(1); // default transform
let frame_offset = pos.div_ceil(8);
let header_matches = header_matches
&& frame_offset <= bytes.len()
&& (pos..frame_offset * 8).all(|bit| bytes[bit / 8] & (1 << (bit % 8)) == 0);
let header_matches = header_matches && frame_offset <= bytes.len() && (pos..frame_offset * 8).all(|bit| bytes[bit / 8] & (1 << (bit % 8)) == 0);
if !header_matches {
return Err(CodecError::encode(F, "unexpected zune-jpegxl header for 16-bit alpha"));
}
@@ -143,11 +141,7 @@ pub(crate) fn encode(image: &Image, plan: Plan) -> Result<Vec<u8>, CodecError> {
let options = ZuneOptions::new(width as usize, height as usize, space, depth);
let mut output = Vec::new();
JxlSimpleEncoder::new(image.data(), options).encode(&mut output).map_err(|e| CodecError::encode(F, e.to_string()))?;
if depth == BitDepth::Sixteen && image.layout() == ChannelLayout::Rgba {
correct_16_bit_alpha_header(&output, width, height)
} else {
Ok(output)
}
if depth == BitDepth::Sixteen && image.layout() == ChannelLayout::Rgba { correct_16_bit_alpha_header(&output, width, height) } else { Ok(output) }
}))
.unwrap_or_else(|_| Err(CodecError::encode(F, "the JPEG XL encoder failed")))
}
+1 -6
View File
@@ -88,12 +88,7 @@ fn jpeg_xl_preserves_sixteen_bit_alpha_across_dimension_header_sizes() {
let height = 2u32;
let mut samples = Vec::with_capacity(width as usize * height as usize * 4);
for i in 0..(width as usize * height as usize) {
samples.extend_from_slice(&[
(i as u16).wrapping_mul(127),
65535,
(i as u16).wrapping_mul(9973),
[0u16, 1, 32768, 65535][i % 4],
]);
samples.extend_from_slice(&[(i as u16).wrapping_mul(127), 65535, (i as u16).wrapping_mul(9973), [0u16, 1, 32768, 65535][i % 4]]);
}
let input = Image::from_u16(width, height, ChannelLayout::Rgba, &samples).unwrap();
let encoded = encode(&input, Format::Jxl, &EncodeOptions::default()).unwrap();
+389 -29
View File
@@ -3,6 +3,8 @@
//! pixel count, so the dialog stays instant on 36 MP documents.
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Mutex;
use photocraft_doc::Document;
use serde_json::{Map, Value, json};
@@ -11,7 +13,47 @@ use crate::state::DialogKind;
use crate::theme::Tokens;
use crate::{ExportSettings, PhotocraftApp};
const FORMATS: [(&str, &str); 6] = [("png", "PNG"), ("jpg", "JPG"), ("webp", "WebP"), ("tif", "TIFF"), ("tga", "TGA"), ("jxl", "JPEG XL")];
const FORMATS: [(&str, &str); 7] = [("png", "PNG"), ("jpg", "JPG"), ("webp", "WebP"), ("tif", "TIFF"), ("tga", "TGA"), ("ico", "ICO"), ("jxl", "JPEG XL")];
/// Preferences ▸ remembered dialog settings: Export As writes the settings it was used with
/// last under its command id and seeds the next dialog from them, as Fill, Liquify and the
/// filter dialogs do.
pub(crate) const COMMAND: &str = "file.export.exportAs";
/// The dialog is seeded from the settings it was used with last (see [`COMMAND`]); a value that
/// no longer matches a control (a hand-edited preferences file) is left at its default.
fn seed_remembered(app: &PhotocraftApp, f: &mut Map<String, Value>) {
let Some(Value::Object(saved)) = app.session.prefs().dialogs.get(COMMAND) else { return };
if let Some(v) = saved.get("format").and_then(Value::as_str).filter(|v| FORMATS.iter().any(|(k, _)| k == v)) {
f.insert("format".into(), json!(v));
}
if let Some(v) = saved.get("quality").and_then(Value::as_f64).filter(|v| (1.0..=100.0).contains(v)) {
f.insert("quality".into(), json!(v));
}
if let Some(v) = saved.get("scale").and_then(Value::as_f64).filter(|v| (1.0..=1000.0).contains(v)) {
f.insert("scale".into(), json!(v));
}
for key in ["lossless", "transparency"] {
if let Some(v) = saved.get(key).and_then(Value::as_bool) {
f.insert(key.into(), json!(v));
}
}
if let Some(v) = saved.get("metadata").and_then(Value::as_str).filter(|v| ["none", "all"].contains(v)) {
f.insert("metadata".into(), json!(v));
}
if let Some(v) = saved.get("tgaBits").and_then(Value::as_str).filter(|v| ["auto", "24", "32"].contains(v)) {
f.insert("tgaBits".into(), json!(v));
}
}
/// Record the settings for the next Export As (see [`seed_remembered`]).
fn remember(app: &mut PhotocraftApp, f: &Map<String, Value>) {
const KEYS: [&str; 7] = ["format", "quality", "lossless", "transparency", "scale", "metadata", "tgaBits"];
let saved: Map<String, Value> = KEYS.iter().filter_map(|k| f.get(*k).map(|v| ((*k).to_string(), v.clone()))).collect();
app.session.prefs.edit(|p| {
p.dialogs.insert(COMMAND.into(), Value::Object(saved));
});
}
pub fn open(app: &mut PhotocraftApp) -> Result<u64, String> {
let st = app.session.active().ok_or("no document")?;
@@ -27,6 +69,7 @@ pub fn open(app: &mut PhotocraftApp) -> Result<u64, String> {
f.insert("tgaBits".into(), json!("auto"));
f.insert("__w".into(), json!(st.doc.size.width));
f.insert("__h".into(), json!(st.doc.size.height));
seed_remembered(app, &mut f);
Ok(app.ui.open_dialog(DialogKind::Command, f))
}
@@ -37,13 +80,30 @@ pub fn open_layer(app: &mut PhotocraftApp, layer: photocraft_doc::LayerId) -> Re
let id = open(app)?;
if let Some(d) = app.ui.dialogs.iter_mut().find(|d| d.id == id) {
d.fields.insert("__layer".into(), json!(layer.0));
d.fields.insert("__label".into(), json!(format!("Export As: {}", ldoc.name)));
d.fields.insert("__label".into(), json!(crate::i18n::fmt(crate::i18n::t("Export As: {name}"), &[("name", &ldoc.name)])));
d.fields.insert("__w".into(), json!(ldoc.size.width));
d.fields.insert("__h".into(), json!(ldoc.size.height));
}
Ok(id)
}
/// Layer › Export As… with several layers (artboards, say) selected: the same dialog, then one
/// file per layer with its settings (#3629). The preview shows the first layer.
pub fn open_layers(app: &mut PhotocraftApp, layers: &[photocraft_doc::LayerId]) -> Result<u64, String> {
let (first, n) = match layers {
[] => return Err("no selected layers".into()),
[one] => return open_layer(app, *one),
[first, ..] => (*first, layers.len()),
};
let id = open_layer(app, first)?;
if let Some(d) = app.ui.dialogs.iter_mut().find(|d| d.id == id) {
d.fields.insert("__layers".into(), json!(layers.iter().map(|l| l.0).collect::<Vec<_>>()));
let template = "Export As: {n} layers";
d.fields.insert("__label".into(), json!(crate::i18n::fmt(tl!(template), &[("n", &n.to_string())])));
}
Ok(id)
}
/// Layer › Quick Export as PNG.
pub fn quick_export_layer_png(app: &mut PhotocraftApp, layer: photocraft_doc::LayerId) -> Result<Value, String> {
let mut f = Map::new();
@@ -96,10 +156,13 @@ fn export_name(name: &str) -> String {
if name.is_empty() { "layer".into() } else { name.into() }
}
/// The files a multi-layer export writes: the chosen path, then numbered siblings named after
/// each layer, in the chosen path's format.
fn batch_paths(path: &str, docs: &[Document]) -> Vec<String> {
let first = std::path::Path::new(path);
let parent = first.parent().unwrap_or_else(|| std::path::Path::new(""));
let stem = first.file_stem().and_then(|s| s.to_str()).unwrap_or("layers");
let ext = first.extension().and_then(|e| e.to_str()).unwrap_or("png");
docs.iter()
.enumerate()
.map(|(i, doc)| {
@@ -107,7 +170,7 @@ fn batch_paths(path: &str, docs: &[Document]) -> Vec<String> {
return path.to_string();
}
let name = export_name(&doc.name);
let candidate = parent.join(format!("{stem}-{}-{name}.png", i + 1));
let candidate = parent.join(format!("{stem}-{}-{name}.{ext}", i + 1));
// The first file's overwrite is handled by the Save dialog; never overwrite sibling
// files silently on desktop. Downloads on the web are named by the browser.
#[cfg(not(target_arch = "wasm32"))]
@@ -115,7 +178,7 @@ fn batch_paths(path: &str, docs: &[Document]) -> Vec<String> {
let mut candidate = candidate;
let mut suffix = 1u64;
while candidate.exists() {
candidate = parent.join(format!("{stem}-{}-{name}-{suffix}.png", i + 1));
candidate = parent.join(format!("{stem}-{}-{name}-{suffix}.{ext}", i + 1));
suffix = suffix.saturating_add(1);
}
candidate
@@ -126,14 +189,17 @@ fn batch_paths(path: &str, docs: &[Document]) -> Vec<String> {
}
/// The document a dialog exports: the whole image, or one layer (`__layer`).
fn source_document(app: &PhotocraftApp, f: &Map<String, Value>) -> Result<Arc<Document>, String> {
let st = app.session.active().ok_or("no document")?;
fn source_document_from(doc: Arc<Document>, f: &Map<String, Value>) -> Result<Arc<Document>, String> {
match f.get("__layer").and_then(Value::as_u64) {
Some(id) => photocraft_engine::layer_menu_cmds::layer_document(&st.doc, photocraft_doc::LayerId(id)).map(Arc::new).map_err(|e| e.to_string()),
None => Ok(st.doc.clone()),
Some(id) => photocraft_engine::layer_menu_cmds::layer_document(&doc, photocraft_doc::LayerId(id)).map(Arc::new).map_err(|e| e.to_string()),
None => Ok(doc),
}
}
fn source_document(app: &PhotocraftApp, f: &Map<String, Value>) -> Result<Arc<Document>, String> {
source_document_from(app.session.active().ok_or("no document")?.doc.clone(), f)
}
fn s(f: &Map<String, Value>, k: &str) -> String {
f.get(k).and_then(Value::as_str).unwrap_or_default().to_string()
}
@@ -156,6 +222,9 @@ fn export_document(doc: &Document, f: &Map<String, Value>, max_side: Option<u32>
// Both dimensions are sent: a scale can leave a 1 px width unchanged while halving the
// height, and the engine would otherwise keep the aspect ratio from the width alone.
let (w, h) = scaled_size(doc.size.width as f64, doc.size.height as f64, scale);
if s_fmt(f) == "ico" && (w > 256.0 || h > 256.0) && max_side.is_none() {
return Err("ICO export is limited to 256 × 256 pixels; reduce the export scale".into());
}
if (w - doc.size.width as f64).abs() >= 1.0 || (h - doc.size.height as f64).abs() >= 1.0 {
s.execute("image.imageSize", json!({"width": w, "height": h, "resample": if max_side.is_some() { "bilinear" } else { "bicubic" }}))
.map_err(|e| e.to_string())?;
@@ -217,15 +286,142 @@ fn settings(f: &Map<String, Value>) -> ExportSettings {
}
}
/// Estimated size (bytes) from a ≤512 px proxy encode, scaled by pixel count.
fn estimate(app: &PhotocraftApp, doc: &Document, f: &Map<String, Value>) -> Option<u64> {
let export = app.services.export.as_ref()?;
let proxy = export_document(doc, f, Some(512)).ok()?;
let (bytes, _) = export(&proxy, &format!("estimate.{}", s_fmt(f)), &settings(f)).ok()?;
/// The preview and size estimate share a single reduced document. Resizing every layer twice is
/// especially expensive for layered PSDs, even when the canvas itself is small.
fn preview_proxy(doc: &Document, f: &Map<String, Value>) -> Result<Document, String> {
export_document(doc, f, Some(if s_fmt(f) == "ico" { 256 } else { 512 }))
}
fn scaled_estimate(bytes: usize, doc: &Document, proxy: &Document, f: &Map<String, Value>) -> u64 {
let scale = n(f, "scale", 100.0) / 100.0;
let full = doc.size.width as f64 * scale * doc.size.height as f64 * scale;
let small = (proxy.size.width as f64 * proxy.size.height as f64).max(1.0);
Some((bytes.len() as f64 * full / small) as u64)
(bytes as f64 * full / small) as u64
}
/// Estimated size (bytes) from the already prepared proxy encode, scaled by pixel count.
fn estimate(app: &PhotocraftApp, doc: &Document, proxy: &Document, f: &Map<String, Value>) -> Option<u64> {
let export = app.services.export.as_ref()?;
let (bytes, _) = export(proxy, &format!("estimate.{}", s_fmt(f)), &settings(f)).ok()?;
Some(scaled_estimate(bytes.len(), doc, proxy, f))
}
struct PreviewPixels {
estimate: Option<u64>,
width: usize,
height: usize,
rgba: Vec<u8>,
}
fn preview_pixels(proxy: &Document, estimate: Option<u64>) -> PreviewPixels {
let img = photocraft_compose::thumbnail(proxy, 360);
PreviewPixels { estimate, width: img.width as usize, height: img.height as usize, rgba: img.pixels }
}
fn preview_sync(app: &PhotocraftApp, doc: &Document, f: &Map<String, Value>) -> Result<PreviewPixels, String> {
let proxy = preview_proxy(doc, f)?;
Ok(preview_pixels(&proxy, estimate(app, doc, &proxy, f)))
}
#[derive(Clone)]
struct CachedPreview {
signature: String,
estimate: Option<u64>,
texture: Option<Arc<egui::TextureHandle>>,
}
fn cache_preview(ui: &mut egui::Ui, key: egui::Id, signature: String, result: Result<PreviewPixels, String>) -> CachedPreview {
let preview = match result {
Ok(pixels) => {
let image = egui::ColorImage::from_rgba_unmultiplied([pixels.width, pixels.height], &pixels.rgba);
let texture = Arc::new(ui.ctx().load_texture("export-preview", image, egui::TextureOptions::LINEAR));
CachedPreview { signature, estimate: pixels.estimate, texture: Some(texture) }
}
Err(error) => {
log::warn!("Export As preview failed: {error}");
CachedPreview { signature, estimate: None, texture: None }
}
};
ui.data_mut(|d| d.insert_temp(key, preview.clone()));
preview
}
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone)]
struct PendingPreview {
key: egui::Id,
signature: String,
result: Arc<Mutex<Option<Result<PreviewPixels, String>>>>,
}
#[cfg(not(target_arch = "wasm32"))]
fn background_preview_needed(doc: &Document) -> bool {
doc.walk().len() > 32 || doc.size.area() > 16_000_000
}
/// Native app: keep the UI responsive while a many-layer document is reduced and encoded.
/// A single pending job per document also avoids starting a worker for every slider tick.
#[cfg(not(target_arch = "wasm32"))]
fn poll_or_start_preview(
ui: &mut egui::Ui,
key: egui::Id,
signature: &str,
doc: Arc<Document>,
fields: &Map<String, Value>,
) -> Option<Result<PreviewPixels, String>> {
let pending_key = egui::Id::new(("export-preview-pending", doc.id.0));
let pending: Option<PendingPreview> = ui.data(|d| d.get_temp(pending_key));
if let Some(pending) = pending {
let result = pending.result.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take()?;
ui.data_mut(|d| d.remove::<PendingPreview>(pending_key));
if pending.key == key && pending.signature == signature {
return Some(result);
}
}
let result = Arc::new(Mutex::new(None));
let shared = result.clone();
let ctx = ui.ctx().clone();
let fields = fields.clone();
let started = std::thread::Builder::new().name("export-preview".into()).spawn(move || {
let prepared = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let source = source_document_from(doc.clone(), &fields).unwrap_or(doc);
let proxy = preview_proxy(&source, &fields)?;
let estimate = estimate_native(&source, &proxy, &fields);
Ok::<_, String>(preview_pixels(&proxy, estimate))
}))
.unwrap_or_else(|_| Err("preview worker panicked".into()));
*shared.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(prepared);
ctx.request_repaint();
});
match started {
Ok(_) => {
ui.data_mut(|d| d.insert_temp(pending_key, PendingPreview { key, signature: signature.to_string(), result }));
None
}
Err(error) => Some(Err(format!("could not start preview worker: {error}"))),
}
}
/// The native exporter uses this same IO encoder. Keep the entire estimate off the UI thread.
#[cfg(not(target_arch = "wasm32"))]
fn estimate_native(doc: &Document, proxy: &Document, f: &Map<String, Value>) -> Option<u64> {
let settings = settings(f);
let mut options = photocraft_io::ExportOptions::default();
if let Some(quality) = settings.jpeg_quality {
options.encode.jpeg_quality = quality;
}
options.encode.webp_lossless = settings.webp_lossless;
if let Some(quality) = settings.webp_quality {
options.encode.webp_quality = quality;
}
options.tiff_layers = settings.tiff_layers;
options.xmp = if settings.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None };
options.tga_bits = settings.tga_bits;
options.image_previews = settings.image_previews;
options.psd_maximize_compatibility = settings.psd_maximize_compatibility;
let bytes = photocraft_io::export(proxy, &format!("estimate.{}", s_fmt(f)), &options).ok()?.bytes;
Some(scaled_estimate(bytes.len(), doc, proxy, f))
}
pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {
@@ -290,6 +486,9 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
let (bw, bh) = (n(f, "__w", f64::from(doc.size.width)), n(f, "__h", f64::from(doc.size.height)));
let (w, h) = scaled_size(bw, bh, f64::from(sc) / 100.0);
ui.label(egui::RichText::new(format!("{w} × {h} px")).color(t.text_dim).size(11.5));
if fmt == "ico" && (w > 256.0 || h > 256.0) {
ui.label(egui::RichText::new(tl!("ICO is limited to 256 × 256 pixels")).color(t.warning));
}
});
ui.add_space(12.0);
// Right: preview + estimated size.
@@ -306,28 +505,40 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
s(f, "metadata"),
s(f, "tgaBits")
);
let cached: Option<(String, Option<u64>, Arc<egui::TextureHandle>)> = ui.data(|d| d.get_temp(key));
let (size, tex) = match cached.filter(|c| c.0 == sig) {
Some((_, size, tex)) => (size, tex),
let cached: Option<CachedPreview> = ui.data(|d| d.get_temp(key));
let preview = match cached.filter(|cached| cached.signature == sig) {
Some(cached) => Some(cached),
None => {
let src = source_document(app, f).unwrap_or_else(|_| doc.clone());
let size = estimate(app, &src, f);
let img = photocraft_compose::thumbnail(&export_document(&src, f, Some(360)).unwrap_or_else(|_| (*src).clone()), 360);
let color = egui::ColorImage::from_rgba_unmultiplied([img.width as usize, img.height as usize], &img.pixels);
let tex = Arc::new(ui.ctx().load_texture("export-preview", color, egui::TextureOptions::LINEAR));
ui.data_mut(|d| d.insert_temp(key, (sig, size, tex.clone())));
(size, tex)
#[cfg(not(target_arch = "wasm32"))]
let result = if background_preview_needed(&doc) {
poll_or_start_preview(ui, key, &sig, doc.clone(), f)
} else {
let source = source_document(app, f).unwrap_or_else(|_| doc.clone());
Some(preview_sync(app, &source, f))
};
#[cfg(target_arch = "wasm32")]
let result = {
let source = source_document(app, f).unwrap_or_else(|_| doc.clone());
Some(preview_sync(app, &source, f))
};
result.map(|result| cache_preview(ui, key, sig, result))
}
};
let side = 300.0;
let (r, _) = ui.allocate_exact_size(egui::vec2(side, side), egui::Sense::hover());
crate::widgets::checker(ui.painter(), r, 8.0);
let ts = tex.size_vec2();
let k = (side / ts.x.max(ts.y)).min(1.0e3);
let ir = egui::Rect::from_center_size(r.center(), ts * k);
ui.painter().image(tex.id(), ir, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), egui::Color32::WHITE);
if let Some(tex) = preview.as_ref().and_then(|preview| preview.texture.as_ref()) {
let ts = tex.size_vec2();
let k = (side / ts.x.max(ts.y)).min(1.0e3);
let ir = egui::Rect::from_center_size(r.center(), ts * k);
ui.painter().image(tex.id(), ir, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), egui::Color32::WHITE);
} else if preview.is_none() {
ui.put(egui::Rect::from_center_size(r.center(), egui::vec2(24.0, 24.0)), egui::Spinner::new());
} else {
ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, tl!("Preview"), egui::FontId::proportional(12.0), t.text_dim);
}
ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Outside);
let est = size.map_or("—".to_string(), |b| crate::sizing::human_bytes(b as f64));
let est = preview.as_ref().and_then(|preview| preview.estimate).map_or("—".to_string(), |b| crate::sizing::human_bytes(b as f64));
ui.label(egui::RichText::new(format!("{} ≈ {est}", s_fmt(f).to_uppercase())).color(t.text_dim).size(11.5));
});
});
@@ -335,6 +546,11 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
/// Export with the dialog's settings: choose a path, render, encode, write.
pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
remember(app, f);
if let Some(layers) = f.get("__layers").and_then(Value::as_array) {
let ids: Vec<_> = layers.iter().filter_map(Value::as_u64).map(photocraft_doc::LayerId).collect();
return confirm_layers(app, f, &ids);
}
let doc = source_document(app, f)?;
let stem = doc.name.rsplit_once('.').map_or(doc.name.as_str(), |(a, _)| a).to_string();
let ext = s_fmt(f);
@@ -356,6 +572,39 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,
})
}
/// [`confirm`] for several layers: one destination prompt, then each layer exported with the
/// dialog's settings and named as Quick Export names a selection's files. The layers are captured
/// when asked, so changing the selection or document meanwhile can't change what is exported.
fn confirm_layers(app: &mut PhotocraftApp, f: &Map<String, Value>, ids: &[photocraft_doc::LayerId]) -> Result<Value, String> {
let st = app.session.active().ok_or("no document")?;
let docs: Vec<Document> =
ids.iter().map(|id| photocraft_engine::layer_menu_cmds::layer_document(&st.doc, *id).map_err(|e| e.to_string())).collect::<Result<_, _>>()?;
if docs.is_empty() {
return Err("no selected layers".into());
}
let stem = st.doc.name.rsplit_once('.').map_or(st.doc.name.as_str(), |(a, _)| a);
let suggested = format!("{}.{}", export_name(stem), s_fmt(f));
let (f, settings) = (f.clone(), settings(f));
app.pick_save(&suggested, move |app, path| {
let mut exported = Vec::new();
for (doc, path) in docs.iter().zip(batch_paths(&path, &docs)) {
let out = export_document(doc, &f, None)?;
let export = app.services.export.as_ref().ok_or("no exporter configured")?;
let (bytes, warnings) = export(&out, &path, &settings)?;
let write = app.services.write.as_mut().ok_or("no writer configured")?;
write(&path, &bytes)?;
let template = "Exported {path}";
let what = crate::i18n::fmt(tl!(template), &[("path", &crate::file_open::display_name(&path))]);
crate::notices::io_warnings(app, &what, &warnings);
exported.push(json!({"path": path, "bytes": bytes.len(), "warnings": warnings}));
}
let template = "Exported {n} files";
app.ui.status = crate::i18n::fmt(tl!(template), &[("n", &exported.len().to_string())]);
app.ui.status_error = false;
Ok(json!({"files": exported}))
})
}
/// File › Export › Quick Export as PNG: the format, quality, metadata, colour space and location
/// from File › Export › Export Preferences (engine `file.export.quickExport`). On the web (no
/// file system) it falls back to a PNG download through the export service.
@@ -393,8 +642,71 @@ fn quick_export(app: &mut PhotocraftApp, p: Value) -> Result<Value, String> {
#[cfg(test)]
mod tests {
#[test]
fn ico_export_is_available_and_rejects_oversize_output() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let mut f = Map::new();
f.insert("format".into(), json!("ico"));
f.insert("scale".into(), json!(100));
assert!(FORMATS.iter().any(|(ext, _)| *ext == "ico"));
assert!(export_document(&app.session.active().unwrap().doc, &f, None).err().is_some_and(|e| e.contains("256")));
f.insert("scale".into(), json!(50));
let resized = export_document(&app.session.active().unwrap().doc, &f, None).unwrap();
assert_eq!((resized.size.width, resized.size.height), (150, 100));
}
use super::*;
/// Export As reopens with the settings it was used with last (Preferences ▸ remembered
/// dialog settings), and a value no control accepts keeps its default.
#[test]
fn export_as_opens_with_the_settings_used_last() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 20, "height": 10})).unwrap();
app.session.prefs.edit(|p| {
p.dialogs.insert(
COMMAND.into(),
json!({"format": "jpg", "quality": 88, "scale": 37, "transparency": false, "metadata": "all", "tgaBits": "24", "lossless": true}),
);
});
let id = open(&mut app).unwrap();
let f = &app.ui.dialog_mut(id).unwrap().fields;
assert_eq!(f["format"], "jpg");
assert_eq!(f["quality"], json!(88.0));
assert_eq!(f["scale"], json!(37.0));
assert_eq!(f["transparency"], false);
assert_eq!(f["metadata"], "all");
assert_eq!(f["tgaBits"], "24");
app.session.prefs.edit(|p| {
p.dialogs.insert(COMMAND.into(), json!({"format": "nope", "scale": 0, "metadata": "sometimes"}));
});
let id = open(&mut app).unwrap();
let f = &app.ui.dialog_mut(id).unwrap().fields;
assert_eq!(f["format"], "png");
assert_eq!(f["scale"], 100);
assert_eq!(f["metadata"], "none");
}
/// Only the dialog's own settings are remembered: not the destination, the document size or
/// the layer the dialog was opened with.
#[test]
fn remembering_keeps_only_the_dialog_settings() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
let mut f = Map::new();
f.insert("format".into(), json!("webp"));
f.insert("scale".into(), json!(50));
f.insert("path".into(), json!("/tmp/x.webp"));
f.insert("__w".into(), json!(1200));
f.insert("__layer".into(), json!(3));
remember(&mut app, &f);
let saved = app.session.prefs().dialogs.get(COMMAND).cloned().unwrap();
assert_eq!(saved["format"], "webp");
assert_eq!(saved["scale"], 50);
assert!(saved.get("path").is_none() && saved.get("__w").is_none() && saved.get("__layer").is_none());
}
#[test]
fn export_document_scales_height_when_rounded_width_is_unchanged() {
use photocraft_doc::{Color, ColorMode, SampleType, Size};
@@ -487,6 +799,54 @@ mod tests {
assert_eq!(scaled_size(10.0, 300.0, 0.01), (1.0, 3.0));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn layered_preview_runs_outside_the_ui_frame() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 32, "height": 16})).unwrap();
for _ in 0..33 {
app.run("layer.new.layer", json!({})).unwrap();
}
let doc = app.session.active().unwrap().doc.clone();
assert!(background_preview_needed(&doc));
let fields = Map::from_iter([("format".into(), json!("png")), ("scale".into(), json!(100))]);
let ctx = egui::Context::default();
let key = egui::Id::new("layered-preview-test");
let mut result = None;
let mut output = ctx.run_ui(Default::default(), |ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
result = poll_or_start_preview(ui, key, "png100", doc.clone(), &fields);
});
});
output.textures_delta.clear();
assert!(result.is_none(), "the first UI frame must only start the worker");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
let mut output = ctx.run_ui(Default::default(), |ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
result = poll_or_start_preview(ui, key, "png100", doc.clone(), &fields);
});
});
output.textures_delta.clear();
if let Some(preview) = result {
let preview = preview.unwrap();
assert_eq!((preview.width, preview.height), (32, 16));
assert_eq!(preview.rgba.len(), 32 * 16 * 4);
assert!(preview.estimate.is_some_and(|bytes| bytes > 0));
break;
}
assert!(std::time::Instant::now() < deadline, "background preview did not complete");
std::thread::sleep(std::time::Duration::from_millis(10));
}
let tiff_fields = Map::from_iter([("format".into(), json!("tif")), ("scale".into(), json!(100))]);
let proxy = preview_proxy(&doc, &tiff_fields).unwrap();
let options = photocraft_io::ExportOptions { tiff_layers: true, xmp: photocraft_io::XmpEmbed::None, ..Default::default() };
let actual_bytes = photocraft_io::export(&proxy, "estimate.tif", &options).unwrap().bytes.len();
assert_eq!(estimate_native(&doc, &proxy, &tiff_fields), Some(scaled_estimate(actual_bytes, &doc, &proxy, &tiff_fields)));
}
#[test]
fn switching_export_formats_uses_independent_quality_preferences() {
let prefs = photocraft_engine::prefs::Export { jpeg_quality: 43, webp_quality: 72, webp_lossless: false, ..Default::default() };