diff --git a/assets/locales/pending/drawing-image.json b/assets/locales/pending/drawing-image.json new file mode 100644 index 00000000000..82c224138d6 --- /dev/null +++ b/assets/locales/pending/drawing-image.json @@ -0,0 +1,26 @@ +{ + "en": { + "cmd.drawing_image_add": "Add Image" + }, + "ar": { + "cmd.drawing_image_add": "إضافة صورة" + }, + "de": { + "cmd.drawing_image_add": "Bild hinzufügen" + }, + "he": { + "cmd.drawing_image_add": "הוספת תמונה" + }, + "ja": { + "cmd.drawing_image_add": "画像を追加" + }, + "ko": { + "cmd.drawing_image_add": "이미지 추가" + }, + "vi": { + "cmd.drawing_image_add": "Thêm hình ảnh" + }, + "zh": { + "cmd.drawing_image_add": "添加图像" + } +} diff --git a/crates/doc/src/drawing.rs b/crates/doc/src/drawing.rs index 86557951e61..7ea7e31d45f 100644 --- a/crates/doc/src/drawing.rs +++ b/crates/doc/src/drawing.rs @@ -23,6 +23,7 @@ //! - **Dimensions** on its views, each measuring named corners or edges of the view's model //! ([`dimension`]). //! - **Balloons** on its views, each pointing at a placed part by a named edge of it ([`balloon`]). +//! - **Images** on its sheets, each file kept once however many places it sits ([`image`]). //! - **Revisions**: one revision record for the whole drawing ([`RevisionRecord`]), its rows in the //! order they were added, the newest last. //! @@ -41,8 +42,8 @@ //! //! [`Drawing::from_json`] reads a drawing in this order: at most [`MAX_DRAWING_BYTES`] of text, //! the family's format check, every number in range, the upgrade, the typed record with its views, -//! dimensions and balloons by id, then [`Drawing::validate`]; [`Drawing::from_value`] the same from the -//! format check on. +//! dimensions, balloons and images by id, then [`Drawing::validate`] and each image's file +//! ([`Drawing::check_image_files`]); [`Drawing::from_value`] the same from the format check on. use std::borrow::Cow; use std::collections::BTreeSet; @@ -60,11 +61,15 @@ use crate::ids::{self, IdSource}; use crate::{DocError, Metadata, Result, expr}; pub mod balloon; +pub mod by_id; pub mod dimension; +pub mod image; pub mod view; use balloon::Balloon; +use by_id::ById; use dimension::Dimension; +use image::{ImageFile, SheetImage}; use view::View; /// The most drawings a design may hold. @@ -124,9 +129,14 @@ pub struct Drawing { /// By id ([`Drawing::add_dimensions`]), each behind its own `Arc`, as the views are. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub dimensions: Vec>, - /// By id ([`Drawing::add_balloons`]), as the dimensions are. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub balloons: Vec>, + #[serde(default, skip_serializing_if = "ById::is_empty")] + pub balloons: ById, + /// The image files, once each however many places they sit. + #[serde(default, skip_serializing_if = "ById::is_empty")] + pub images: ById, + /// Where they sit on the sheets. + #[serde(default, skip_serializing_if = "ById::is_empty")] + pub sheet_images: ById, /// Behind an `Arc` as the sheets are, so an undo step shares it while it doesn't change. #[serde(default, skip_serializing_if = "no_revisions")] pub revisions: Arc, @@ -213,12 +223,14 @@ pub struct OnSheet { pub dimensions: Vec, /// The balloons in its views. pub balloons: Vec, + /// The images placed on it. + pub images: Vec, } impl OnSheet { /// Nothing is on the sheet. pub fn is_empty(&self) -> bool { - self.views.is_empty() && self.dimensions.is_empty() && self.balloons.is_empty() + self.views.is_empty() && self.dimensions.is_empty() && self.balloons.is_empty() && self.images.is_empty() } } @@ -257,7 +269,9 @@ impl Drawing { sheets: vec![Arc::new(first)], views: Vec::new(), dimensions: Vec::new(), - balloons: Vec::new(), + balloons: ById::default(), + images: ById::default(), + sheet_images: ById::default(), revisions: Arc::default(), }; drawing.validate()?; @@ -281,11 +295,14 @@ impl Drawing { DRAWING.check_numbers(&v, "properties")?; DRAWING.upgrade(&mut v, version, applied.as_deref())?; let mut d: Drawing = serde_json::from_value(v).map_err(damaged)?; - let (views, dimensions, balloons) = (std::mem::take(&mut d.views), std::mem::take(&mut d.dimensions), std::mem::take(&mut d.balloons)); + let (views, dimensions) = (std::mem::take(&mut d.views), std::mem::take(&mut d.dimensions)); d.add_views(views); d.add_dimensions(dimensions); - d.add_balloons(balloons); + d.balloons.put_in_order(); + d.images.put_in_order(); + d.sheet_images.put_in_order(); d.validate().map_err(damaged)?; + d.check_image_files().map_err(damaged)?; Ok(Drawing { format: DRAWING.format_string(DRAWING.current()), format_pending: DRAWING.pending_names(), ..d }) } @@ -320,21 +337,25 @@ impl Drawing { /// Whether `id` names an object a sheet shows: a view, a dimension or a balloon. pub fn has_object(&self, id: u64) -> bool { - self.view(id).is_some() || self.dimension(id).is_some() || self.balloon(id).is_some() + self.view(id).is_some() || self.dimension(id).is_some() || self.balloons.by_id(id).is_some() } - /// What is on sheet `id`: its views and the dimensions and balloons in them. Each later kind of record on a - /// sheet adds its own here, and goes with the sheet ([`Drawing::remove_sheet`]). + /// What is on sheet `id`: its views and the dimensions and balloons in them, and the images placed on it. + /// Each later kind of record on a sheet adds its own here, and goes with the sheet + /// ([`Drawing::remove_sheet`]). pub fn on_sheet(&self, id: u64) -> OnSheet { - // The views are listed by id, so the sheet's are too. - self.with_contents(self.views.iter().filter(|v| v.sheet == id).map(|v| v.id).collect()) + // The views are listed by id, so the sheet's are too, and so are its images. + let mut on = self.with_contents(self.views.iter().filter(|v| v.sheet == id).map(|v| v.id).collect()); + on.images = self.sheet_images.iter().filter(|i| i.sheet == id).map(|i| i.id).collect(); + on } - /// `views`, listed by id, with the dimensions and balloons in them. + /// `views`, listed by id, with the dimensions and balloons in them. An image sits on a sheet, never in a + /// view, so there are none. pub fn with_contents(&self, views: Vec) -> OnSheet { let dimensions = self.dimensions.iter().filter(|d| views.binary_search(&d.view).is_ok()).map(|d| d.id).collect(); let balloons = self.balloons.iter().filter(|b| views.binary_search(&b.view).is_ok()).map(|b| b.id).collect(); - OnSheet { views, dimensions, balloons } + OnSheet { views, dimensions, balloons, images: Vec::new() } } /// Takes sheet `id` out with everything on it ([`Drawing::on_sheet`]), and answers what that @@ -348,11 +369,14 @@ impl Drawing { } /// Takes `objects` out, each list by id: the one rule a sheet's delete and a selection's delete - /// remove by. As in [`Drawing::remove_sheet`], what is left must still keep the record's rules. + /// remove by, with the image files nothing uses any more. As in [`Drawing::remove_sheet`], what is + /// left must still keep the record's rules. pub fn remove_objects(&mut self, objects: &OnSheet) { self.views.retain(|v| objects.views.binary_search(&v.id).is_err()); self.dimensions.retain(|d| objects.dimensions.binary_search(&d.id).is_err()); self.balloons.retain(|b| objects.balloons.binary_search(&b.id).is_err()); + self.sheet_images.retain(|i| objects.images.binary_search(&i.id).is_err()); + self.drop_unused_images(); } /// Every object's id, of every kind: what a new id must differ from. Each later kind adds its @@ -364,6 +388,8 @@ impl Drawing { .chain(self.views.iter().map(|v| v.id)) .chain(self.dimensions.iter().map(|d| d.id)) .chain(self.balloons.iter().map(|b| b.id)) + .chain(self.images.iter().map(|i| i.id)) + .chain(self.sheet_images.iter().map(|i| i.id)) .chain(self.revisions.ids()) } @@ -395,7 +421,8 @@ impl Drawing { self.revisions.validate().map_err(|e| DocError::Invalid(e.to_string()))?; self.check_views()?; self.check_dimensions()?; - self.check_balloons() + self.check_balloons()?; + self.check_images() } /// A sheet's own rules, and that the source it documents is one of the drawing's. diff --git a/crates/doc/src/drawing/balloon.rs b/crates/doc/src/drawing/balloon.rs index 8f9f06bbc8f..478dff80276 100644 --- a/crates/doc/src/drawing/balloon.rs +++ b/crates/doc/src/drawing/balloon.rs @@ -18,15 +18,14 @@ //! [`Document::resolve_balloons`] finds each balloon's edge again as a dimension's is found //! ([`super::dimension::Status`]): by name, strictly, and what it can't decide it says. -use std::sync::Arc; - use serde::{Deserialize, Serialize}; use solidcraft_geom::Vec3; use solidcraft_geom::drawing_view::is_paper_coordinate; use solidcraft_geom::paper::MAX_SIDE_MM; +use super::by_id::Record; use super::dimension::{Lookup, ModelEdge, Status, check_edge, edge_candidates}; -use super::{Drawing, add_by_id, in_id_order, require}; +use super::{Drawing, require}; use crate::{DocError, Document, Model, Result, ids}; /// The most balloons a drawing may have. @@ -54,31 +53,17 @@ impl Balloon { } } -impl Drawing { - /// Adds `balloons`, each where its id puts it, as [`Drawing::add_dimensions`] adds dimensions. - pub fn add_balloons(&mut self, balloons: impl IntoIterator>) { - add_by_id(&mut self.balloons, balloons, |b| b.id); - } - - /// Balloon `id`, found by halves in the balloons' id order. - pub fn balloon(&self, id: u64) -> Option<&Balloon> { - self.balloon_index(id).and_then(|i| self.balloons.get(i)).map(|b| &**b) - } - - /// Where balloon `id` is in [`Drawing::balloons`]. - pub fn balloon_index(&self, id: u64) -> Option { - self.balloons.binary_search_by_key(&id, |b| b.id).ok() +impl Record for Balloon { + fn id(&self) -> u64 { + self.id } +} +impl Drawing { /// The balloons' rules (the module's notes). The views are checked first, so they are in id /// order here. pub(super) fn check_balloons(&self) -> Result<()> { - require(self.balloons.len() <= MAX_BALLOONS, || format!("a drawing has at most {MAX_BALLOONS} balloons"))?; - require(in_id_order(&self.balloons, |b| b.id), || "a drawing lists its balloons by id".into())?; - for balloon in &self.balloons { - self.check_balloon(balloon).map_err(|e| DocError::Invalid(format!("balloon {}: {e}", ids::encode(balloon.id))))?; - } - Ok(()) + self.balloons.check(MAX_BALLOONS, "balloon", |b| self.check_balloon(b)) } fn check_balloon(&self, b: &Balloon) -> Result<()> { @@ -110,7 +95,7 @@ impl Document { wanted .iter() .map(|id| { - let b = drawing.balloon(*id).ok_or_else(|| DocError::Unknown(format!("balloon {}", ids::encode(*id))))?; + let b = drawing.balloons.by_id(*id).ok_or_else(|| DocError::Unknown(format!("balloon {}", ids::encode(*id))))?; Ok(match lookup.edges(&b.edge) { // A split edge has no one middle: the pieces are listed, and none is chosen. Ok(found) if !found.whole => { diff --git a/crates/doc/src/drawing/balloon_tests.rs b/crates/doc/src/drawing/balloon_tests.rs index 9eccbeea06e..551b5612085 100644 --- a/crates/doc/src/drawing/balloon_tests.rs +++ b/crates/doc/src/drawing/balloon_tests.rs @@ -1,4 +1,5 @@ use std::collections::BTreeSet; +use std::sync::Arc; use serde_json::{Value, json}; use solidcraft_geom::drawing_sheet::{self, Orientation, PaperSize}; @@ -39,7 +40,7 @@ fn ballooned() -> (Drawing, [u64; 2]) { let mut added = [0; 2]; for ((path, at), id) in [(vec![3], [40.0, 25.0]), (vec![3, 7], [-35.5, 60.0])].into_iter().zip(&mut added) { *id = d.allocate_id(&mut id_source).unwrap(); - d.add_balloons([Arc::new(Balloon { id: *id, view, edge: edge("F1:side|F2:head", path), at })]); + d.balloons.add([Arc::new(Balloon { id: *id, view, edge: edge("F1:side|F2:head", path), at })]); } d.validate().unwrap(); (d, added) @@ -80,7 +81,7 @@ fn balloons_save_what_they_point_at_and_read_back_as_saved() { }) ); assert_eq!(balloon(&mut v, &placed)["edge"]["path"], json!([3])); - assert_eq!(d.balloon(added[1]).unwrap().occurrence(), [3, 7], "the part it numbers is its edge's path"); + assert_eq!(d.balloons.by_id(added[1]).unwrap().occurrence(), [3, 7], "the part it numbers is its edge's path"); let listed: Vec = v["balloons"].as_array().unwrap().iter().map(|x| ids::decode(x["id"].as_str().unwrap()).unwrap()).collect(); let mut by_id = added.to_vec(); by_id.sort_unstable(); diff --git a/crates/doc/src/drawing/by_id.rs b/crates/doc/src/drawing/by_id.rs new file mode 100644 index 00000000000..9fc96407150 --- /dev/null +++ b/crates/doc/src/drawing/by_id.rs @@ -0,0 +1,90 @@ +//! A drawing's list of one kind of record: each behind its own `Arc`, so an undo step shares what it +//! didn't change, and by id, whatever order they came in. It holds what every such list does, so a +//! kind's own file holds only its own rules. + +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; + +use super::require; +use crate::{DocError, Result, ids}; + +/// A record a drawing lists by its id. +pub trait Record { + fn id(&self) -> u64; +} + +/// The records of one kind, by id. It reads as the `Vec` it is, and a file holds them as one. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ById(Vec>); + +impl Default for ById { + fn default() -> Self { + ById(Vec::new()) + } +} + +impl Deref for ById { + type Target = Vec>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for ById { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl<'a, T> IntoIterator for &'a ById { + type Item = &'a Arc; + type IntoIter = std::slice::Iter<'a, Arc>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl ById { + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +impl ById { + /// Adds `more`, each where its id puts it. + pub fn add(&mut self, more: impl IntoIterator>) { + self.0.extend(more); + self.put_in_order(); + } + + /// Puts what a file listed in another order where each id puts it. + pub(super) fn put_in_order(&mut self) { + self.0.sort_by_key(|record| record.id()); + } + + /// Where record `id` is in the list, found by halves. + pub fn index_of(&self, id: u64) -> Option { + self.0.binary_search_by_key(&id, |record| record.id()).ok() + } + + /// Record `id`. + pub fn by_id(&self, id: u64) -> Option<&T> { + self.index_of(id).and_then(|at| self.0.get(at)).map(|record| &**record) + } + + /// The list's rules, each named by `word`: at most `most` records, by id, each keeping `rule`. + pub(super) fn check(&self, most: usize, word: &str, rule: impl Fn(&T) -> Result<()>) -> Result<()> { + require(self.0.len() <= most, || format!("a drawing has at most {most} {word}s"))?; + require(self.0.is_sorted_by_key(|record| record.id()), || format!("a drawing lists its {word}s by id"))?; + self.0.iter().try_for_each(|record| rule(record).map_err(|e| DocError::Invalid(format!("{word} {}: {e}", ids::encode(record.id()))))) + } +} + +#[cfg(test)] +#[path = "by_id_tests.rs"] +mod tests; diff --git a/crates/doc/src/drawing/by_id_tests.rs b/crates/doc/src/drawing/by_id_tests.rs new file mode 100644 index 00000000000..cd1c1061f19 --- /dev/null +++ b/crates/doc/src/drawing/by_id_tests.rs @@ -0,0 +1,50 @@ +use serde_json::json; + +use super::*; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct Thing(u64); + +impl Record for Thing { + fn id(&self) -> u64 { + self.0 + } +} + +fn things(ids: &[u64]) -> ById { + let mut list = ById::default(); + list.add(ids.iter().map(|id| Arc::new(Thing(*id)))); + list +} + +#[test] +fn records_go_where_their_ids_put_them_and_are_found_there() { + let mut list = things(&[30, 10]); + list.add([Arc::new(Thing(20))]); + assert_eq!(list.iter().map(|t| t.0).collect::>(), [10, 20, 30]); + assert_eq!((list.index_of(20), list.by_id(30).map(|t| t.0)), (Some(1), Some(30))); + assert_eq!((list.index_of(25), list.by_id(25)), (None, None)); + assert!(ById::::default().is_empty() && !list.is_empty()); +} + +#[test] +fn a_file_holds_the_plain_list() { + let list = things(&[1, 2]); + assert_eq!(serde_json::to_value(&list).unwrap(), json!([1, 2])); + assert_eq!(serde_json::from_value::>(json!([1, 2])).unwrap(), list); +} + +#[test] +fn the_rules_name_the_kind_and_the_record() { + let fine = |_: &Thing| Ok(()); + things(&[1, 2]).check(2, "thing", fine).unwrap(); + assert!(things(&[1, 2, 3]).check(2, "thing", fine).is_err_and(|e| e.to_string().contains("at most 2 things"))); + let mut out_of_order = things(&[1, 2]); + out_of_order.reverse(); + assert!(out_of_order.check(2, "thing", fine).is_err_and(|e| e.to_string().contains("lists its things by id"))); + out_of_order.put_in_order(); + out_of_order.check(2, "thing", fine).unwrap(); + let odd = |t: &Thing| require(t.0.is_multiple_of(2), || "it is odd".into()); + let e = things(&[2, 3]).check(2, "thing", odd).unwrap_err().to_string(); + assert!(e.contains(&format!("thing {}: it is odd", ids::encode(3))), "{e}"); +} diff --git a/crates/doc/src/drawing/format/pending/images.rs b/crates/doc/src/drawing/format/pending/images.rs new file mode 100644 index 00000000000..75d89dfa8b0 --- /dev/null +++ b/crates/doc/src/drawing/format/pending/images.rs @@ -0,0 +1,4 @@ +//! Drawings save their images (#5426): `images` holds each file once, with its format, pixel size and +//! bytes (base64), and `sheet_images` each place one sits, with its sheet, its rectangle and the file's +//! id. The file's path is never saved. An older drawing has neither. The last release refuses a drawing +//! saved with them, as a newer format. diff --git a/crates/doc/src/drawing/image.rs b/crates/doc/src/drawing/image.rs new file mode 100644 index 00000000000..b7d59ee90c9 --- /dev/null +++ b/crates/doc/src/drawing/image.rs @@ -0,0 +1,156 @@ +//! A drawing's images (W38e, #5426): a PNG or JPEG placed on a sheet, such as a logo or a photo. +//! +//! - **A file and its placements are two records.** A logo sits on every sheet: [`Drawing::images`] +//! holds it once, and each [`SheetImage`] in [`Drawing::sheet_images`] says where one sits. A file +//! goes with the last thing that uses it ([`Drawing::images_in_use`]). +//! - **The bytes** travel in the drawing's record (base64, as a canvas's do), so the design opens +//! without the original file, and the file's path is never saved. +//! - **The caps** are checked from the file's bytes and header, before anything decodes its pixels: +//! a small file can claim to hold more pixels than memory has. The header can lie in the record +//! too, so reading a drawing compares the two ([`Drawing::check_image_files`]); an edit, which only +//! ever adds a checked file, doesn't decode them again. +//! +//! The rules, beside the record's: a file is used; a placement names a file the drawing has, and is +//! on one of its sheets, in a rectangle on paper with a size; at most [`MAX_IMAGES`] files of at most +//! [`MAX_IMAGE_BYTES`] and [`MAX_IMAGE_PIXELS`] each, and [`MAX_IMAGES_BYTES`] between them; at most +//! [`MAX_SHEET_IMAGES`] placements; each list by id. + +use std::collections::BTreeSet; + +use serde::{Deserialize, Serialize}; +use solidcraft_geom::drawing_view::is_paper_coordinate; +use solidcraft_geom::paper::{MAX_IMAGE_PIXELS, MAX_SIDE_MM}; + +use super::by_id::Record; +use super::{Drawing, require}; +use crate::canvas::{base64_decode, base64_encode, image_info}; +use crate::{DocError, Result, ids}; + +/// The most image files a drawing may have. +pub const MAX_IMAGES: usize = 1_000; +/// The most placements of them a drawing may have. +pub const MAX_SHEET_IMAGES: usize = 1_000; +/// The largest file an image may be. +pub const MAX_IMAGE_BYTES: usize = 4 << 20; +/// The most a drawing's image files may be between them: two of the largest and some, whose 12 MiB +/// of text leaves room under [`super::MAX_DRAWING_BYTES`] for the rest of the record. +pub const MAX_IMAGES_BYTES: usize = 9 << 20; + +/// One image file of a drawing, however many places it sits. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImageFile { + #[serde(with = "crate::ids")] + pub id: u64, + /// `png` or `jpeg`, as the file's header says. + pub format: String, + /// Its width and height in pixels, as the file's header says. + pub pixels: [u32; 2], + /// The file, base64. + pub data: String, +} + +/// One place an image file sits, on a sheet of a drawing. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SheetImage { + #[serde(with = "crate::ids")] + pub id: u64, + #[serde(with = "crate::ids")] + pub sheet: u64, + /// Where it sits, `[x0, y0, x1, y1]` in millimetres from the sheet's lower-left corner. + pub rect_mm: [f64; 4], + /// The file it shows, by id. + #[serde(with = "crate::ids")] + pub image: u64, +} + +/// The length of `bytes` bytes in base64. +const fn encoded(bytes: usize) -> usize { + bytes.div_ceil(3) * 4 +} + +/// What a file's bytes and header say it is, when its caps allow it. Nothing is decoded. +fn file_info(bytes: &[u8]) -> Result<(&'static str, [u32; 2])> { + require(bytes.len() <= MAX_IMAGE_BYTES, || format!("the file is over {} MiB", MAX_IMAGE_BYTES >> 20))?; + let (format, pixels) = image_info(bytes).ok_or_else(|| DocError::Invalid("the file isn't a PNG or JPEG".into()))?; + let [w, h] = pixels; + require(u64::from(w) * u64::from(h) <= MAX_IMAGE_PIXELS, || format!("the file has {w} by {h} pixels, over {MAX_IMAGE_PIXELS}"))?; + Ok((format, pixels)) +} + +impl ImageFile { + /// The image file of a file's `bytes`, when its caps allow it: nothing is decoded. + pub fn from_file(id: u64, bytes: &[u8]) -> Result { + let (format, pixels) = file_info(bytes)?; + Ok(ImageFile { id, format: format.into(), pixels, data: base64_encode(bytes) }) + } +} + +impl Record for ImageFile { + fn id(&self) -> u64 { + self.id + } +} + +impl Record for SheetImage { + fn id(&self) -> u64 { + self.id + } +} + +impl Drawing { + /// The image files something in the drawing uses: the one list of what keeps a file. Anything new + /// that shows a file adds its own here. + pub fn images_in_use(&self) -> BTreeSet { + self.sheet_images.iter().map(|placement| placement.image).collect() + } + + /// Takes out each image file nothing uses now. + pub(super) fn drop_unused_images(&mut self) { + let used = self.images_in_use(); + self.images.retain(|file| used.contains(&file.id)); + } + + pub(super) fn check_images(&self) -> Result<()> { + // The placements first: one that names no file says so, before its file reads as unused. + self.sheet_images.check(MAX_SHEET_IMAGES, "placed image", |placement| self.check_sheet_image(placement))?; + let used = self.images_in_use(); + self.images.check(MAX_IMAGES, "image", |file| { + check_image(file)?; + require(used.contains(&file.id), || "nothing uses it".into()) + })?; + let total = self.images.iter().fold(0, |total: usize, i| total.saturating_add(i.data.len())); + require(total <= encoded(MAX_IMAGES_BYTES), || format!("a drawing's images are at most {} MiB between them", MAX_IMAGES_BYTES >> 20)) + } + + fn check_sheet_image(&self, i: &SheetImage) -> Result<()> { + require(self.images.by_id(i.image).is_some(), || format!("it shows image {}, which the drawing doesn't have", ids::encode(i.image)))?; + require(self.sheets.iter().any(|s| s.id == i.sheet), || format!("it is on sheet {}, which the drawing doesn't have", ids::encode(i.sheet)))?; + let [x0, y0, x1, y1] = i.rect_mm; + let on_paper = [x0, y0, x1, y1].into_iter().all(is_paper_coordinate); + require(on_paper && x0 < x1 && y0 < y1, || format!("its rectangle has a size and is at most {MAX_SIDE_MM} mm on paper")) + } + + /// Each image's bytes are the file its record says: what reading a drawing checks once, as it + /// decodes the base64, so that nothing later trusts a size the file doesn't have. + pub(super) fn check_image_files(&self) -> Result<()> { + self.images.iter().try_for_each(|i| { + let bytes = base64_decode(&i.data).ok_or_else(|| DocError::Invalid(format!("image {}: its file isn't base64", ids::encode(i.id))))?; + let (format, pixels) = file_info(&bytes).map_err(|e| DocError::Invalid(format!("image {}: {e}", ids::encode(i.id))))?; + require(format == i.format && pixels == i.pixels, || format!("image {}: its record and its file disagree", ids::encode(i.id))) + }) + } +} + +/// A file's own rules, from its record alone: what every edit keeps, without decoding it. +fn check_image(i: &ImageFile) -> Result<()> { + require(matches!(i.format.as_str(), "png" | "jpeg"), || "it is a PNG or a JPEG".into())?; + let [w, h] = i.pixels; + require(w > 0 && h > 0 && u64::from(w) * u64::from(h) <= MAX_IMAGE_PIXELS, || format!("it has 1 to {MAX_IMAGE_PIXELS} pixels"))?; + require(i.data.len() <= encoded(MAX_IMAGE_BYTES), || format!("its file is at most {} MiB", MAX_IMAGE_BYTES >> 20)) +} + +#[cfg(test)] +#[path = "image_tests.rs"] +mod tests; diff --git a/crates/doc/src/drawing/image_tests.rs b/crates/doc/src/drawing/image_tests.rs new file mode 100644 index 00000000000..63b5f29561c --- /dev/null +++ b/crates/doc/src/drawing/image_tests.rs @@ -0,0 +1,233 @@ +use std::collections::BTreeSet; +use std::sync::Arc; + +use serde_json::{Value, json}; +use solidcraft_geom::drawing_sheet::{self, Orientation, PaperSize}; + +use super::*; +use crate::ids::IdSource; + +const RECT: [f64; 4] = [10.0, 20.0, 60.0, 45.0]; + +/// A PNG's header, saying these pixels: all a cap reads. +fn png(w: u32, h: u32) -> Vec { + let mut b = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); + b.extend(w.to_be_bytes()); + b.extend(h.to_be_bytes()); + b.extend([8, 6, 0, 0, 0]); + b +} + +/// A JPEG's start, saying these pixels. +fn jpeg(w: u16, h: u16) -> Vec { + let mut b = vec![0xFF, 0xD8, 0xFF, 0xC0, 0, 17, 8]; + b.extend(h.to_be_bytes()); + b.extend(w.to_be_bytes()); + b.extend([0; 12]); + b +} + +/// A drawing on one A3 sheet with one image of `bytes` placed on it: the drawing, the file's id and +/// the placement's. +fn pictured(bytes: &[u8]) -> (Drawing, u64, u64) { + let mut id_source = IdSource::seeded(5426); + let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape); + let mut d = Drawing::new("Pictured", "en", "Sheet 1", a3, None, &BTreeSet::new(), &mut id_source).unwrap(); + let (file, placed) = (d.allocate_id(&mut id_source).unwrap(), d.allocate_id(&mut id_source).unwrap()); + d.images.add([Arc::new(ImageFile::from_file(file, bytes).unwrap())]); + d.sheet_images.add([Arc::new(SheetImage { id: placed, sheet: d.sheets[0].id, rect_mm: RECT, image: file })]); + d.validate().unwrap(); + (d, file, placed) +} + +/// A copy of the drawing's first sheet, as a sheet of its own. +fn drawing_sheet_copy(d: &Drawing, id: u64) -> crate::drawing::Sheet { + crate::drawing::Sheet { id, name: "Sheet 2".into(), ..(*d.sheets[0]).clone() } +} + +fn file(d: &Drawing) -> Value { + serde_json::from_str(&d.to_json().unwrap()).unwrap() +} + +fn refused(d: &Drawing, edit: impl FnOnce(&mut Value)) -> String { + let mut v = file(d); + edit(&mut v); + Drawing::from_json(&v.to_string()).map_or_else(|e| e.to_string(), |_| "read".into()) +} + +#[test] +fn an_image_is_saved_with_its_bytes_and_reads_back_the_same() { + let bytes = png(640, 480); + let (d, image, placed) = pictured(&bytes); + let saved = d.to_json().unwrap(); + let read = Drawing::from_json(&saved).unwrap(); + assert_eq!(read, d); + assert_eq!(read.to_json().unwrap(), saved); + let found = read.images.by_id(image).unwrap(); + assert_eq!((found.format.as_str(), found.pixels), ("png", [640, 480])); + assert_eq!(base64_decode(&found.data).unwrap(), bytes); + assert_eq!(read.sheet_images.by_id(placed).map(|i| (i.rect_mm, i.image)), Some((RECT, image))); + assert!(read.images.by_id(placed).is_none() && read.sheet_images.by_id(image).is_none()); +} + +/// One file sits on two sheets and is saved once. Its bytes count once towards the caps, so a logo on +/// every sheet costs what one does. +#[test] +fn one_file_on_two_sheets_is_saved_once() { + let mut logo = png(10, 10); + logo.resize(1 << 20, 0); + let (mut d, image, _) = pictured(&logo); + let first = d.sheets[0].id; + let mut id_source = IdSource::seeded(4); + let second = d.allocate_id(&mut id_source).unwrap(); + let sheet = drawing_sheet_copy(&d, second); + d.sheets.push(Arc::new(sheet)); + for n in 0..20u64 { + let id = d.allocate_id(&mut id_source).unwrap(); + d.sheet_images.add([Arc::new(SheetImage { id, sheet: second, rect_mm: [n as f64, 0.0, n as f64 + 5.0, 5.0], image })]); + } + d.validate().unwrap(); + assert_eq!((d.images.len(), d.sheet_images.len()), (1, 21)); + let read = Drawing::from_json(&d.to_json().unwrap()).unwrap(); + assert_eq!(read, d); + assert!(d.to_json().unwrap().len() < 2 << 20, "the bytes are there once"); + assert_eq!(d.images_in_use(), BTreeSet::from([image])); + + // The first sheet's going leaves the file for the second's, and the second's takes it. + d.remove_sheet(first); + assert_eq!((d.images.len(), d.sheet_images.len()), (1, 20)); + d.validate().unwrap(); + d.remove_sheet(second); + assert!(d.images.is_empty() && d.sheet_images.is_empty()); +} + +/// A file goes with its last placement, and nothing is left to save. +#[test] +fn a_file_goes_with_its_last_placement() { + let (mut d, _, placed) = pictured(&png(1, 1)); + let (sheet, other) = (d.sheets[0].id, d.allocate_id(&mut IdSource::seeded(4)).unwrap()); + let empty = drawing_sheet_copy(&d, other); + d.sheets.push(Arc::new(empty)); + assert_eq!(d.on_sheet(sheet).images, [placed]); + assert!(!d.on_sheet(sheet).is_empty() && d.on_sheet(other).is_empty()); + assert_eq!(d.remove_sheet(sheet).images, [placed]); + assert!(d.images.is_empty() && d.sheet_images.is_empty()); + d.validate().unwrap(); + let v = file(&d); + assert!(v.get("images").is_none() && v.get("sheet_images").is_none(), "{v}"); + assert_eq!(Drawing::from_json(&v.to_string()).unwrap(), d, "an older drawing has neither"); +} + +#[test] +fn ids_stay_apart_across_files_and_placements() { + let (d, image, placed) = pictured(&png(1, 1)); + let taken = d.ids().collect::>(); + assert!(taken.contains(&image) && taken.contains(&placed)); + let mut twin = d.clone(); + Arc::make_mut(&mut twin.sheet_images[0]).id = image; + assert!(twin.validate().is_err_and(|e| e.to_string().contains("two objects"))); +} + +#[test] +fn the_caps_are_read_from_the_file_before_anything_decodes_it() { + let make = |b: &[u8]| ImageFile::from_file(1, b).map(|i| i.pixels).map_err(|e| e.to_string()); + assert_eq!(make(&png(8_000, 8_000)), Ok([8_000, 8_000])); + assert_eq!(make(&jpeg(8_000, 8_000)), Ok([8_000, 8_000])); + // The limits, one over, and sizes whose product would overflow 32 bits. + for (w, h) in [(8_001, 8_000), (64_000_001, 1), (1, 64_000_001), (65_536, 65_536), (u32::MAX, u32::MAX)] { + assert!(make(&png(w, h)).is_err_and(|e| e.contains("pixels")), "{w} by {h}"); + } + assert!(make(&jpeg(u16::MAX, u16::MAX)).is_err_and(|e| e.contains("pixels"))); + let not_images: [&[u8]; 6] = [b"", b"GIF89a", b"\x89PNG", &png(0, 5), &png(5, 0), &jpeg(0, 5)]; + for not_image in not_images { + assert!(make(not_image).is_err_and(|e| e.contains("PNG or JPEG")), "{not_image:?}"); + } + let mut full = png(10, 10); + full.resize(MAX_IMAGE_BYTES, 0); + assert_eq!(make(&full), Ok([10, 10])); + full.push(0); + assert!(make(&full).is_err_and(|e| e.contains("MiB"))); +} + +#[test] +fn a_file_that_lies_is_refused_on_reading() { + let (d, ..) = pictured(&png(10, 10)); + let with = |key: &'static str, value: Value| move |v: &mut Value| v["images"][0][key] = value; + assert!(refused(&d, with("pixels", json!([1, 1]))).contains("disagree")); + assert!(refused(&d, with("format", "jpeg".into())).contains("disagree")); + assert!(refused(&d, with("format", "gif".into())).contains("PNG or a JPEG")); + assert!(refused(&d, with("data", "!!!".into())).contains("base64")); + assert!(refused(&d, with("data", base64_encode(&png(9_000, 9_000)).into())).contains("pixels")); + assert!(refused(&d, with("data", "".into())).contains("PNG or JPEG")); + assert!(refused(&d, with("pixels", json!([0, 10]))).contains("pixels")); + assert!(refused(&d, with("pixels", json!([65_536, 65_536]))).contains("pixels")); + assert!(refused(&d, with("path", "C:/secret.png".into())).contains("path"), "an unknown field is damage"); +} + +/// A placement names a file and a sheet the drawing has, and a file nothing places isn't kept. +#[test] +fn a_placement_and_its_file_name_each_other() { + let (d, ..) = pictured(&png(10, 10)); + let placed = |key: &'static str, value: Value| move |v: &mut Value| v["sheet_images"][0][key] = value; + assert!(refused(&d, placed("sheet", ids::encode(1 << 41).into())).contains("sheet")); + assert!(refused(&d, placed("image", ids::encode(1 << 41).into())).contains("doesn't have")); + assert!(refused(&d, |v| v["sheet_images"] = json!([])).contains("nothing uses it")); + assert!(refused(&d, |v| v["images"] = json!([])).contains("doesn't have")); + assert!(refused(&d, placed("data", "AAAA".into())).contains("data"), "the file's bytes aren't the placement's"); +} + +#[test] +fn a_rectangle_is_on_paper_and_has_a_size() { + let (d, ..) = pictured(&png(10, 10)); + for rect in [ + [60.0, 20.0, 10.0, 45.0], + [10.0, 45.0, 60.0, 20.0], + [10.0, 20.0, 10.0, 45.0], + [10.0, 20.0, 60.0, 20.0], + [1e300, 20.0, 2e300, 45.0], + [f64::NAN; 4], + ] { + let mut bad = d.clone(); + Arc::make_mut(&mut bad.sheet_images[0]).rect_mm = rect; + assert!(bad.validate().is_err_and(|e| e.to_string().contains("rectangle")), "{rect:?}"); + } +} + +#[test] +fn a_drawings_images_keep_their_counts() { + let (d, image, placed) = pictured(&png(1, 1)); + // A file and something to use it, ids after the first ones. + let again = |d: &mut Drawing, n: u64, data: &str| { + let mut file = (*d.images[0]).clone(); + file.id = image + 2 * n; + file.data = data.into(); + let use_of = SheetImage { id: placed + 2 * n, sheet: d.sheets[0].id, rect_mm: RECT, image: file.id }; + d.images.add([Arc::new(file)]); + d.sheet_images.add([Arc::new(use_of)]); + }; + // One file's cap and the cap between them, checked on every edit from the text's length alone. + let mut big = d.clone(); + Arc::make_mut(&mut big.images[0]).data = "A".repeat(encoded(MAX_IMAGE_BYTES) + 1); + assert!(big.validate().is_err_and(|e| e.to_string().contains("its file"))); + let mut many = d.clone(); + let full = "A".repeat(encoded(MAX_IMAGE_BYTES)); + Arc::make_mut(&mut many.images[0]).data.clone_from(&full); + again(&mut many, 1, &full); + let room = encoded(MAX_IMAGES_BYTES) - 2 * full.len(); + again(&mut many, 2, &"A".repeat(room)); + many.validate().unwrap(); + again(&mut many, 3, "A"); + assert!(many.validate().is_err_and(|e| e.to_string().contains("between them"))); + let mut crowd = d.clone(); + (1..=MAX_IMAGES as u64).for_each(|n| again(&mut crowd, n, "AAAA")); + assert!(crowd.validate().is_err_and(|e| e.to_string().contains("at most"))); + let mut placements = d.clone(); + let logo = placements.sheet_images[0].clone(); + let copies = (1..=MAX_SHEET_IMAGES as u64).map(|n| Arc::new(SheetImage { id: placed + 2 * n, ..(*logo).clone() })); + placements.sheet_images.add(copies.collect::>()); + assert!(placements.validate().is_err_and(|e| e.to_string().contains("at most"))); + let mut twins = d.clone(); + let twin = twins.sheet_images[0].clone(); + twins.sheet_images.push(twin); + assert!(twins.validate().is_err()); +} diff --git a/crates/doc/src/drawing_tests.rs b/crates/doc/src/drawing_tests.rs index a67d3c19830..850585a4d36 100644 --- a/crates/doc/src/drawing_tests.rs +++ b/crates/doc/src/drawing_tests.rs @@ -88,7 +88,7 @@ fn plate() -> Drawing { d.add_dimensions([Arc::new(Dimension { id, view: front, kind, offset_mm: -10.0, text, decimals: 1, override_text, last_good: None })]); } let id = d.allocate_id(&mut id_source).unwrap(); - d.add_balloons([Arc::new(Balloon { id, view: front, edge: edge("F1:front|F1:top"), at: [60.0, 45.0] })]); + d.balloons.add([Arc::new(Balloon { id, view: front, edge: edge("F1:front|F1:top"), at: [60.0, 45.0] })]); d.validate().unwrap(); d } diff --git a/crates/engine/src/cmd/delete.rs b/crates/engine/src/cmd/delete.rs index 0e33609d113..cffa7f63fb7 100644 --- a/crates/engine/src/cmd/delete.rs +++ b/crates/engine/src/cmd/delete.rs @@ -66,7 +66,7 @@ fn delete_in_drawing(s: &mut Session, p: &Value, items: &[Sel]) -> Result views.insert(*object); } else if open.dimension(*object).is_some() { dimensions.push(*object); - } else if open.balloon(*object).is_some() { + } else if open.balloons.by_id(*object).is_some() { balloons.push(*object); } else { return Err(bad(cmd, format!("the drawing open has no view, dimension or balloon {}", ids::encode(*object)))); diff --git a/crates/engine/src/cmd/drawing_balloon.rs b/crates/engine/src/cmd/drawing_balloon.rs index f9b979b06dc..72adb8aeb94 100644 --- a/crates/engine/src/cmd/drawing_balloon.rs +++ b/crates/engine/src/cmd/drawing_balloon.rs @@ -71,7 +71,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let id = record.allocate_id(&mut s.ids).map_err(|e| bad(ADD, e.to_string()))?; let balloon = Balloon { id, view, edge, at: request.at }; s.edit_drawing(ADD, |d| { - d.add_balloons([Arc::new(balloon)]); + d.balloons.add([Arc::new(balloon)]); Ok(()) })?; answer(s, ADD, id) @@ -81,7 +81,7 @@ fn edit(s: &mut Session, p: &Value) -> Result { let request: EditParams = crate::schema::read(EDIT, p)?; let id = request.balloon.0; let changed = s.edit_drawing(EDIT, |d| { - let at = d.balloon_index(id).ok_or_else(|| bad(EDIT, format!("the drawing has no balloon {}", ids::encode(id))))?; + let at = d.balloons.index_of(id).ok_or_else(|| bad(EDIT, format!("the drawing has no balloon {}", ids::encode(id))))?; let Some(balloon) = d.balloons.get_mut(at).map(Arc::make_mut) else { return Ok(Vec::new()) }; let moved = request.set.at.filter(|place| *place != balloon.at); if let Some(place) = moved { @@ -101,7 +101,7 @@ fn inspect(s: &mut Session, p: &Value) -> Result { /// Balloon `id` of the open drawing as the model has it now. fn answer(s: &Session, cmd: &str, id: u64) -> Result { let d = s.drawing(cmd)?; - let balloon = d.balloon(id).ok_or_else(|| bad(cmd, format!("the drawing has no balloon {}", ids::encode(id))))?; + let balloon = d.balloons.by_id(id).ok_or_else(|| bad(cmd, format!("the drawing has no balloon {}", ids::encode(id))))?; let resolved = s.doc.resolve_balloons(&s.model, d, &[id]).map_err(|e| bad(cmd, e.to_string()))?; let r = resolved.into_iter().next().ok_or_else(|| bad(cmd, format!("balloon {} wasn't read", ids::encode(id))))?; let (status, why, candidates) = status_words(r.status); diff --git a/crates/engine/src/cmd/drawing_image.rs b/crates/engine/src/cmd/drawing_image.rs new file mode 100644 index 00000000000..a81f9277a22 --- /dev/null +++ b/crates/engine/src/cmd/drawing_image.rs @@ -0,0 +1,66 @@ +//! `drawing.image.add` (W38e, #5426): a PNG or JPEG on a sheet, its bytes saved in the design, once +//! however many places it sits. One undo step, and no model is evaluated. A placed image goes with its +//! sheet, and its file goes with the last of them. + +use std::sync::Arc; + +use serde_json::Value; +use solidcraft_doc::drawing::image::{ImageFile, MAX_IMAGE_BYTES, SheetImage}; +use solidcraft_doc::ids; + +use super::CommandSpec; +use crate::params::bad; +use crate::schema::drawing_image::{AddParams, AddResult}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{EngineError, Result, Session}; + +const ADD: &str = "drawing.image.add"; +const ADD_CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(ADD, "Add Image", crate::checked!("drawing.image.add", add)) + .icon("new") + .in_drawing() + .doc_only() + .contract(&ADD_CONTRACT) + .output(output_schema_for::) + .params( + "sheet: id or name; file: a PNG or JPEG, at most 4 MiB and 64 million pixels, read from the file's header before anything decodes it; \ + rect_mm: [x0, y0, x1, y1] from the sheet's lower-left corner → {image, format, pixels}. Its bytes are saved in the design, once however many places it \ + sits, and its path isn't. image is the placement's id. At most 9 MiB of image files a drawing. One undo step; no model is evaluated.", + )]; + +fn add(s: &mut Session, p: &Value) -> Result { + let request: AddParams = crate::schema::read(ADD, p)?; + let record = s.drawing(ADD)?.clone(); + let sheet = crate::drawing_scene::sheet_id(&record, &request.sheet, ADD)?; + let file = request.file.as_str(); + if file.trim().is_empty() || file.len() >= 4096 { + return Err(bad(ADD, "`file` is the path of a PNG or JPEG")); + } + let bytes = solidcraft_io::vfs::read(file, MAX_IMAGE_BYTES).map_err(|e| EngineError::Other(format!("{file}: {e}")))?; + let (id, new_file) = (record.allocate_id(&mut s.ids), record.allocate_id(&mut s.ids)); + let id = id.map_err(|e| bad(ADD, e.to_string()))?; + let new_file = new_file.map_err(|e| bad(ADD, e.to_string()))?; + let image = ImageFile::from_file(new_file, &bytes).map_err(|e| bad(ADD, format!("{file}: {e}")))?; + let reply = AddResult { image: ids::encode(id), format: image.format.clone(), pixels: image.pixels, param_warnings: Vec::new() }; + let rect_mm = request.rect_mm; + s.edit_drawing(ADD, |d| { + // The same bytes are the same file: a logo added to each sheet is stored once. + let shown = match d.images.iter().find(|known| known.data == image.data) { + Some(known) => known.id, + None => { + d.images.add([Arc::new(image)]); + new_file + } + }; + d.sheet_images.add([Arc::new(SheetImage { id, sheet, rect_mm, image: shown })]); + // Every drawing saved opens again, so one that couldn't be saved is refused here, not at the save. + d.to_json().map_err(|e| bad(ADD, e.to_string()))?; + Ok(()) + })?; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + +#[cfg(test)] +#[path = "drawing_image_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/drawing_image_tests.rs b/crates/engine/src/cmd/drawing_image_tests.rs new file mode 100644 index 00000000000..3b40f2ba61f --- /dev/null +++ b/crates/engine/src/cmd/drawing_image_tests.rs @@ -0,0 +1,205 @@ +use std::path::PathBuf; + +use serde_json::json; +use solidcraft_doc::canvas::base64_decode; +use solidcraft_geom::paper::MAX_IMAGE_PIXELS; +use solidcraft_io::vfs::{self, PathScope}; + +use super::*; +use crate::schema::tests::conforms; + +const RECT: [f64; 4] = [10.0, 20.0, 60.0, 45.0]; + +/// A PNG's header, saying these pixels. +fn png(w: u32, h: u32) -> Vec { + let mut b = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); + b.extend(w.to_be_bytes()); + b.extend(h.to_be_bytes()); + b.extend([8, 6, 0, 0, 0]); + b +} + +/// A folder of this test's own, holding `bytes` as `logo.png`: the folder and the file. +fn on_disk(test: &str, bytes: &[u8]) -> (PathBuf, String) { + let dir = std::env::temp_dir().join(format!("solidcraft-drawing-image-{}-{test}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("logo.png"); + std::fs::write(&file, bytes).unwrap(); + (dir, file.to_string_lossy().into_owned()) +} + +/// A session with a box and a drawing of it, open, on the sheet it returns. +fn drawing() -> (Session, String) { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 80, "width": 40, "height": 30})).unwrap(); + s.execute("drawing.create", &json!({})).unwrap(); + let sheet = ids::encode(s.drawing("test").unwrap().sheets[0].id); + (s, sheet) +} + +fn refused(s: &mut Session, p: Value) -> String { + s.execute(ADD, &p).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("accepted: {p}")) +} + +#[test] +fn an_image_is_read_saved_without_its_path_and_one_undo_step() { + let bytes = png(640, 480); + let (dir, file) = on_disk("saved", &bytes); + let (mut s, sheet) = drawing(); + let reply = s.execute(ADD, &json!({"sheet": sheet, "file": file, "rect_mm": RECT})).unwrap(); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}"); + assert_eq!((&reply["format"], &reply["pixels"]), (&json!("png"), &json!([640, 480])), "{reply}"); + + // The original file is gone: the design has its bytes, and doesn't know where they came from. + std::fs::remove_dir_all(&dir).unwrap(); + let record = s.drawing("test").unwrap().clone(); + let id = ids::decode(reply["image"].as_str().unwrap()).unwrap(); + assert_eq!(base64_decode(&record.images.by_id(record.sheet_images.by_id(id).unwrap().image).unwrap().data).unwrap(), bytes); + assert!(!record.to_json().unwrap().contains("logo")); + + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.drawing("test").unwrap().images.is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.drawing("test").unwrap().sheet_images.by_id(id).is_some()); +} + +/// The same logo on two sheets is one file, and it goes when the last of them goes. Other bytes are +/// another file. A sheet's delete takes its placements, and the file stays for the other sheet. +#[test] +fn the_same_bytes_are_one_file_on_each_sheet() { + let (dir, file) = on_disk("logo", &png(32, 32)); + let (other_dir, other) = on_disk("logo-other", &png(64, 64)); + let (mut s, first) = drawing(); + s.execute("drawing.sheet.add", &json!({})).unwrap(); + let second = ids::encode(s.drawing("test").unwrap().sheets[1].id); + let add = |s: &mut Session, sheet: &str, file: &str| s.execute(ADD, &json!({"sheet": sheet, "file": file, "rect_mm": RECT})).unwrap(); + let a = add(&mut s, &first, &file); + let b = add(&mut s, &second, &file); + assert_ne!(a["image"], b["image"], "each place has its own id"); + assert_eq!(b["pixels"], json!([32, 32])); + let d = s.drawing("test").unwrap().clone(); + assert_eq!((d.images.len(), d.sheet_images.len()), (1, 2), "stored once"); + assert_eq!(d.sheet_images[0].image, d.sheet_images[1].image); + add(&mut s, &first, &other); + assert_eq!(s.drawing("test").unwrap().images.len(), 2, "other bytes are another file"); + + let why = s.execute("drawing.sheet.delete", &json!({"sheet": first})).unwrap_err().to_string(); + assert!(why.contains("2 images"), "a sheet with images on it says so: {why}"); + s.execute("drawing.sheet.delete", &json!({"sheet": first, "contents": "delete"})).unwrap(); + let left = s.drawing("test").unwrap(); + assert_eq!((left.images.len(), left.sheet_images.len()), (1, 1), "the other sheet still uses one file"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.drawing("test").unwrap().images.len(), 2, "an undo brings it back"); + s.execute("edit.redo", &json!({})).unwrap(); + let again = s.drawing("test").unwrap().to_json().unwrap(); + assert!(solidcraft_doc::drawing::Drawing::from_json(&again).is_ok()); + for d in [dir, other_dir] { + std::fs::remove_dir_all(d).unwrap(); + } +} + +#[test] +fn what_isnt_an_image_or_breaks_a_cap_is_refused_and_changes_nothing() { + let (dir, bomb) = on_disk("refused", &png(100_000, 100_000)); + let (mut s, sheet) = drawing(); + let before = s.drawing("test").unwrap().clone(); + let side = (MAX_IMAGE_PIXELS as f64).sqrt() as u32 + 1; + let text = dir.join("words.png"); + std::fs::write(&text, b"not a picture").unwrap(); + let big = dir.join("big.png"); + std::fs::write(&big, vec![0; MAX_IMAGE_BYTES + 1]).unwrap(); + let over = dir.join("over.png"); + std::fs::write(&over, png(side, side)).unwrap(); + let path = |p: &PathBuf| p.to_string_lossy().into_owned(); + let dir_text = path(&dir); + let missing = path(&dir.join("missing.png")); + let files: [&str; 10] = [&bomb, &path(&text), &path(&big), &path(&over), &dir_text, &missing, "", " ", "a\0b", &"x".repeat(4096)]; + for file in files { + let why = refused(&mut s, json!({"sheet": sheet, "file": file, "rect_mm": RECT})); + assert!(!why.is_empty(), "{file:?}"); + } + for file in ["", " "] { + let why = refused(&mut s, json!({"sheet": sheet, "file": file, "rect_mm": RECT})); + assert!(why.contains("path of a PNG or JPEG"), "{file:?} names no file to look for: {why}"); + } + let (good_dir, good) = on_disk("refused-good", &png(4, 4)); + assert!(refused(&mut s, json!({"sheet": "no such sheet", "file": good, "rect_mm": RECT})).contains("sheet")); + for rect in [[60, 20, 10, 45], [10, 20, 10, 45], [0, 0, 1_000_000_000, 1]] { + assert!(refused(&mut s, json!({"sheet": sheet, "file": good, "rect_mm": rect})).contains("rectangle"), "{rect:?}"); + } + assert_eq!(**s.drawing("test").unwrap(), *before); + for d in [dir, good_dir] { + std::fs::remove_dir_all(d).unwrap(); + } +} + +/// A file outside the folders an agent may read is refused by the same check every other read takes. +#[test] +fn a_file_outside_the_allowed_folders_is_refused() { + let (dir, file) = on_disk("scope", &png(4, 4)); + let (allowed, _) = on_disk("scope-allowed", &png(4, 4)); + let (mut s, sheet) = drawing(); + let p = json!({"sheet": sheet, "file": file, "rect_mm": RECT}); + let answer = vfs::scoped(Some(PathScope::new([allowed.clone()])), || s.execute(ADD, &p)); + assert!(answer.is_err(), "{answer:?}"); + assert!(s.drawing("test").unwrap().images.is_empty()); + for d in [dir, allowed] { + std::fs::remove_dir_all(d).unwrap(); + } +} + +/// Under the images' own cap, with another tool's properties filling the rest of the record: the +/// save's limit is what refuses the image, and the drawing as it stands still saves. +#[test] +fn an_image_that_would_stop_the_drawing_saving_is_refused() { + let sized = |w: u32| { + let mut file = png(w, 4); + file.resize(MAX_IMAGE_BYTES, 0); + file + }; + let (dir, file) = on_disk("save-a", &sized(4)); + let (dir_b, file_b) = on_disk("save-b", &sized(5)); + let (mut s, sheet) = drawing(); + s.edit_drawing("test", |d| { + Arc::make_mut(&mut d.properties).0.insert("com.example".into(), json!({"text": "x".repeat(6 << 20)})); + Ok(()) + }) + .unwrap(); + let p = |file: &str| json!({"sheet": sheet, "file": file, "rect_mm": RECT}); + s.execute(ADD, &p(&file)).unwrap(); + assert!(refused(&mut s, p(&file_b)).contains("too large to save")); + s.drawing("test").unwrap().to_json().unwrap(); + for d in [dir, dir_b] { + std::fs::remove_dir_all(d).unwrap(); + } +} + +/// A drawing that couldn't be saved again is refused when the image is added, not at the save. +#[test] +fn an_image_a_drawing_has_no_room_for_is_refused() { + let mut full = png(4, 4); + full.resize(MAX_IMAGE_BYTES, 0); + let (dir, file) = on_disk("room", &full); + let (mut s, sheet) = drawing(); + let (dir_b, file_b) = on_disk("room-b", &{ + let mut b = png(5, 4); + b.resize(MAX_IMAGE_BYTES, 0); + b + }); + let (dir_c, file_c) = on_disk("room-c", &{ + let mut c = png(6, 4); + c.resize(MAX_IMAGE_BYTES / 2, 0); + c + }); + let p = |file: &str| json!({"sheet": sheet, "file": file, "rect_mm": RECT}); + s.execute(ADD, &p(&file)).unwrap(); + s.execute(ADD, &p(&file_b)).unwrap(); + s.execute(ADD, &p(&file)).unwrap(); + assert!(refused(&mut s, p(&file_c)).contains("between them"), "the same file again costs nothing; a third doesn't fit"); + s.drawing("test").unwrap().to_json().unwrap(); + for d in [dir_b, dir_c] { + std::fs::remove_dir_all(d).unwrap(); + } + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/engine/src/cmd/drawing_sheet.rs b/crates/engine/src/cmd/drawing_sheet.rs index f6e68bcf548..1084353ee98 100644 --- a/crates/engine/src/cmd/drawing_sheet.rs +++ b/crates/engine/src/cmd/drawing_sheet.rs @@ -67,7 +67,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .output(output_schema_for::) .params( "sheet: id or name (a drawing keeps at least one); contents?: delete, to delete the views on it, their dimensions and \ - balloons with it (without it a sheet with anything on it is refused, naming what) → the drawing's sheets. One undo step.", + balloons, and the images on it, with it (without it a sheet with anything on it is refused, naming what) → the drawing's sheets. One undo step.", ), ]; @@ -98,7 +98,10 @@ fn listed(on: &OnSheet) -> String { (!list.is_empty()).then(|| format!("{} {what}{s} ({})", list.len(), named(list))) }; let mut kinds: Vec = - [kind("view", &on.views), kind("dimension", &on.dimensions), kind("balloon", &on.balloons)].into_iter().flatten().collect(); + [kind("view", &on.views), kind("dimension", &on.dimensions), kind("balloon", &on.balloons), kind("image", &on.images)] + .into_iter() + .flatten() + .collect(); let last = kinds.pop().unwrap_or_default(); if kinds.is_empty() { last } else { format!("{} and {last}", kinds.join(", ")) } } diff --git a/crates/engine/src/cmd/drawing_tests.rs b/crates/engine/src/cmd/drawing_tests.rs index 3d48896159e..0e73a7e1c54 100644 --- a/crates/engine/src/cmd/drawing_tests.rs +++ b/crates/engine/src/cmd/drawing_tests.rs @@ -536,7 +536,7 @@ fn inspect_lists_each_sheets_views_in_order() { })]); // Inspect only lists it, so the part it numbers needn't be in the design. let edge = ModelEdge { body: "Block".into(), origin_feature: s.doc.features[0].id, name: "edge".into(), path: vec![1] }; - d.add_balloons([Arc::new(Balloon { id: balloon, view: right, edge, at: [20.0, 20.0] })]); + d.balloons.add([Arc::new(Balloon { id: balloon, view: right, edge, at: [20.0, 20.0] })]); d.validate().unwrap(); s.doc_mut().put_drawing(Arc::new(d)); let [front_id, right_id, top_id, left_id] = [front, right, top, left].map(ids::encode); diff --git a/crates/engine/src/cmd/drawing_view.rs b/crates/engine/src/cmd/drawing_view.rs index 26759462c5c..450f6679b1e 100644 --- a/crates/engine/src/cmd/drawing_view.rs +++ b/crates/engine/src/cmd/drawing_view.rs @@ -619,11 +619,11 @@ fn copy_to_sheet(s: &mut Session, p: &Value) -> Result { .iter() .zip(&balloon_copies) .filter_map(|(old, new)| { - let original = d.balloon(*old)?; + let original = d.balloons.by_id(*old)?; Some(Arc::new(Balloon { id: *new, view: copy_of(original.view)?, ..original.clone() })) }) .collect(); - d.add_balloons(copied); + d.balloons.add(copied); Ok(sheet) })?; let first = copies.first().copied().unwrap_or_default(); diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 06e21a23670..9325c607fd2 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -35,6 +35,7 @@ mod drawing; mod drawing_balloon; mod drawing_dimension; mod drawing_export; +mod drawing_image; mod drawing_revision; mod drawing_scene; mod drawing_sheet; @@ -395,6 +396,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(view_dxf::COMMANDS.iter()); v.extend(drawing::COMMANDS.iter()); v.extend(drawing_balloon::COMMANDS.iter()); + v.extend(drawing_image::COMMANDS.iter()); v.extend(drawing_dimension::COMMANDS.iter()); v.extend(drawing_export::COMMANDS.iter()); v.extend(drawing_revision::COMMANDS.iter()); diff --git a/crates/engine/src/schema/drawing_image.rs b/crates/engine/src/schema/drawing_image.rs new file mode 100644 index 00000000000..cb93c575980 --- /dev/null +++ b/crates/engine/src/schema/drawing_image.rs @@ -0,0 +1,34 @@ +//! Contracts and result types for the commands in `cmd/drawing_image.rs` (#5426, W38e). + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::drawing_sheet::sheet_ref; + +/// What `drawing.image.add` takes. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(deny_unknown_fields)] +pub struct AddParams { + /// The sheet it goes on, by id or name. + #[serde(deserialize_with = "sheet_ref")] + pub sheet: String, + /// The PNG or JPEG file to read. Its bytes are saved in the design and its path isn't. + pub file: String, + /// Where it sits, `[x0, y0, x1, y1]` in millimetres from the sheet's lower-left corner. + pub rect_mm: [f64; 4], +} + +/// What `drawing.image.add` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AddResult { + /// The placement's id. + pub image: String, + /// `png` or `jpeg`. + pub format: String, + /// Its width and height in pixels. + pub pixels: [u32; 2], + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 4857f7eb387..1ef714d46aa 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -60,6 +60,7 @@ pub mod construct; pub mod drawing_balloon; pub mod drawing_dimension; pub mod drawing_export; +pub mod drawing_image; pub mod drawing_revision; pub mod drawing_scene; pub mod drawing_sheet; diff --git a/crates/geom/src/paper.rs b/crates/geom/src/paper.rs index 00b9cd692ce..d2e9463bb7d 100644 --- a/crates/geom/src/paper.rs +++ b/crates/geom/src/paper.rs @@ -72,6 +72,8 @@ pub const MAX_DASH_MM: f64 = 1000.0; pub const MAX_DASHES: f64 = 1e6; /// The longest side a sheet may have, in millimetres. pub const MAX_SIDE_MM: f64 = 5000.0; +/// The most pixels an image on paper may have: 8,000 by 8,000, 256 MB once decoded. +pub const MAX_IMAGE_PIXELS: u64 = 64_000_000; /// Groups, items, loops and curve pieces a scene may hold in all. pub const MAX_RECORDS: usize = 100_000; /// The largest coordinate and radius either way, in millimetres: twenty times the longest side. diff --git a/crates/io/src/design/drawing_tests.rs b/crates/io/src/design/drawing_tests.rs index 5f7a966d2c2..cd32e01dd9f 100644 --- a/crates/io/src/design/drawing_tests.rs +++ b/crates/io/src/design/drawing_tests.rs @@ -2,6 +2,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::io::{Cursor, Write}; use serde_json::{Value, json}; +use solidcraft_doc::drawing::image::{ImageFile, SheetImage}; use solidcraft_doc::drawing::{MAX_DRAWINGS, Source}; use solidcraft_doc::format::DRAWING; use solidcraft_doc::ids::IdSource; @@ -80,6 +81,36 @@ fn a_designs_drawings_round_trip_through_both_forms_byte_for_byte() { assert_eq!(write_design(&read), json, "the plain form too"); } +/// An image on a sheet travels in its drawing's record through both forms, and an entry whose file +/// isn't what its record says refuses the whole design. +#[test] +fn an_image_on_a_sheet_round_trips_and_a_lying_one_is_refused() { + let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); + header.extend(640u32.to_be_bytes()); + header.extend(480u32.to_be_bytes()); + header.extend([8, 6, 0, 0, 0]); + let mut doc = plate(); + let mut d = (*doc.drawings[0]).clone(); + let mut ids = IdSource::seeded(5426); + let (file, placed) = (d.allocate_id(&mut ids).unwrap(), d.allocate_id(&mut ids).unwrap()); + d.images.add([Arc::new(ImageFile::from_file(file, &header).unwrap())]); + d.sheet_images.add([Arc::new(SheetImage { id: placed, sheet: d.sheets[0].id, rect_mm: [10.0, 20.0, 60.0, 45.0], image: file })]); + doc.drawings[0] = Arc::new(d); + let bytes = write_design_container(&doc).unwrap(); + let read = read_design(&bytes).unwrap(); + assert_eq!(read.drawings, doc.drawings); + assert_eq!(write_design_container(&read).unwrap(), bytes, "save, open, save: the same bytes"); + let json = write_design(&doc); + assert_eq!(read_design(&json).unwrap().drawings, doc.drawings, "the plain form too"); + + let mut inside = parts(&bytes); + let name = entry(doc.drawings[0].id); + let mut record: Value = serde_json::from_slice(&inside[&name]).unwrap(); + record["images"][0]["pixels"] = json!([1, 1]); + inside.insert(name, record.to_string().into_bytes()); + assert!(read_design(&container(&inside)).is_err()); +} + /// What a container refuses in its drawings, each time the whole design: an entry under /// `drawings/` that isn't a drawing's, one whose record has another id, a damaged drawing, one a /// newer build saved, drawings inline in `document.json` beside the entries, and more entries than