mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge pr/1394
This commit is contained in:
2 files changed
+211
-7
No files matched your search
@@ -74,16 +74,19 @@ fn n(f: &Map<String, Value>, k: &str, d: f64) -> f64 {
|
||||
fn export_document(doc: &Document, f: &Map<String, Value>, max_side: Option<u32>) -> Result<Document, String> {
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
s.add_document(doc.clone(), None);
|
||||
let scale = n(f, "scale", 100.0) / 100.0;
|
||||
let mut w = (doc.size.width as f64 * scale).round().max(1.0);
|
||||
let mut scale = n(f, "scale", 100.0) / 100.0;
|
||||
if let Some(m) = max_side {
|
||||
let long = doc.size.width.max(doc.size.height) as f64 * scale;
|
||||
if long > m as f64 {
|
||||
w = (w * m as f64 / long).round().max(1.0);
|
||||
scale *= m as f64 / long;
|
||||
}
|
||||
}
|
||||
if (w - doc.size.width as f64).abs() >= 1.0 {
|
||||
s.execute("image.imageSize", json!({"width": w, "resample": if max_side.is_some() { "bilinear" } else { "bicubic" }})).map_err(|e| e.to_string())?;
|
||||
// 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 (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())?;
|
||||
}
|
||||
let fmt = s_fmt(f);
|
||||
if !f.get("transparency").and_then(Value::as_bool).unwrap_or(true) || fmt == "jpg" {
|
||||
@@ -92,6 +95,12 @@ fn export_document(doc: &Document, f: &Map<String, Value>, max_side: Option<u32>
|
||||
s.active().map(|d| (*d.doc).clone()).ok_or_else(|| "export failed".into())
|
||||
}
|
||||
|
||||
/// The exported pixel size: each side scaled and rounded on its own, never below 1 px. The
|
||||
/// dialog's size label and `export_document` share it so the label names the file's real size.
|
||||
fn scaled_size(w: f64, h: f64, scale: f64) -> (f64, f64) {
|
||||
((w * scale).round().max(1.0), (h * scale).round().max(1.0))
|
||||
}
|
||||
|
||||
/// Export As already supports lossy WebP; reuse the Quick Export defaults when
|
||||
/// choosing that format so both flows expose the same quality and lossless options.
|
||||
fn set_format_defaults(f: &mut Map<String, Value>, fmt: &str, prefs: &photocraft_engine::prefs::Export) {
|
||||
@@ -188,8 +197,8 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
|
||||
crate::widgets::value_field(ui, &mut sc, 1.0..=1000.0, "%", 70.0);
|
||||
});
|
||||
f.insert("scale".into(), json!(sc.round()));
|
||||
let (bw, bh) = (n(f, "__w", f64::from(doc.size.width)) as f32, n(f, "__h", f64::from(doc.size.height)) as f32);
|
||||
let (w, h) = ((bw * sc / 100.0).round(), (bh * sc / 100.0).round());
|
||||
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));
|
||||
});
|
||||
ui.add_space(12.0);
|
||||
@@ -283,6 +292,51 @@ pub fn quick_export_png(app: &mut PhotocraftApp) -> Result<Value, String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn export_document_scales_height_when_rounded_width_is_unchanged() {
|
||||
use photocraft_doc::{Color, ColorMode, SampleType, Size};
|
||||
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
for (width, height, scale, expected) in [
|
||||
(1, 100, 50, (1, 50)),
|
||||
(1, 200, 50, (1, 100)),
|
||||
(10, 100, 99, (10, 99)),
|
||||
(10, 100, 101, (10, 101)),
|
||||
(400, 300, 50, (200, 150)),
|
||||
(400, 300, 100, (400, 300)),
|
||||
] {
|
||||
let doc = Document::with_background("x", Size::new(width, height), ColorMode::Rgb, depth, Color::WHITE);
|
||||
let before = doc.clone();
|
||||
let mut f = Map::new();
|
||||
f.insert("format".into(), json!("png"));
|
||||
f.insert("scale".into(), json!(scale));
|
||||
let out = export_document(&doc, &f, None).unwrap();
|
||||
assert_eq!((out.size.width, out.size.height), expected, "{width} × {height} at {scale}%, {depth:?}");
|
||||
assert_eq!(out.depth, depth, "export preserves the document's depth");
|
||||
assert_eq!(doc, before, "export leaves the source document unchanged");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_document_proxy_limits_both_dimensions_before_rounding() {
|
||||
use photocraft_doc::{Color, ColorMode, SampleType, Size};
|
||||
|
||||
for (width, height, scale, max_side, expected) in
|
||||
[(1, 1000, 100, 360, (1, 360)), (1, 1000, 50, 360, (1, 360)), (1, 1000, 25, 360, (1, 250)), (13, 20, 50, 8, (5, 8)), (20, 13, 50, 8, (8, 5))]
|
||||
{
|
||||
let doc = Document::with_background("x", Size::new(width, height), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
let before = doc.clone();
|
||||
let mut f = Map::new();
|
||||
f.insert("format".into(), json!("png"));
|
||||
f.insert("scale".into(), json!(scale));
|
||||
let out = export_document(&doc, &f, Some(max_side)).unwrap();
|
||||
assert_eq!((out.size.width, out.size.height), expected, "{width} × {height} at {scale}%, proxy limit {max_side}");
|
||||
assert!(out.size.width.max(out.size.height) <= max_side, "proxy respects its longest-side limit");
|
||||
assert_eq!(doc, before, "preview leaves the source document unchanged");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_document_scales_and_flattens() {
|
||||
let doc = Document::with_background(
|
||||
@@ -303,6 +357,33 @@ mod tests {
|
||||
assert_eq!(settings(&f).jpeg_quality, Some(85));
|
||||
}
|
||||
|
||||
/// #1353: a scale that changes only the height (the width rounds back to the original)
|
||||
/// used to be skipped, so the exported file kept the original size while the dialog
|
||||
/// labelled it as scaled.
|
||||
#[test]
|
||||
fn export_document_scales_when_only_the_height_changes() {
|
||||
let mut f = Map::new();
|
||||
f.insert("format".into(), json!("png"));
|
||||
f.insert("scale".into(), json!(50));
|
||||
for (src_h, want_h) in [(100u32, 50u32), (200, 100)] {
|
||||
let doc = Document::with_background(
|
||||
"x",
|
||||
photocraft_doc::Size::new(1, src_h),
|
||||
photocraft_doc::ColorMode::Rgb,
|
||||
photocraft_doc::SampleType::U8,
|
||||
photocraft_doc::Color::WHITE,
|
||||
);
|
||||
let out = export_document(&doc, &f, None).unwrap();
|
||||
assert_eq!((out.size.width, out.size.height), (1, want_h), "1 × {src_h} at 50%");
|
||||
// The preview proxy takes the same path.
|
||||
let proxy = export_document(&doc, &f, Some(40)).unwrap();
|
||||
assert_eq!((proxy.size.width, proxy.size.height), (1, 40), "proxy of 1 × {src_h}");
|
||||
}
|
||||
// The label and the export agree, and neither side drops below 1 px.
|
||||
assert_eq!(scaled_size(1.0, 100.0, 0.5), (1.0, 50.0));
|
||||
assert_eq!(scaled_size(10.0, 300.0, 0.01), (1.0, 3.0));
|
||||
}
|
||||
|
||||
#[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() };
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! #1353: Export As must scale the height even when the rounded width stays unchanged.
|
||||
//! Drive the real Scale field and Export button, then decode the PNG the writer received.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use photocraft_ui_egui::{PhotocraftApp, Services, menus};
|
||||
use serde_json::json;
|
||||
|
||||
type Harness = egui_kittest::Harness<'static, PhotocraftApp>;
|
||||
type Writes = Rc<RefCell<Vec<(String, Vec<u8>)>>>;
|
||||
|
||||
fn harness() -> Option<(Harness, Writes)> {
|
||||
let built = std::panic::catch_unwind(|| {
|
||||
let writes = Writes::default();
|
||||
let captured = writes.clone();
|
||||
let h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 760.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(
|
||||
move |cc| {
|
||||
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
|
||||
let services = Services {
|
||||
pick_save: Some(Box::new(|suggested| Some(suggested.to_string()))),
|
||||
export: Some(Box::new(|doc, path, settings| {
|
||||
let opts = photocraft_io::ExportOptions {
|
||||
xmp: if settings.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None },
|
||||
..Default::default()
|
||||
};
|
||||
photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string())
|
||||
})),
|
||||
write: Some(Box::new(move |path, bytes| {
|
||||
captured.borrow_mut().push((path.to_string(), bytes.to_vec()));
|
||||
Ok(())
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
|
||||
app.session.prefs.edit(|p| p.interface.language = "en".into());
|
||||
if let Some(rs) = cc.wgpu_render_state.as_ref() {
|
||||
app.set_wgpu(rs.clone());
|
||||
}
|
||||
app
|
||||
},
|
||||
);
|
||||
(h, writes)
|
||||
});
|
||||
match built {
|
||||
Ok(h) => Some(h),
|
||||
Err(_) => {
|
||||
eprintln!("skipping: no GPU adapter");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn evidence(h: &mut Harness, depth: u8, stage: &str) {
|
||||
if let Some(dir) = std::env::var_os("PHOTOCRAFT_EXPORT_EVIDENCE_DIR") {
|
||||
std::fs::create_dir_all(&dir).expect("evidence directory");
|
||||
h.render().expect("render UI").save(std::path::Path::new(&dir).join(format!("{stage}-{depth}bit.png"))).expect("save UI evidence");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_as_scales_a_narrow_image_without_editing_the_source() {
|
||||
let Some((mut h, writes)) = harness() else { return };
|
||||
h.run_steps(4);
|
||||
for depth in [8, 16, 32] {
|
||||
writes.borrow_mut().clear();
|
||||
{
|
||||
let app = h.state_mut();
|
||||
while app.session.active().is_some() {
|
||||
app.run("file.close", json!({"discard": true})).expect("close");
|
||||
}
|
||||
app.run("file.new", json!({"width": 1, "height": 100, "depth": depth, "background": "white"})).expect("new narrow document");
|
||||
app.sync_views();
|
||||
}
|
||||
let st = h.state().session.active().expect("document");
|
||||
let source = st.doc.clone();
|
||||
let history = st.history.entries();
|
||||
let revision = st.revision;
|
||||
|
||||
let ctx = h.ctx.clone();
|
||||
menus::invoke(h.state_mut(), &ctx, "file.export.exportAs", json!({})).expect("open Export As");
|
||||
h.run_steps(6);
|
||||
let label = h.get_by_label("Scale").rect();
|
||||
let field = h
|
||||
.query_all_by_role(egui::accesskit::Role::SpinButton)
|
||||
.find(|n| {
|
||||
let r = n.rect();
|
||||
r.left() >= label.right() && r.left() < label.right() + 100.0 && (r.center().y - label.center().y).abs() < 3.0
|
||||
})
|
||||
.expect("Scale numeric field");
|
||||
field.click();
|
||||
h.run_steps(2);
|
||||
// Clicking a numeric field selects its current value; type through egui's text input.
|
||||
h.event(egui::Event::Text("50".into()));
|
||||
h.run_steps(3);
|
||||
// Click away to commit the field without Enter confirming the dialog.
|
||||
h.get_by_label("Image Size").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.query_by_label("1 × 50 px").is_some(), "{depth}-bit: dialog shows the requested output size");
|
||||
evidence(&mut h, depth, "dialog");
|
||||
|
||||
h.get_by_label("Export").click();
|
||||
h.run_steps(6);
|
||||
evidence(&mut h, depth, "result");
|
||||
let written = writes.borrow();
|
||||
assert_eq!(written.len(), 1, "{depth}-bit: Export writes one file");
|
||||
let (path, bytes) = &written[0];
|
||||
assert!(path.ends_with(".png"), "PNG export path: {path}");
|
||||
if let Some(dir) = std::env::var_os("PHOTOCRAFT_EXPORT_EVIDENCE_DIR") {
|
||||
std::fs::write(std::path::Path::new(&dir).join(format!("exported-{depth}bit.png")), bytes).expect("save exported PNG evidence");
|
||||
}
|
||||
let png = photocraft_codecs::decode_as(photocraft_codecs::Format::Png, bytes).expect("decode the written PNG");
|
||||
assert_eq!(png.dimensions(), (1, 50), "{depth}-bit: written dimensions match the dialog");
|
||||
|
||||
let st = h.state().session.active().expect("source remains open");
|
||||
assert!(Arc::ptr_eq(&st.doc, &source), "{depth}-bit: source document is unchanged");
|
||||
assert_eq!((st.doc.size.width, st.doc.size.height), (1, 100));
|
||||
assert_eq!(st.history.entries(), history, "export must not add source history");
|
||||
assert_eq!(st.revision, revision, "export must not change source revision");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user