PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Artboard placement, edits and export reject coordinates past the 32-bit range instead of overflowing (#931) (#1032)
yangba4dc112bb8c
diff --git a/crates/engine/src/artboard_cmds.rs b/crates/engine/src/artboard_cmds.rsindex 93a1ad5bf..13fdd72ae 100644--- a/crates/engine/src/artboard_cmds.rs+++ b/crates/engine/src/artboard_cmds.rs@@ -106,26 +106,43 @@ fn background_param(p: &Value, cmd: &str) -> Result<Option<ArtboardBackground>>})}-/// `rect` as `[x, y, w, h]` or `x`/`y`/`width`/`height` keys over `base`.-fn rect_param(p: &Value, base: Rect, cmd: &str) -> Result<Rect> {- if let Some(Value::Array(a)) = p.get("rect") {- let v: Vec<i32> = a.iter().filter_map(|x| x.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i32)).collect();- if v.len() != 4 || v[2] <= 0 || v[3] <= 0 {- return Err(bad(cmd, "\"rect\" must be [x, y, width, height] with a positive size"));- }- return Ok(Rect::from_xywh(v[0], v[1], v[2] as u32, v[3] as u32));- }- let x = int_i32(cmd, p, "x")?.unwrap_or(base.x0);- let y = int_i32(cmd, p, "y")?.unwrap_or(base.y0);- let w = int(p, "width").unwrap_or(i64::from(base.width()));- let h = int(p, "height").unwrap_or(i64::from(base.height()));+/// A board rect from `x, y, width, height`, or a bad-params error naming them when an edge falls+/// outside the 32-bit coordinate range. `Rect::from_xywh` would clamp the far edge to `i32::MAX`+/// (silently shrinking the board) and wrap a width past `i32::MAX` negative (#931).+fn board_rect(cmd: &str, [x, y, w, h]: [i64; 4]) -> Result<Rect> {if w <= 0 || h <= 0 {- return Err(bad(cmd, "the artboard size must be positive"));+ return Err(bad(cmd, format!("the artboard size must be positive (width = {w}, height = {h})")));+ }+ let span = |a: i64, len: i64| Some((i32::try_from(a).ok()?, i32::try_from(a.checked_add(len)?).ok()?));+ match (span(x, w), span(y, h)) {+ (Some((x0, x1)), Some((y0, y1))) => Ok(Rect::new(x0, y0, x1, y1)),+ _ => Err(bad(+ cmd,+ format!("the artboard [x, y, width, height] = [{x}, {y}, {w}, {h}] reaches outside the 32-bit coordinate range ({}..={})", i32::MIN, i32::MAX),+ )),}- if w > i32::MAX as i64 || h > i32::MAX as i64 {- return Err(bad(cmd, "the artboard size is too large for a 32-bit canvas"));+}++/// `rect` as `[x, y, w, h]` or `x`/`y`/`width`/`height` keys over `base` (`[x, y, w, h]`, wide so+/// a default position past the edge reaches [`board_rect`] instead of overflowing).+fn rect_param(p: &Value, base: [i64; 4], cmd: &str) -> Result<Rect> {+ if let Some(Value::Array(a)) = p.get("rect") {+ let v: Vec<i64> = a.iter().filter_map(|x| x.as_i64().or_else(|| x.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64))).collect();+ let Ok(v) = <[i64; 4]>::try_from(v) else {+ return Err(bad(cmd, "\"rect\" must be [x, y, width, height] with a positive size"));+ };+ return board_rect(cmd, v);}- Ok(Rect::from_xywh(x, y, w as u32, h as u32))+ let x = int_i32(cmd, p, "x")?.map_or(base[0], i64::from);+ let y = int_i32(cmd, p, "y")?.map_or(base[1], i64::from);+ let w = int(p, "width").unwrap_or(base[2]);+ let h = int(p, "height").unwrap_or(base[3]);+ board_rect(cmd, [x, y, w, h])+}++/// `r` as `[x, y, w, h]` for [`rect_param`].+fn xywh(r: Rect) -> [i64; 4] {+ [i64::from(r.x0), i64::from(r.y0), i64::from(r.width()), i64::from(r.height())]}/// Grow the canvas (right/bottom) so every artboard fits.@@ -164,10 +181,17 @@ fn new_artboard(s: &mut Session, p: &Value) -> Result<Value> {// Default placement: right of the rightmost artboard, else the canvas origin.let right = d.doc.artboards().iter().map(|b| b.2.rect.x1).max();let top = d.doc.artboards().iter().map(|b| b.2.rect.y0).min().unwrap_or(0);+ // In i64: `x1 + GAP` passes i32::MAX for a board at the far right edge (#931).let base = match right {- Some(x) => Rect::from_xywh(x + GAP, top, pw, ph),- None => Rect::from_xywh(0, 0, pw, ph),+ Some(x) => [i64::from(x) + i64::from(GAP), i64::from(top), i64::from(pw), i64::from(ph)],+ None => [0, 0, i64::from(pw), i64::from(ph)],};+ // With no room right of the rightmost board, ask for a position rather than pick another+ // spot that may overlap a board; an explicit `x` (or `rect`) still works.+ let explicit_x = p.get("rect").is_some() || p.get("x").is_some_and(|v| !v.is_null());+ if let Some(edge) = right.filter(|_| !explicit_x && base[0] > i64::from(i32::MAX)) {+ return Err(bad(cmd, format!("no room for a new artboard right of the rightmost one (its right edge is x = {edge}); pass \"x\" to place it")));+ }// A preset decides the size (dialogs send the canvas size alongside it).let rect = if preset.is_empty() || p.get("rect").is_some() {rect_param(p, base, cmd)?@@ -246,17 +270,30 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {};let old = d.doc.layer(id).and_then(Layer::artboard).cloned().ok_or_else(|| bad(cmd, "the layer is not an artboard"))?;let preset = p.get("preset").and_then(Value::as_str).map(str::to_string);- let mut base = old.rect;+ let mut base = xywh(old.rect);if let Some(name) = preset.as_deref().filter(|n| !n.is_empty()) {let (w, h) = preset_size(name).ok_or_else(|| bad(cmd, format!("unknown preset `{name}`")))?;- base = Rect::from_xywh(base.x0, base.y0, w, h);+ (base[2], base[3]) = (i64::from(w), i64::from(h));}let rect = rect_param(p, base, cmd)?;let background = background_param(p, cmd)?;let name = p.get("name").and_then(Value::as_str).map(str::to_string);let move_contents = p.get("moveContents").and_then(Value::as_bool).unwrap_or(true);+ // The offset between two in-range edges can need 33 bits (#931); layers move by i32 only.+ let (dx, dy) = (i64::from(rect.x0) - i64::from(old.rect.x0), i64::from(rect.y0) - i64::from(old.rect.y0));+ let (dx, dy) = match (i32::try_from(dx), i32::try_from(dy)) {+ (Ok(dx), Ok(dy)) => (dx, dy),+ _ if !move_contents => (0, 0),+ _ => {+ return Err(bad(+ cmd,+ format!(+ "moving the artboard with its contents by ({dx}, {dy}) is outside the 32-bit range; move it in smaller steps or pass \"moveContents\": false"+ ),+ ));+ }+ };s.edit("Edit Artboard", |doc, _| {- let (dx, dy) = (rect.x0 - old.rect.x0, rect.y0 - old.rect.y0);if move_contents && (dx, dy) != (0, 0) {let snapshot = doc.clone();let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;@@ -302,14 +339,20 @@ fn clear_artboard_guides(s: &mut Session) -> Result<Value> {Ok(json!({"cleared": n}))}-/// One artboard as its own document: the board's size, its group moved to the origin.-pub fn artboard_document(doc: &Document, id: LayerId) -> Option<Document> {- let l = doc.layer(id)?;- let r = l.artboard()?.rect;+/// One artboard as its own document: the board's size, its group moved to the origin. `None`+/// when `id` is not an artboard; an error when the board is too far from the origin to move.+pub fn artboard_document(doc: &Document, id: LayerId) -> Result<Option<Document>> {+ let Some(l) = doc.layer(id) else { return Ok(None) };+ let Some(r) = l.artboard().map(|a| a.rect) else { return Ok(None) };+ // A board starting at i32::MIN needs an offset of 2^31 to reach the origin, one past+ // i32::MAX (#931).+ let (Some(dx), Some(dy)) = (r.x0.checked_neg(), r.y0.checked_neg()) else {+ return Err(EngineError::Other(format!("artboard `{}` at ({}, {}) is too far from the origin to export", l.name, r.x0, r.y0)));+ };let mut group = l.clone();group.visible = true;- crate::commands::translate_layer(doc, &mut group, -r.x0, -r.y0);- crate::vector_cmds::translate_vectors(doc, &mut group, f64::from(-r.x0), f64::from(-r.y0));+ crate::commands::translate_layer(doc, &mut group, dx, dy);+ crate::vector_cmds::translate_vectors(doc, &mut group, f64::from(dx), f64::from(dy));let mut one = doc.clone();one.name = l.name.clone();one.size = Size::new(r.width(), r.height());@@ -323,7 +366,13 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Option<Document> {let shift = |v: &[f32], o: i32, len: u32| v.iter().map(|g| g - o as f32).filter(|g| *g > 0.0 && *g < len as f32).collect::<Vec<_>>();one.guides.vertical = shift(&doc.guides.vertical, r.x0, r.width());one.guides.horizontal = shift(&doc.guides.horizontal, r.y0, r.height());- Some(one)+ Ok(Some(one))+}++/// [`artboard_document`] for each chosen board, all built before any file is written so a+/// board that can't be exported fails the export without leaving a partial set behind.+fn chosen_documents(doc: &Document, p: &Value) -> Result<Vec<Document>> {+ chosen_artboards(doc, p).into_iter().filter_map(|id| artboard_document(doc, id).transpose()).collect()}/// The artboards an export covers: `"artboards": [ids]`, else all, top of the Layers panel first.@@ -347,8 +396,7 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result<Value> {let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name));let doc = d.doc.clone();let mut files = Vec::new();- for id in chosen_artboards(&doc, p) {- let Some(one) = artboard_document(&doc, id) else { continue };+ for one in chosen_documents(&doc, p)? {let name = if prefix.is_empty() { sanitize(&one.name) } else { format!("{}_{}", sanitize(&prefix), sanitize(&one.name)) };let path = join(&dir, &format!("{name}.{format}"));save_doc(&one, &path, SaveOpts::from_params(p))?;@@ -414,8 +462,7 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result<Value> {let doc = d.doc.clone();let quality = f64_param(p, "quality").or(Some(10.0));let mut pages = Vec::new();- for id in chosen_artboards(&doc, p) {- let Some(one) = artboard_document(&doc, id) else { continue };+ for one in chosen_documents(&doc, p)? {let buf = photocraft_compose::flatten(&one).over_background([1.0, 1.0, 1.0]);let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true);let mut flat = Document::new(&one.name, one.size, ColorMode::Rgb, SampleType::U8);diff --git a/crates/engine/src/artboard_cmds/tests.rs b/crates/engine/src/artboard_cmds/tests.rsindex 93ac762b5..3715bc4b6 100644--- a/crates/engine/src/artboard_cmds/tests.rs+++ b/crates/engine/src/artboard_cmds/tests.rs@@ -168,3 +168,140 @@ fn disabled_without_artboards() {let _ = s.execute("layer.new.artboard", json!({}));assert!(!s.is_enabled("layer.new.artboardFromLayers"));}++/// Runs `cmd` and asserts it fails with a bad-params error that leaves the document, its+/// revision, its active layer and its history exactly as they were (#931).+fn assert_rejected(s: &mut Session, cmd: &str, p: Value) -> String {+ let d = s.active().unwrap();+ let (before, rev, active, past) = (d.doc.clone(), d.revision, d.active_layer, d.history.past_len());+ let err = s.execute(cmd, p.clone()).expect_err(&format!("{cmd} {p} should fail"));+ assert!(matches!(err, EngineError::BadParams { .. }), "{cmd} {p}: {err}");+ let d = s.active().unwrap();+ assert!(d.doc == before, "{cmd} {p} changed the document");+ assert_eq!(d.revision, rev, "{cmd} {p}");+ assert_eq!(d.active_layer, active, "{cmd} {p}");+ assert_eq!(d.history.past_len(), past, "{cmd} {p} recorded a history step");+ err.to_string()+}++fn board_rect(s: &Session, id: u64) -> Rect {+ doc(s).layer(LayerId(id)).unwrap().artboard().unwrap().rect+}++#[test]+fn new_artboard_rejects_coordinates_past_the_32_bit_range() {+ let mut s = session(8);+ // A board flush with the far right edge: x1 = i32::MAX.+ let r = s.execute("layer.new.artboard", json!({"x": i32::MAX - 50, "y": 0, "width": 50, "height": 50})).unwrap();+ assert_eq!(r["rect"], json!([i32::MAX - 50, 0, 50, 50]));+ // Default placement right of it has no room: an error naming the edge, not a wrapped x.+ let msg = assert_rejected(&mut s, "layer.new.artboard", json!({}));+ assert!(msg.contains(&i32::MAX.to_string()), "{msg}");+ assert_rejected(&mut s, "layer.new.artboard", json!({"preset": "iPhone 14"}));+ // An explicit position still works beside it (the canvas grew to its 300000 px cap).+ let r = s.execute("layer.new.artboard", json!({"x": 0})).unwrap();+ assert_eq!(r["rect"], json!([0, 0, 300_000, 80]));+ let r = s.execute("layer.new.artboard", json!({"preset": "A4", "x": 0, "y": 100})).unwrap();+ assert_eq!(r["rect"], json!([0, 100, 595, 842]));+ assert_eq!(doc(&s).artboards().len(), 3);++ // Default placement whose x fits but whose canvas-sized width runs past the edge.+ let mut s = session(8);+ s.execute("layer.new.artboard", json!({"x": i32::MAX - 250, "width": 50, "height": 50})).unwrap();+ assert_rejected(&mut s, "layer.new.artboard", json!({}));++ // Explicit rects that would end past i32::MAX (or start outside it) are rejected, not clamped.+ let mut s = session(8);+ for p in [+ json!({"x": i32::MAX, "width": 50, "height": 50}),+ json!({"x": i32::MAX - 10, "width": 50, "height": 50}),+ json!({"y": i32::MAX - 10, "width": 50, "height": 50}),+ json!({"rect": [i32::MAX - 10, 0, 50, 50]}),+ json!({"rect": [0, i32::MAX, 50, 50]}),+ json!({"rect": [3e9, 0, 50, 50]}),+ json!({"rect": [-3e9, 0, 50, 50]}),+ json!({"rect": [0, 0, 3e9, 50]}),+ json!({"x": 0, "width": 3_000_000_000_i64, "height": 50}),+ ] {+ assert_rejected(&mut s, "layer.new.artboard", p);+ }+ // Representable extremes are fine: flush with either edge.+ let r = s.execute("layer.new.artboard", json!({"x": i32::MIN, "y": i32::MIN, "width": 50, "height": 50})).unwrap();+ assert_eq!(r["rect"], json!([i32::MIN, i32::MIN, 50, 50]));+ let r = s.execute("layer.new.artboard", json!({"rect": [i32::MAX - 50, i32::MAX - 50, 50, 50]})).unwrap();+ assert_eq!(r["rect"], json!([i32::MAX - 50, i32::MAX - 50, 50, 50]));+}++#[test]+fn edit_artboard_rejects_moves_and_sizes_past_the_32_bit_range() {+ let mut s = session(8);+ let r = s.execute("layer.new.artboard", json!({"x": i32::MIN, "y": i32::MIN, "width": 50, "height": 50})).unwrap();+ let id = r["layer"].as_u64().unwrap();+ // Moving the board with its contents from one edge to the other needs an offset of about+ // 2^32, which no layer can be translated by.+ let msg = assert_rejected(&mut s, "layer.artboard.set", json!({"x": i32::MAX - 50}));+ assert!(msg.contains("4294967245"), "{msg}");+ assert_rejected(&mut s, "layer.artboard.set", json!({"y": i32::MAX - 50}));+ // A rect that would end past the edge is rejected with or without moving the contents.+ assert_rejected(&mut s, "layer.artboard.set", json!({"x": i32::MAX, "moveContents": false}));+ assert_rejected(&mut s, "layer.artboard.set", json!({"x": i32::MAX - 10}));+ assert_rejected(&mut s, "layer.artboard.set", json!({"rect": [i32::MAX - 10, 0, 50, 50], "moveContents": false}));+ // Without the contents only the board's own rect changes, so the far move is fine.+ let r = s.execute("layer.artboard.set", json!({"x": i32::MAX - 50, "y": i32::MAX - 50, "moveContents": false})).unwrap();+ assert_eq!(r["rect"], json!([i32::MAX - 50, i32::MAX - 50, 50, 50]));+ assert_eq!(board_rect(&s, id), Rect::new(i32::MAX - 50, i32::MAX - 50, i32::MAX, i32::MAX));+ // Resizing past the edge is rejected instead of shrinking the board to fit.+ assert_rejected(&mut s, "layer.artboard.set", json!({"width": 51}));+ assert_rejected(&mut s, "layer.artboard.set", json!({"height": 3_000_000_000_i64}));+ assert_rejected(&mut s, "layer.artboard.set", json!({"preset": "iPhone 14"}));+ // A board at the edge can still be shrunk or moved back in.+ let r = s.execute("layer.artboard.set", json!({"width": 20})).unwrap();+ assert_eq!(r["rect"], json!([i32::MAX - 50, i32::MAX - 50, 20, 50]));+ let r = s.execute("layer.artboard.set", json!({"x": 0, "y": 0, "moveContents": false})).unwrap();+ assert_eq!(r["rect"], json!([0, 0, 20, 50]));+}++#[test]+fn artboards_at_ordinary_coordinates_still_place_and_edit() {+ // Default placement leaves a 100 px gap right of the rightmost board.+ let mut s = session(8);+ let r = s.execute("layer.new.artboard", json!({"x": 10, "width": 50, "height": 50})).unwrap();+ let first = r["layer"].as_u64().unwrap();+ let r = s.execute("layer.new.artboard", json!({"width": 50})).unwrap();+ assert_eq!(r["rect"], json!([160, 0, 50, 80]));+ // Editing moves the board (and its contents) and resizes it.+ let red = add_square(&mut s, Rect::new(20, 10, 30, 20), [1.0, 0.0, 0.0, 1.0]);+ s.edit("into board", |doc, _| {+ let l = doc.remove(red).unwrap();+ let LayerContent::Group(g) = &mut doc.layer_mut(LayerId(first)).unwrap().content else { panic!("not a group") };+ g.children.push(l);+ Ok(())+ })+ .unwrap();+ let r = s.execute("layer.artboard.set", json!({"layer": first, "x": 200})).unwrap();+ assert_eq!(r["rect"], json!([200, 0, 50, 50]));+ assert_eq!(doc(&s).layer(red).unwrap().surface().unwrap().content_bounds(), Rect::new(210, 10, 220, 20));+ let r = s.execute("layer.artboard.set", json!({"layer": first, "width": 70, "height": 40})).unwrap();+ assert_eq!(r["rect"], json!([200, 0, 70, 40]));+}++#[test]+fn export_rejects_a_board_too_far_from_the_origin() {+ let mut s = session(8);+ s.execute("layer.new.artboard", json!({"x": i32::MIN, "width": 50, "height": 50, "name": "Far"})).unwrap();+ let dir = std::env::temp_dir().join(format!("photocraft-artboards-931-{}", std::process::id()));+ let d = dir.to_string_lossy().into_owned();+ // Moving the board to the origin needs dx = 2^31, one past i32::MAX: an error, not a panic.+ let err = s.execute("file.export.artboardsToFiles", json!({"dir": d})).unwrap_err().to_string();+ assert!(err.contains(&i32::MIN.to_string()), "{err}");+ let pdf = join(&d, "boards.pdf");+ assert!(s.execute("file.export.artboardsToPdf", json!({"path": pdf})).is_err());+ assert!(!dir.exists(), "nothing was written");+ // One pixel in from the edge is representable and still exports.+ let one = artboard_document(doc(&s), doc(&s).artboards()[0].0);+ assert!(one.is_err());+ s.execute("layer.artboard.set", json!({"x": i32::MIN + 1, "moveContents": false})).unwrap();+ let one = artboard_document(doc(&s), doc(&s).artboards()[0].0).unwrap().unwrap();+ assert_eq!((one.size.width, one.size.height), (50, 50));+ assert_eq!(one.artboards()[0].2.rect, Rect::new(0, 0, 50, 50));+}