Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions assets/locales/pending/drawing-image.json
Original file line number Diff line number Diff line change
@@ -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": "添加图像"
}
}
63 changes: 45 additions & 18 deletions crates/doc/src/drawing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
//!
Expand All @@ -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;
Expand All @@ -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.
Expand Down Expand Up @@ -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<Arc<Dimension>>,
/// By id ([`Drawing::add_balloons`]), as the dimensions are.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub balloons: Vec<Arc<Balloon>>,
#[serde(default, skip_serializing_if = "ById::is_empty")]
pub balloons: ById<Balloon>,
/// The image files, once each however many places they sit.
#[serde(default, skip_serializing_if = "ById::is_empty")]
pub images: ById<ImageFile>,
/// Where they sit on the sheets.
#[serde(default, skip_serializing_if = "ById::is_empty")]
pub sheet_images: ById<SheetImage>,
/// 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<RevisionRecord>,
Expand Down Expand Up @@ -213,12 +223,14 @@ pub struct OnSheet {
pub dimensions: Vec<u64>,
/// The balloons in its views.
pub balloons: Vec<u64>,
/// The images placed on it.
pub images: Vec<u64>,
}

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()
}
}

Expand Down Expand Up @@ -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()?;
Expand All @@ -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 })
}

Expand Down Expand Up @@ -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<u64>) -> 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
Expand All @@ -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
Expand All @@ -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())
}

Expand Down Expand Up @@ -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.
Expand Down
33 changes: 9 additions & 24 deletions crates/doc/src/drawing/balloon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<Item = Arc<Balloon>>) {
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<usize> {
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<()> {
Expand Down Expand Up @@ -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 => {
Expand Down
5 changes: 3 additions & 2 deletions crates/doc/src/drawing/balloon_tests.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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<u64> = 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();
Expand Down
90 changes: 90 additions & 0 deletions crates/doc/src/drawing/by_id.rs
Original file line number Diff line number Diff line change
@@ -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<T>(Vec<Arc<T>>);

impl<T> Default for ById<T> {
fn default() -> Self {
ById(Vec::new())
}
}

impl<T> Deref for ById<T> {
type Target = Vec<Arc<T>>;

fn deref(&self) -> &Self::Target {
&self.0
}
}

impl<T> DerefMut for ById<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}

impl<'a, T> IntoIterator for &'a ById<T> {
type Item = &'a Arc<T>;
type IntoIter = std::slice::Iter<'a, Arc<T>>;

fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}

impl<T> ById<T> {
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}

impl<T: Record> ById<T> {
/// Adds `more`, each where its id puts it.
pub fn add(&mut self, more: impl IntoIterator<Item = Arc<T>>) {
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<usize> {
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;
Loading