diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index f0c1308a62..58b727b8bc 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -1065,6 +1065,11 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; let doc = d.doc.clone(); let quality = f64_param(p, "quality").or(Some(10.0)); + // Reverse Page Order (#13644): the default page order the other way round. + let reverse = match p.get("reversePageOrder") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "`reversePageOrder` must be true or false"))?, + }; let guard = ScratchGuard::new(&doc)?; let mut pages = Vec::new(); // Pages go bottom artboard of the Layers panel first, as in the reference application (#13643); @@ -1076,6 +1081,9 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result { if pages.is_empty() { return Err(bad(cmd, "no matching artboards")); } + if reverse { + pages.reverse(); + } guard.check()?; write_file(&path, &raster_pdf(&pages))?; Ok(json!({"path": path, "pages": pages.len()})) @@ -1148,7 +1156,7 @@ pub fn specs() -> Vec { "file.export.artboardsToPdf", "Artboards to PDF…", &["File", "Export"], - r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10} → {path, pages} (one raster page per board, bottom artboard of the Layers panel first)"##, + r##"{"path":str (.pdf),"artboards":[id]?,"quality":0..12=10,"reversePageOrder":bool=false (the default page order the other way round)} → {path, pages} (one raster page per board, bottom artboard of the Layers panel first)"##, export_artboards, artboards_to_pdf ), @@ -1189,5 +1197,8 @@ mod overlapping_areas_tests; #[path = "artboard_cmds/pdf_page_order_tests.rs"] mod pdf_page_order_tests; #[cfg(test)] +#[path = "artboard_cmds/pdf_reverse_page_order_tests.rs"] +mod pdf_reverse_page_order_tests; +#[cfg(test)] #[path = "artboard_cmds/tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs new file mode 100644 index 0000000000..b3009e1251 --- /dev/null +++ b/crates/engine/src/cmd/artboard_cmds/pdf_reverse_page_order_tests.rs @@ -0,0 +1,95 @@ +//! Artboards to PDF's Reverse Page Order (#13644), on the measured document: 800 x 400 with Red, +//! Blue and Empty Board, bottom to top. The boards have three different sizes, so each page's +//! MediaBox says which board it is. + +use super::*; + +/// The measured document, and the ids of Red, Blue and Empty Board (bottom to top). +fn session() -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 400, "depth": 8, "resolution": 72})).unwrap(); + let mut board = |rect: [i64; 4], name: &str| { + let r = s.execute("layer.new.artboard", json!({"rect": rect, "name": name})).unwrap(); + r["layer"].as_u64().unwrap() + }; + let ids = [board([0, 0, 200, 150], "Red Board"), board([120, 30, 200, 200], "Blue Board"), board([600, 0, 100, 100], "Empty Board")]; + (s, ids) +} + +/// Runs the export with `params` (plus a path in a fresh temporary folder) and returns its result +/// and the bytes written (empty when nothing was). +fn export(s: &mut Session, params: Value) -> (Result, Vec) { + let dir = tempfile::tempdir().unwrap(); + let path = join(&dir.path().to_string_lossy(), "boards.pdf"); + let mut params = params; + params["path"] = json!(path); + let r = s.execute("file.export.artboardsToPdf", params); + let bytes = std::fs::read(&path).unwrap_or_default(); + (r, bytes) +} + +/// Each page's size in points, in page order. +fn page_sizes(s: &mut Session, params: Value) -> Vec<(u32, u32)> { + let (r, bytes) = export(s, params); + r.unwrap(); + let text = String::from_utf8_lossy(&bytes).into_owned(); + text.split("/MediaBox [0 0 ") + .skip(1) + .map(|rest| { + let mut n = rest.split([' ', ']']).map(|v| v.parse::().unwrap().round() as u32); + (n.next().unwrap(), n.next().unwrap()) + }) + .collect() +} + +fn reversed(mut v: Vec<(u32, u32)>) -> Vec<(u32, u32)> { + v.reverse(); + v +} + +#[test] +fn reverse_page_order_turns_the_default_order_round() { + let (mut s, _) = session(); + let default = page_sizes(&mut s, json!({})); + assert_eq!(default.len(), 3); + let mut sorted = default.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [(100, 100), (200, 150), (200, 200)], "one page per board"); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": true})), reversed(default)); +} + +#[test] +fn false_or_no_param_keeps_the_default_order() { + let (mut s, _) = session(); + let default = page_sizes(&mut s, json!({})); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": false})), default); + assert_eq!(page_sizes(&mut s, json!({"reversePageOrder": null})), default); +} + +#[test] +fn chosen_artboards_come_in_the_reversed_order_too() { + let (mut s, [red, blue, _]) = session(); + let chosen = json!([red, blue]); + let default = page_sizes(&mut s, json!({"artboards": chosen})); + let mut sorted = default.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [(200, 150), (200, 200)], "only Red and Blue Board"); + assert_eq!(page_sizes(&mut s, json!({"artboards": chosen, "reversePageOrder": true})), reversed(default)); +} + +#[test] +fn a_non_boolean_value_is_an_error_not_a_panic() { + let (mut s, _) = session(); + for v in [json!("yes"), json!(1), json!([true]), json!({"on": true})] { + let (r, bytes) = export(&mut s, json!({"reversePageOrder": v})); + let e = r.unwrap_err().to_string(); + assert!(e.contains("reversePageOrder"), "{e}"); + assert!(bytes.is_empty(), "nothing is written for {v}"); + } +} + +#[test] +fn the_params_doc_names_the_option() { + let spec = specs().into_iter().find(|c| c.id == "file.export.artboardsToPdf").unwrap(); + assert!(spec.params.contains(r#""reversePageOrder":bool=false"#), "{}", spec.params); +} diff --git a/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs new file mode 100644 index 0000000000..50c0e480fe --- /dev/null +++ b/crates/ui-egui/src/artboards_to_pdf_reverse_tests.rs @@ -0,0 +1,119 @@ +//! #13644: the Artboards to PDF dialog has a Reverse Page Order checkbox. It is unticked on first +//! open, reaches the command, and reopens as the last successful run left it. +use crate::PhotocraftApp; +use craft::ui::dialog::DialogId; +use egui::accesskit::{Role, Toggled}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +const COMMAND: &str = "file.export.artboardsToPdf"; + +type H = Harness<'static, Box>; + +/// A document with two artboards of different sizes, so a page's MediaBox says which board it is. +fn harness() -> H { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [0, 0, 200, 150], "name": "Low"})).unwrap(); + app.run("layer.new.artboard", json!({"rect": [250, 0, 100, 100], "name": "High"})).unwrap(); + app.sync_views(); + let h = Harness::builder() + .with_size(egui::vec2(1440.0, 900.0)) + .with_max_steps(64) + .with_context(app.ctx().clone()) + .build_ui_state(|ui, app: &mut Box| crate::dialogs::run(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h +} + +/// Opens the dialog from its menu entry with File set to `path`. +fn open(h: &mut H, path: &str) -> DialogId { + let ctx = h.ctx.clone(); + let reply = crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap(); + let want = reply["dialog"].as_str().unwrap().to_owned(); + let dialog = h.state().framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|d| d.value().to_string() == want).unwrap(); + h.run_steps(4); + h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, "path", json!(path)).unwrap(); + // Every board, not only the selected one: Export Selected Artboards opens ticked while a board is selected (#13647). + h.state_mut().framework.dialogs.set_json_field(&ctx, dialog, "artboards", serde_json::Value::Null).unwrap(); + h.run_steps(4); + dialog +} + +fn confirm(h: &mut H, dialog: DialogId) -> Result<(), String> { + let ctx = h.ctx.clone(); + let r = crate::dialogs::confirm(h.state_mut(), &ctx, dialog); + h.run_steps(4); + r +} + +fn ticked(h: &H) -> bool { + h.get_by_role_and_label(Role::CheckBox, "Reverse Page Order").accesskit_node().toggled() == Some(Toggled::True) +} + +fn tick(h: &mut H) { + h.get_by_role_and_label(Role::CheckBox, "Reverse Page Order").click(); + h.run_steps(2); +} + +/// Each page's width in points, in page order. +fn page_widths(path: &str) -> Vec { + let text = String::from_utf8_lossy(&std::fs::read(path).unwrap()).into_owned(); + text.split("/MediaBox [0 0 ").skip(1).map(|rest| rest.split(' ').next().unwrap().parse::().unwrap().round() as u32).collect() +} + +#[test] +fn the_checkbox_starts_unticked_and_reverses_the_pages() { + let t = tempfile::tempdir().unwrap(); + let path = t.path().join("plain.pdf").to_string_lossy().into_owned(); + let mut h = harness(); + let d = open(&mut h, &path); + assert!(!ticked(&h), "unticked on first open"); + confirm(&mut h, d).unwrap(); + let plain = page_widths(&path); + assert_eq!(plain.len(), 2); + + let path = t.path().join("reversed.pdf").to_string_lossy().into_owned(); + let d = open(&mut h, &path); + tick(&mut h); + assert!(ticked(&h)); + confirm(&mut h, d).unwrap(); + let mut want = plain; + want.reverse(); + assert_eq!(page_widths(&path), want); +} + +#[test] +fn a_successful_run_is_remembered_a_failed_one_is_not() { + let t = tempfile::tempdir().unwrap(); + let mut h = harness(); + let path = t.path().join("out.pdf").to_string_lossy().into_owned(); + let d = open(&mut h, &path); + tick(&mut h); + confirm(&mut h, d).unwrap(); + + // Reopens ticked; untick it and fail the run (the destination is a file, not a folder). + let blocked = t.path().join("file"); + std::fs::write(&blocked, b"x").unwrap(); + let bad = blocked.join("out.pdf").to_string_lossy().into_owned(); + let d = open(&mut h, &bad); + assert!(ticked(&h), "remembered after a successful run"); + tick(&mut h); + assert!(!ticked(&h)); + assert!(!h.state().ui.status_error, "the first run succeeded: {}", h.state().ui.status); + let r = confirm(&mut h, d); + // The run fails, so it must not be what the next open remembers. + assert!(r.is_err() || h.state().ui.status_error, "the blocked run fails: {r:?}, status {}", h.state().ui.status); + assert!(!std::path::Path::new(&bad).exists(), "the blocked run writes nothing"); + if h.state().framework.dialogs.get_dyn(d).is_some() { + let ctx = h.ctx.clone(); + crate::dialogs::cancel(h.state_mut(), &ctx, d).unwrap(); + h.run_steps(4); + } + + let d = open(&mut h, &path); + assert!(ticked(&h), "a failed run leaves the remembered value alone"); + let ctx = h.ctx.clone(); + crate::dialogs::cancel(h.state_mut(), &ctx, d).unwrap(); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 801767535b..ec54e47795 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1041,6 +1041,8 @@ mod artboards_overlap_dialog_tests; #[cfg(test)] mod artboards_to_files_types_tests; #[cfg(test)] +mod artboards_to_pdf_reverse_tests; +#[cfg(test)] mod browse_field_tests; #[cfg(test)] mod export_quality_tests; diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index a9cf26672e..cf8052c54a 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -326,6 +326,8 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec {