DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Integration: coordinates must be finite (#1050)
aionggd04d4de8fe31
diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rsindex 5d86d4036..e2ae243fe 100644--- a/crates/doc/src/edit.rs+++ b/crates/doc/src/edit.rs@@ -609,6 +609,22 @@ impl Document {None}+ /// The first item on a document or parent spread whose geometry isn't finite+ /// ([`Item::geometry_is_finite`]).+ pub fn non_finite_item(&self) -> Option<ItemId> {+ let mut found = None;+ for sp in self.spreads.iter().chain(&self.parents) {+ for it in &sp.items {+ it.walk(&mut |i| {+ if found.is_none() && !i.geometry_is_finite() {+ found = Some(i.id);+ }+ });+ }+ }+ found+ }+/// Every item id (pre-order) on document spreads.pub fn all_items(&self) -> Vec<ItemId> {let mut v = Vec::new();diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rsindex 456fb8783..cfb13dc53 100644--- a/crates/doc/src/item.rs+++ b/crates/doc/src/item.rs@@ -1612,6 +1612,19 @@ impl Item {}}+ /// Whether the item's own geometry (path, transform, a placed graphic's size and transform)+ /// is finite. JSON has no infinity or NaN, so a document holding one can't be saved.+ pub fn geometry_is_finite(&self) -> bool {+ let pt = |p: Point| p.x.is_finite() && p.y.is_finite();+ let affine = |a: &Affine| a.as_coeffs().iter().all(|c| c.is_finite());+ let path = self.path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| pt(a.p) && pt(a.h_in) && pt(a.h_out));+ let graphic = match &self.content {+ Content::Graphic(g) => g.size.0.is_finite() && g.size.1.is_finite() && affine(&g.xf),+ _ => true,+ };+ path && affine(&self.xf) && graphic+ }+/// Visit this item and descendants (pre-order).pub fn walk<'a>(&'a self, f: &mut impl FnMut(&'a Item)) {f(self);diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rsindex 13463ad36..a55f51ebe 100644--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@ -718,7 +718,8 @@ fn file_place(s: &mut Session, p: &Value) -> Result<Value> {let (x, y) = (px.unwrap_or(pr.x0), py.unwrap_or(pr.y0));let id = ItemId(d.alloc());let k = w / nw;- let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(x, y, x + bw * k, y + bh * k)));+ let r = super::finite_rect("file.place", Rect::new(x, y, x + bw * k, y + bh * k))?;+ let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(r));it.object_style = d.styles.default_graphic_frame.clone();if let Some(e) = d.styles.object_effects(&it.object_style) {it.effects = e.clone();@@ -867,6 +868,7 @@ fn place_drop(s: &mut Session, p: &Value) -> Result<Value> {}_ => (Rect::new(x, y, x + nw, y + nh), 1.0),};+ let frame_r = super::finite_rect("place.drop", frame_r)?;let id = ItemId(d.alloc());let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(frame_r));it.object_style = d.styles.default_graphic_frame.clone();@@ -1076,7 +1078,7 @@ mod image_place_tests {use crate::Session;- fn image_file() -> std::io::Result<tempfile::NamedTempFile> {+ pub(super) fn image_file() -> std::io::Result<tempfile::NamedTempFile> {image_file_with_color(30)}@@ -1623,6 +1625,34 @@ mod save_tests {assert!(checkpoint.exists(), "the recovery checkpoint stays");let _ = std::fs::remove_dir_all(&dir);}++ /// #1050: a placement whose coordinates overflow to infinity is refused, and Save refuses a+ /// document holding a non-finite rect anyway, leaving the file on disk as it was.+ #[test]+ fn non_finite_coordinates_are_refused_and_never_saved() {+ let image = super::image_place_tests::image_file().unwrap();+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let e = s.execute("file.place", &json!({"path": image.path(), "x": 1e308, "width": 1e308})).unwrap_err();+ assert!(e.to_string().contains("finite"), "{e}");+ assert!(s.doc().unwrap().doc.all_items().is_empty(), "nothing is placed");++ let dir = std::env::temp_dir().join(format!("dc-save-non-finite-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("doc.designcraft");+ s.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap();+ let before = std::fs::read(&path).unwrap();+ let id = designcraft_doc::ItemId(s.execute("frame.create", &json!({"rect": [36, 36, 300, 200]})).unwrap()["id"].as_u64().unwrap());+ let st = s.doc_mut().unwrap();+ let infinite = designcraft_geom::Rect::new(36.0, 36.0, f64::INFINITY, 200.0);+ std::sync::Arc::make_mut(&mut st.doc).item_mut(id).unwrap().path = designcraft_geom::shapes::rectangle(infinite);+ let e = s.execute("file.save", &json!({})).unwrap_err();+ assert!(e.to_string().contains("not a finite number"), "{e}");+ assert_eq!(std::fs::read(&path).unwrap(), before, "the saved file is untouched");+ assert!(s.doc().unwrap().is_dirty());+ let _ = std::fs::remove_dir_all(&dir);+ }}#[cfg(test)]diff --git a/crates/engine/src/cmd/media.rs b/crates/engine/src/cmd/media.rsindex 43c6cfacf..9e26fb0b4 100644--- a/crates/engine/src/cmd/media.rs+++ b/crates/engine/src/cmd/media.rs@@ -49,7 +49,8 @@ pub(crate) fn place_media(s: &mut Session, p: &Value, name: String, mime: &str,let pr = d.spread(spread).and_then(|sp| sp.pages.first()).map(|pg| pg.margin_rect()).unwrap_or(Rect::new(36.0, 36.0, 300.0, 300.0));let (x, y) = (px.unwrap_or(pr.x0), py.unwrap_or(pr.y0));let id = ItemId(d.alloc());- let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(x, y, x + w, y + h)));+ let r = super::finite_rect("file.place", Rect::new(x, y, x + w, y + h))?;+ let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(r));it.content = Content::Graphic(Graphic {asset: aid,size: (w, h),diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex e1287f385..a1069052a 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -273,6 +273,16 @@ pub(crate) fn point_param(p: &Value, key: &str) -> Option<Point> {let a = p.get(key)?.as_array()?;Some(Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?))}+/// `r`, computed from coordinate params, or an error when a value overflowed to infinity or NaN:+/// a document holding one can't be saved (#1050).+pub(crate) fn finite_rect(command: &str, r: Rect) -> Result<Rect> {+ if [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {+ Ok(r)+ } else {+ Err(bad(command, "the position and size must stay finite numbers"))+ }+}+pub(crate) fn rect_param(p: &Value, key: &str) -> Option<Rect> {let a = p.get(key)?.as_array()?;let f = |i: usize| a.get(i).and_then(Value::as_f64);diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rsindex efd04d528..cada21060 100644--- a/crates/engine/src/cmd/object.rs+++ b/crates/engine/src/cmd/object.rs@@ -2406,7 +2406,8 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result<Value> {&& ["columnsKind", "columnWidth", "columns", "gutter", "inset"].iter().any(|k| p.get(*k).is_some())&& let Some(r) = d.item(*id).map(Item::inner_bounds){- crate::autosize::resize(d, *id, Rect::new(r.x0, r.y0, r.x0 + width, r.y1));+ let r = super::finite_rect("object.textFrameOptions", Rect::new(r.x0, r.y0, r.x0 + width, r.y1))?;+ crate::autosize::resize(d, *id, r);}}// Story direction belongs to the story: every frame of the thread turns.diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rsindex 50d48fb21..80b31f078 100644--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@ -31,6 +31,9 @@ pub enum FormatError {TooNew(u32),#[error("{0}")]Io(String),+ /// The document holds something the file can't represent; nothing is written.+ #[error("{0}")]+ Unsaveable(String),}fn ext_for(mime: &str) -> &'static str {@@ -62,6 +65,10 @@ pub fn save_with_preview(doc: &Document, preview: Option<&[u8]>) -> Result<Vec<uconst LARGE_ENTRY: usize = (u32::MAX as usize).saturating_sub(64 << 20);fn save_with_large_entries_from(doc: &Document, preview: Option<&[u8]>, large_entry: usize) -> Result<Vec<u8>, FormatError> {+ // JSON writes infinity and NaN as null, which no load accepts: the file would not open.+ if let Some(id) = doc.non_finite_item() {+ return Err(FormatError::Unsaveable(format!("object {} has a position or size that is not a finite number", id.0)));+ }let mut compact = doc.clone();compact.compact_assets();let doc = &compact;