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
15 changes: 8 additions & 7 deletions crates/doc/src/drawing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,12 @@ use crate::ids::{self, IdSource};
use crate::{DocError, Metadata, Result, expr};

pub mod balloon;
pub mod by_id;
pub mod dimension;
pub mod view;

use balloon::Balloon;
use by_id::ById;
use dimension::Dimension;
use view::View;

Expand Down Expand Up @@ -124,9 +126,8 @@ 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>,
/// 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 @@ -257,7 +258,7 @@ impl Drawing {
sheets: vec![Arc::new(first)],
views: Vec::new(),
dimensions: Vec::new(),
balloons: Vec::new(),
balloons: ById::default(),
revisions: Arc::default(),
};
drawing.validate()?;
Expand All @@ -281,10 +282,10 @@ 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.validate().map_err(damaged)?;
Ok(Drawing { format: DRAWING.format_string(DRAWING.current()), format_pending: DRAWING.pending_names(), ..d })
}
Expand Down Expand Up @@ -320,7 +321,7 @@ 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
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;
50 changes: 50 additions & 0 deletions crates/doc/src/drawing/by_id_tests.rs
Original file line number Diff line number Diff line change
@@ -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<Thing> {
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::<Vec<_>>(), [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::<Thing>::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::<ById<Thing>>(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}");
}
2 changes: 1 addition & 1 deletion crates/doc/src/drawing_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ fn delete_in_drawing(s: &mut Session, p: &Value, items: &[Sel]) -> Result<Value>
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))));
Expand Down
6 changes: 3 additions & 3 deletions crates/engine/src/cmd/drawing_balloon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
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)
Expand All @@ -81,7 +81,7 @@ fn edit(s: &mut Session, p: &Value) -> Result<Value> {
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 {
Expand All @@ -101,7 +101,7 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
/// Balloon `id` of the open drawing as the model has it now.
fn answer(s: &Session, cmd: &str, id: u64) -> Result<Value> {
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);
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/drawing_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/src/cmd/drawing_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -619,11 +619,11 @@ fn copy_to_sheet(s: &mut Session, p: &Value) -> Result<Value> {
.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();
Expand Down