feat(drawing): store bounded sheet-sketch records (#7082)
First data-only W38a increment on the existing embedded drawing receiver. Native doc library, strict scoped Clippy and wasm pass; the actual full-repository gate result remains explicit in draft PR #7608. No editor, kernel or CI changes.
This commit is contained in:
1 parent
e0cd0c982b
commit
2deda2276d
5 files changed
+564
-2
No files matched your search
@@ -33,6 +33,10 @@
|
||||
//! the family's format check, every number in range, the upgrade, the typed record, then
|
||||
//! [`Drawing::validate`]; [`Drawing::from_value`] the same from the format check on.
|
||||
|
||||
mod sketch;
|
||||
|
||||
pub use sketch::{MAX_SHEET_SKETCHES, SheetSketch};
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -88,6 +92,9 @@ pub struct Drawing {
|
||||
pub language: String,
|
||||
/// In order, each behind its own `Arc`, so an undo step shares every sheet it didn't change.
|
||||
pub sheets: Vec<Arc<Sheet>>,
|
||||
/// Authored sheet sketches, ordered by id on disk, with their original paper-mm payload.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", serialize_with = "sketch::serialize_sorted")]
|
||||
pub sketches: Vec<Arc<SheetSketch>>,
|
||||
}
|
||||
|
||||
/// A design the drawing draws: the design the drawing is in. Views and sheets name it by its id,
|
||||
@@ -182,6 +189,7 @@ impl Drawing {
|
||||
units: Units::default(),
|
||||
language: language.into(),
|
||||
sheets: vec![Arc::new(first)],
|
||||
sketches: Vec::new(),
|
||||
};
|
||||
drawing.validate()?;
|
||||
Ok(drawing)
|
||||
@@ -203,7 +211,9 @@ impl Drawing {
|
||||
let (version, applied) = DRAWING.take_version(&mut v)?;
|
||||
DRAWING.check_numbers(&v, "properties")?;
|
||||
DRAWING.upgrade(&mut v, version, applied.as_deref())?;
|
||||
let d: Drawing = serde_json::from_value(v).map_err(damaged)?;
|
||||
sketch::check_raw(&v).map_err(damaged)?;
|
||||
let mut d: Drawing = serde_json::from_value(v).map_err(damaged)?;
|
||||
d.sketches.sort_by_key(|record| record.id);
|
||||
d.validate().map_err(damaged)?;
|
||||
Ok(Drawing { format: DRAWING.format_string(DRAWING.current()), format_pending: DRAWING.pending_names(), ..d })
|
||||
}
|
||||
@@ -213,6 +223,9 @@ impl Drawing {
|
||||
/// properties are kept as they came, and indenting them can make a drawing that read in
|
||||
/// under the limit save over it.
|
||||
pub fn to_json(&self) -> Result<String> {
|
||||
if !self.sketches.is_empty() {
|
||||
self.validate()?;
|
||||
}
|
||||
let text = serde_json::to_string_pretty(self).map_err(|e| DocError::Invalid(format!("drawing not saved: {e}")))?;
|
||||
require(text.len() <= MAX_DRAWING_BYTES, || format!("drawing too large to save (at most {} MiB)", MAX_DRAWING_BYTES >> 20))?;
|
||||
Ok(text)
|
||||
@@ -224,10 +237,18 @@ impl Drawing {
|
||||
id_source.next(&self.ids().collect())
|
||||
}
|
||||
|
||||
/// Read only this drawing's sketch. Identical local sketch ids in another drawing are unrelated.
|
||||
pub fn sheet_sketch(&self, id: u64) -> Option<&Arc<SheetSketch>> {
|
||||
self.sketches.iter().find(|record| record.id == id)
|
||||
}
|
||||
|
||||
/// Every object's id, of every kind: what a new id must differ from. Each later kind adds its
|
||||
/// own here.
|
||||
fn ids(&self) -> impl Iterator<Item = u64> {
|
||||
std::iter::once(self.id).chain(self.sources.iter().map(|s| s.id)).chain(self.sheets.iter().map(|s| s.id))
|
||||
std::iter::once(self.id)
|
||||
.chain(self.sources.iter().map(|s| s.id))
|
||||
.chain(self.sheets.iter().map(|s| s.id))
|
||||
.chain(self.sketches.iter().map(|s| s.id))
|
||||
}
|
||||
|
||||
/// The record's rules (the module's notes): what reading a drawing checks, and what every edit
|
||||
@@ -244,6 +265,7 @@ impl Drawing {
|
||||
let length = unit.trim() == unit.as_str() && expr::unit_info(unit).is_some_and(|(kind, _)| kind == expr::Kind::Length);
|
||||
require(length, || "the drawing's unit is not a length unit (such as `mm` or `in`)".into())?;
|
||||
}
|
||||
sketch::check_drawing(self)?;
|
||||
let mut seen = BTreeSet::new();
|
||||
for id in self.ids() {
|
||||
require(id != 0, || "an object has the id 0, which is never one".into())?;
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Optional drawing-owned sheet sketches (#7082), with drawing-global ids, explicit sheet
|
||||
//! ownership and the original Sketch payload in paper millimetres. Empty/absent sketches keep
|
||||
//! the old record shape. No migration: old drawings have no sketches; serde supplies an empty
|
||||
//! list. A build without this pending change refuses its newer format instead of dropping it.
|
||||
@@ -0,0 +1,228 @@
|
||||
//! W38a's first record slice: sheet-owned, paper-mm geometry, with no model evaluation.
|
||||
//! The Sketch payload stays the shared type. Links, patterns and offsets await the
|
||||
//! receiver-aware store: refusing them here is explicit, never silent data loss.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize, Serializer};
|
||||
use serde_json::Value;
|
||||
use solidcraft_geom::Vec2;
|
||||
use solidcraft_sketch::{ConstraintKind, CurveKind, MAX_CONSTRAINTS, MAX_COORD, MAX_CURVES, MAX_POINTS, MAX_SPLINE_POINTS, Sketch};
|
||||
|
||||
use super::{Drawing, MAX_DRAWING_BYTES, check_name, require};
|
||||
use crate::{DocError, Result};
|
||||
|
||||
/// Maximum sheet sketches in one drawing; independently of the number of sheets.
|
||||
pub const MAX_SHEET_SKETCHES: usize = 1000;
|
||||
// One drawing cannot multiply the shared sketch array caps by its sketch count.
|
||||
const MAX_ENTITIES: usize = MAX_POINTS + MAX_CURVES + MAX_CONSTRAINTS;
|
||||
const MAX_VALIDATION_WORK: usize = 2_000_000;
|
||||
const MAX_STORED_TEXT_BYTES: usize = 4096;
|
||||
const MAX_LOCAL_ID_BYTES: usize = 512;
|
||||
const AUXILIARY: [&str; 5] = ["links", "patterns", "offsets", "freeform_offsets", "wires"];
|
||||
|
||||
/// Authored sheet geometry. Points and lengths are paper XY millimetres, regardless
|
||||
/// of the drawing's display units. This record has no view scale or source path.
|
||||
/// Expressions are retained verbatim; interpreting them is the later read-only store's job.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SheetSketch {
|
||||
#[serde(with = "crate::ids")]
|
||||
pub id: u64,
|
||||
#[serde(with = "crate::ids")]
|
||||
pub sheet: u64,
|
||||
pub name: String,
|
||||
pub sketch: Sketch,
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> DocError {
|
||||
DocError::Invalid(format!("sheet sketch: {}", message.into()))
|
||||
}
|
||||
|
||||
fn charge(used: &mut usize, amount: usize, limit: usize, what: &str) -> Result<()> {
|
||||
*used = used.checked_add(amount).filter(|n| *n <= limit).ok_or_else(|| invalid(format!("{what} limit exceeded")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn text(s: &str) -> Result<()> {
|
||||
require(!s.trim().is_empty() && s.len() <= MAX_STORED_TEXT_BYTES && !s.chars().any(char::is_control), || {
|
||||
"sheet sketch expression is empty, too long or contains control characters".into()
|
||||
})
|
||||
}
|
||||
|
||||
fn position(p: Vec2) -> Result<()> {
|
||||
require(p.is_finite() && p.x.abs() < MAX_COORD && p.y.abs() < MAX_COORD, || "sheet sketch point is out of range".into())
|
||||
}
|
||||
|
||||
fn identity<'a>(seen: &mut BTreeSet<&'a str>, id: &'a str) -> Result<()> {
|
||||
require(!id.trim().is_empty() && id.len() <= MAX_LOCAL_ID_BYTES && !id.chars().any(char::is_control), || {
|
||||
"sheet sketch local id is empty, too long or contains control characters".into()
|
||||
})?;
|
||||
require(seen.insert(id), || "sheet sketch local ids must be unique".into())
|
||||
}
|
||||
|
||||
/// Every collection is bounded before serde allocates the typed sketch payload.
|
||||
/// A raw JSON Value already exists here; the drawing reader separately caps encoded bytes.
|
||||
pub(super) fn check_raw(value: &Value) -> Result<()> {
|
||||
let Some(records) = value.get("sketches") else { return Ok(()) };
|
||||
let records = records.as_array().ok_or_else(|| invalid("sketches must be an array"))?;
|
||||
require(records.len() <= MAX_SHEET_SKETCHES, || "too many sheet sketches".into())?;
|
||||
let mut total = 0;
|
||||
let mut nodes = 0;
|
||||
let mut bytes = 0;
|
||||
for record in records {
|
||||
raw_tree(record, 0, &mut nodes, &mut bytes)?;
|
||||
let Some(sketch) = record.get("sketch") else { continue };
|
||||
for (key, limit) in [("points", MAX_POINTS), ("curves", MAX_CURVES), ("constraints", MAX_CONSTRAINTS)] {
|
||||
if let Some(array) = sketch.get(key) {
|
||||
let array = array.as_array().ok_or_else(|| invalid(format!("{key} must be an array")))?;
|
||||
require(array.len() <= limit, || format!("sheet sketch {key} limit exceeded"))?;
|
||||
charge(&mut total, array.len(), MAX_ENTITIES, "drawing sketch entity")?;
|
||||
}
|
||||
}
|
||||
for key in AUXILIARY {
|
||||
if let Some(array) = sketch.get(key) {
|
||||
let array = array.as_array().ok_or_else(|| invalid(format!("{key} must be an array")))?;
|
||||
require(array.is_empty(), || format!("not supported yet: sheet sketch {key}"))?;
|
||||
}
|
||||
}
|
||||
if let Some(curves) = sketch.get("curves").and_then(Value::as_array) {
|
||||
for curve in curves {
|
||||
if let Some(points) = curve.get("pts").and_then(Value::as_array) {
|
||||
require(points.len() <= MAX_SPLINE_POINTS, || "sheet sketch spline point limit exceeded".into())?;
|
||||
charge(&mut total, points.len(), MAX_ENTITIES, "drawing sketch entity")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(counters) = sketch.get("counters").and_then(Value::as_object) {
|
||||
require(counters.len() <= 64, || "sheet sketch counter prefix limit exceeded".into())?;
|
||||
require(counters.keys().all(|key| key.len() <= MAX_LOCAL_ID_BYTES), || "sheet sketch counter prefix too long".into())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// These guards apply to from_value as well as from_json, and precede typed decoding.
|
||||
fn raw_tree(value: &Value, depth: usize, nodes: &mut usize, bytes: &mut usize) -> Result<()> {
|
||||
require(depth <= 32, || "sheet sketch payload nested too deeply".into())?;
|
||||
charge(nodes, 1, MAX_ENTITIES * 16, "raw node")?;
|
||||
match value {
|
||||
Value::String(s) => {
|
||||
require(s.len() <= MAX_STORED_TEXT_BYTES, || "sheet sketch stored text too long".into())?;
|
||||
charge(bytes, s.len(), MAX_DRAWING_BYTES, "stored text")?;
|
||||
}
|
||||
Value::Array(array) => {
|
||||
require(array.len() <= MAX_ENTITIES, || "sheet sketch raw array too large".into())?;
|
||||
for item in array {
|
||||
raw_tree(item, depth + 1, nodes, bytes)?;
|
||||
}
|
||||
}
|
||||
Value::Object(object) => {
|
||||
require(object.len() <= MAX_ENTITIES, || "sheet sketch raw object too large".into())?;
|
||||
for (key, item) in object {
|
||||
require(key.len() <= MAX_LOCAL_ID_BYTES, || "sheet sketch field name too long".into())?;
|
||||
charge(bytes, key.len(), MAX_DRAWING_BYTES, "stored text")?;
|
||||
raw_tree(item, depth + 1, nodes, bytes)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn check_drawing(drawing: &Drawing) -> Result<()> {
|
||||
require(drawing.sketches.len() <= MAX_SHEET_SKETCHES, || "too many sheet sketches".into())?;
|
||||
let sheets: BTreeSet<_> = drawing.sheets.iter().map(|s| s.id).collect();
|
||||
let mut entities = 0;
|
||||
let mut work = 0;
|
||||
for record in &drawing.sketches {
|
||||
require(sheets.contains(&record.sheet), || "sheet sketch owner does not exist in this drawing".into())?;
|
||||
check_name(&record.name, "sheet sketch")?;
|
||||
let sk = &record.sketch;
|
||||
for (count, cap) in [(sk.points.len(), MAX_POINTS), (sk.curves.len(), MAX_CURVES), (sk.constraints.len(), MAX_CONSTRAINTS)] {
|
||||
require(count <= cap, || "sheet sketch array limit exceeded".into())?;
|
||||
charge(&mut entities, count, MAX_ENTITIES, "drawing sketch entity")?;
|
||||
}
|
||||
require(
|
||||
sk.links.is_empty() && sk.patterns.is_empty() && sk.offsets.is_empty() && sk.freeform_offsets.is_empty() && sk.wires.is_empty(),
|
||||
|| "not supported yet: sheet sketch links, patterns, offsets or 3D wires".into(),
|
||||
)?;
|
||||
require(!sk.view.three_d && !sk.view.slice, || "model-only sketch view is not a sheet sketch".into())?;
|
||||
let origin = sk.points.first().ok_or_else(|| invalid("missing sketch origin"))?;
|
||||
require(origin.id == "origin" && origin.pos == Vec2::ZERO && origin.fixed && origin.link.is_none() && origin.exprs.is_none(), || {
|
||||
"sheet sketch point zero must be its fixed local origin".into()
|
||||
})?;
|
||||
let mut seen = BTreeSet::new();
|
||||
for point in &sk.points {
|
||||
identity(&mut seen, &point.id)?;
|
||||
position(point.pos)?;
|
||||
require(point.link.is_none(), || "not supported yet: linked sheet sketch point".into())?;
|
||||
if let Some(expressions) = &point.exprs {
|
||||
for expression in [&expressions.x, &expressions.y].into_iter().flatten() {
|
||||
text(expression)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
for curve in &sk.curves {
|
||||
identity(&mut seen, &curve.id)?;
|
||||
require(curve.link.is_none(), || "not supported yet: linked sheet sketch curve".into())?;
|
||||
if let CurveKind::Spline { pts, degree, control, .. } = &curve.kind {
|
||||
require(
|
||||
(2..=MAX_SPLINE_POINTS).contains(&pts.len()) && (1..=5).contains(degree) && (!control || pts.len() > usize::from(*degree)),
|
||||
|| "invalid sheet sketch spline size or degree".into(),
|
||||
)?;
|
||||
charge(&mut entities, pts.len(), MAX_ENTITIES, "drawing sketch entity")?;
|
||||
}
|
||||
require(curve.kind.point_ids().iter().all(|&i| i < sk.points.len()), || "sheet sketch curve references an unknown point".into())?;
|
||||
match curve.kind {
|
||||
CurveKind::Line { a, b } => require(a != b, || "sheet sketch line needs distinct point identities".into())?,
|
||||
CurveKind::Circle { r, .. } | CurveKind::Ellipse { r, .. } => {
|
||||
require(r.is_finite() && r > 0.0 && r < MAX_COORD, || "sheet sketch radius is out of range".into())?;
|
||||
}
|
||||
CurveKind::Conic { rho, .. } => {
|
||||
require(rho.is_finite() && rho > 0.0 && rho < 1.0, || "sheet sketch conic rho is out of range".into())?
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
require(!curve.infinite || (curve.construction && matches!(curve.kind, CurveKind::Line { .. })), || {
|
||||
"only a construction line can be infinite in a sheet sketch".into()
|
||||
})?;
|
||||
}
|
||||
for constraint in &sk.constraints {
|
||||
identity(&mut seen, &constraint.id)?;
|
||||
// Slot validation can search the constraint list twice. Charge that upper
|
||||
// bound before invoking the shared validator, rather than allowing O(n^3).
|
||||
let cost = if matches!(constraint.kind, ConstraintKind::SlotOverallLength { .. }) {
|
||||
sk.constraints
|
||||
.len()
|
||||
.checked_mul(sk.constraints.len())
|
||||
.and_then(|n| n.checked_mul(4))
|
||||
.ok_or_else(|| invalid("validation work overflow"))?
|
||||
} else {
|
||||
1
|
||||
};
|
||||
charge(&mut work, cost, MAX_VALIDATION_WORK, "validation work")?;
|
||||
sk.validate(&constraint.kind).map_err(|e| invalid(e.to_string()))?;
|
||||
if let Some(value) = &constraint.param {
|
||||
text(value)?;
|
||||
}
|
||||
if let Some(at) = constraint.text {
|
||||
position(at)?;
|
||||
}
|
||||
}
|
||||
sk.validate_periodic_splines().map_err(|e| invalid(e.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sort references, not the live geometry. Sheet order stays authored; sketch
|
||||
/// record order depends only on ids, so insertion order never changes saved bytes.
|
||||
pub(super) fn serialize_sorted<S: Serializer>(records: &[Arc<SheetSketch>], serializer: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
if records.len() > MAX_SHEET_SKETCHES {
|
||||
return Err(serde::ser::Error::custom("too many sheet sketches"));
|
||||
}
|
||||
let mut sorted: Vec<_> = records.iter().collect();
|
||||
sorted.sort_by_key(|record| record.id);
|
||||
sorted.serialize(serializer)
|
||||
}
|
||||
@@ -622,3 +622,210 @@ fn mutate(v: &mut Value, pick: &mut usize, lie: &Value, how: u64) -> bool {
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
// W38a: original paper-mm payload, independent of any Drawing UI or model solver.
|
||||
fn paper_sketch_file() -> Value {
|
||||
let mut d = file(&plate());
|
||||
let mut sketch = solidcraft_sketch::Sketch::new();
|
||||
let pts = [(15.0, 10.0), (55.0, 10.0), (55.0, 30.0), (15.0, 30.0)];
|
||||
for (i, (x, y)) in pts.into_iter().enumerate() {
|
||||
sketch.add_point(solidcraft_geom::Vec2::new(x, y), Some(&format!("p{i}"))).unwrap();
|
||||
}
|
||||
for i in 0..4 {
|
||||
sketch.add_line_pts(i + 1, (i + 1) % 4 + 1, Some(&format!("l{i}"))).unwrap();
|
||||
}
|
||||
sketch.add_constraint(solidcraft_sketch::ConstraintKind::Length { l: 0, value: 40.0 }, Some("Width".into())).unwrap();
|
||||
sketch.points[1].exprs = Some(Box::new(solidcraft_sketch::PointExprs { x: Some("Inset + 5 mm".into()), y: None }));
|
||||
d["sketches"] = json!([{"id": ids::encode(41), "sheet": d["sheets"][0]["id"], "name":"Detail outline", "sketch": sketch}]);
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_sketch_records_round_trip_in_paper_millimetres() {
|
||||
let input = paper_sketch_file();
|
||||
let loaded = read(&input).unwrap();
|
||||
let saved = file(&loaded);
|
||||
assert_eq!(saved["sketches"], input["sketches"]);
|
||||
assert_eq!(saved["units"], json!({"fixed":{"unit":"in"}}));
|
||||
assert_eq!(saved["sketches"][0]["sketch"]["points"][2]["pos"], json!([55.0, 10.0]));
|
||||
assert_eq!(saved["sketches"][0]["sketch"]["constraints"][0]["value"], json!(40.0));
|
||||
assert_eq!(saved["sketches"][0]["sketch"]["constraints"][0]["param"], json!("Width"));
|
||||
assert_eq!(read(&saved).unwrap().to_json().unwrap(), loaded.to_json().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_sketch_records_are_ordered_by_id_without_reordering_sheets_or_geometry() {
|
||||
let mut input = paper_sketch_file();
|
||||
let mut second = input["sketches"][0].clone();
|
||||
second["id"] = json!(ids::encode(40));
|
||||
second["sheet"] = input["sheets"][1]["id"].clone();
|
||||
input["sketches"].as_array_mut().unwrap().push(second);
|
||||
let d = read(&input).unwrap();
|
||||
assert_eq!(d.sketches.iter().map(|s| s.id).collect::<Vec<_>>(), [40, 41]);
|
||||
assert_eq!(file(&d)["sheets"], input["sheets"]);
|
||||
let mut reverse = d.clone();
|
||||
reverse.sketches.reverse();
|
||||
assert_eq!(reverse.to_json().unwrap(), d.to_json().unwrap());
|
||||
assert_eq!(reverse.sketches[0].id, 41, "saving must not mutate the live record");
|
||||
assert_eq!(d.sheet_sketch(41).unwrap().sheet, d.sheets[0].id);
|
||||
assert!(bare().sheet_sketch(41).is_none(), "lookup must not fall back to another drawing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_sketch_ids_share_the_drawing_namespace_and_owners_must_resolve() {
|
||||
let good = paper_sketch_file();
|
||||
for duplicate in [good["id"].clone(), good["sources"][0]["id"].clone(), good["sheets"][0]["id"].clone(), json!(ids::encode(0))] {
|
||||
let mut v = good.clone();
|
||||
v["sketches"][0]["id"] = duplicate;
|
||||
assert!(read(&v).is_err());
|
||||
}
|
||||
let mut v = good.clone();
|
||||
v["sketches"][0]["sheet"] = good["sources"][0]["id"].clone();
|
||||
assert!(refusal(&v).contains("owner does not exist"));
|
||||
v["sketches"][0]["sheet"] = json!(ids::encode(999));
|
||||
assert!(read(&v).is_err());
|
||||
let mut duplicate = good;
|
||||
let record = duplicate["sketches"][0].clone();
|
||||
duplicate["sketches"].as_array_mut().unwrap().push(record);
|
||||
assert!(read(&duplicate).is_err());
|
||||
|
||||
let mut d = read(&paper_sketch_file()).unwrap();
|
||||
let mut generator = IdSource::seeded(777);
|
||||
let taken = generator.next(&BTreeSet::new()).unwrap();
|
||||
Arc::make_mut(&mut d.sketches[0]).id = taken;
|
||||
assert_ne!(d.allocate_id(&mut IdSource::seeded(777)).unwrap(), taken);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawings_without_sketches_keep_their_old_shape_and_gain_only_the_pending_format() {
|
||||
let old = plate();
|
||||
let v = file(&old);
|
||||
assert!(v.get("sketches").is_none());
|
||||
assert!(read(&v).unwrap().sketches.is_empty());
|
||||
assert!(DRAWING.pending_names().iter().any(|n| n == "sheet-sketches"));
|
||||
let mut explicit_empty = v;
|
||||
explicit_empty["sketches"] = json!([]);
|
||||
assert!(file(&read(&explicit_empty).unwrap()).get("sketches").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_sketch_record_caps_run_before_typed_payload_decoding() {
|
||||
let base = paper_sketch_file();
|
||||
for (field, cap) in
|
||||
[("points", solidcraft_sketch::MAX_POINTS), ("curves", solidcraft_sketch::MAX_CURVES), ("constraints", solidcraft_sketch::MAX_CONSTRAINTS)]
|
||||
{
|
||||
let mut v = base.clone();
|
||||
// Null would fail typed SPoint/Curve/Constraint decoding; the size guard must run first.
|
||||
v["sketches"][0]["sketch"][field] = Value::Array(vec![Value::Null; cap + 1]);
|
||||
let why = refusal(&v);
|
||||
assert!(why.contains(&format!("{field} limit exceeded")), "{why}");
|
||||
}
|
||||
let mut too_many = base.clone();
|
||||
too_many["sketches"] = Value::Array(vec![Value::Null; MAX_SHEET_SKETCHES + 1]);
|
||||
assert!(refusal(&too_many).contains("too many sheet sketches"));
|
||||
for malformed in [Value::Null, json!({}), json!(true)] {
|
||||
let mut v = base.clone();
|
||||
v["sketches"] = malformed;
|
||||
assert!(read(&v).is_err());
|
||||
}
|
||||
let mut spline = base;
|
||||
spline["sketches"][0]["sketch"]["curves"][0] = json!({"type":"spline", "id":"s1", "pts":vec![0; solidcraft_sketch::MAX_SPLINE_POINTS + 1]});
|
||||
assert!(refusal(&spline).contains("spline point limit exceeded"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_sketch_count_limit_is_inclusive_and_entity_budget_is_shared() {
|
||||
let mut v = paper_sketch_file();
|
||||
let template = v["sketches"][0].clone();
|
||||
let records: Vec<_> = (0..MAX_SHEET_SKETCHES)
|
||||
.map(|i| {
|
||||
let mut record = template.clone();
|
||||
record["id"] = json!(ids::encode(100 + i as u64));
|
||||
record["sketch"] = serde_json::to_value(solidcraft_sketch::Sketch::new()).unwrap();
|
||||
record
|
||||
})
|
||||
.collect();
|
||||
v["sketches"] = json!(records);
|
||||
assert_eq!(read(&v).unwrap().sketches.len(), MAX_SHEET_SKETCHES);
|
||||
// Individually allowed arrays must not multiply the drawing-wide budget.
|
||||
let payload = json!({"points":vec![Value::Null; solidcraft_sketch::MAX_POINTS]});
|
||||
let many: Vec<_> = (0..5).map(|i| json!({"id":ids::encode(100+i),"sketch":payload})).collect();
|
||||
v["sketches"] = json!(many);
|
||||
assert!(refusal(&v).contains("drawing sketch entity limit exceeded"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_sketch_payload_refuses_bad_geometry_identity_and_constraints_without_repair() {
|
||||
let original = paper_sketch_file();
|
||||
let edits: Vec<(&str, Value)> = vec![
|
||||
("/sketches/0/sketch/points/1/id", json!("origin")),
|
||||
("/sketches/0/sketch/curves/0/id", json!("p0")),
|
||||
("/sketches/0/sketch/points/0/fixed", json!(false)),
|
||||
("/sketches/0/sketch/points/0/pos", json!([1.0, 0.0])),
|
||||
("/sketches/0/sketch/curves/0/a", json!(9999)),
|
||||
("/sketches/0/sketch/constraints/0/l", json!(9999)),
|
||||
("/sketches/0/sketch/constraints/0/value", json!(-1.0)),
|
||||
("/sketches/0/name", json!(" ")),
|
||||
("/sketches/0/sketch/points/1/exprs/x", json!("x".repeat(4097))),
|
||||
("/sketches/0/sketch/constraints/0/param", json!("\n")),
|
||||
];
|
||||
for (pointer, bad) in edits {
|
||||
let mut v = original.clone();
|
||||
*v.pointer_mut(pointer).unwrap() = bad;
|
||||
assert!(read(&v).is_err(), "accepted {pointer}");
|
||||
}
|
||||
let mut d = read(&original).unwrap();
|
||||
Arc::make_mut(&mut d.sketches[0]).sketch.points[1].pos.x = f64::NAN;
|
||||
assert!(d.validate().is_err());
|
||||
assert!(d.to_json().is_err(), "NaN must not silently serialize as null");
|
||||
assert_eq!(original, paper_sketch_file(), "the oracle was not modified");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_sketch_records_refuse_unconnected_auxiliary_and_model_only_state_explicitly() {
|
||||
let original = paper_sketch_file();
|
||||
for field in ["links", "patterns", "offsets", "freeform_offsets", "wires"] {
|
||||
let mut v = original.clone();
|
||||
v["sketches"][0]["sketch"][field] = json!([null]);
|
||||
assert!(refusal(&v).contains("not supported yet"), "{field}");
|
||||
}
|
||||
for flag in ["slice", "three_d"] {
|
||||
let mut v = original.clone();
|
||||
v["sketches"][0]["sketch"]["view"] = json!({flag:true});
|
||||
assert!(refusal(&v).contains("model-only"));
|
||||
}
|
||||
let mut unknown = original;
|
||||
unknown["sketches"][0]["source_path"] = json!("another-design.solidcraft");
|
||||
assert!(refusal(&unknown).contains("unknown field"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_design_roundtrip_preserves_sketch_payload_without_model_parameter_creation() {
|
||||
let d = read(&paper_sketch_file()).unwrap();
|
||||
let mut doc = crate::Document::new("Source");
|
||||
let before = doc.to_json();
|
||||
doc.drawings.push(Arc::new(d));
|
||||
let reopened = crate::Document::from_json(&doc.to_json()).unwrap();
|
||||
assert_eq!(file(&reopened.drawings[0])["sketches"], paper_sketch_file()["sketches"]);
|
||||
let mut only_model = reopened;
|
||||
only_model.drawings.clear();
|
||||
assert_eq!(only_model.to_json(), before, "record IO must not create source parameters or features");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_sketch_json_mutations_are_errors_or_complete_reopenable_records() {
|
||||
let base = paper_sketch_file();
|
||||
let count = count(&base);
|
||||
for index in 0..count {
|
||||
for lie in [Value::Null, json!(true), json!("hostile"), json!(-1), json!(1e100)] {
|
||||
let mut v = base.clone();
|
||||
let mut pick = index;
|
||||
mutate(&mut v, &mut pick, &lie, 0);
|
||||
if let Ok(d) = read(&v) {
|
||||
d.validate().unwrap();
|
||||
let saved = d.to_json().unwrap();
|
||||
assert_eq!(Drawing::from_json(&saved).unwrap(), d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
# Drawing-owned sheet sketches: W38a record slice
|
||||
|
||||
This is the first, data-only increment of [W38a #7082][issue]. It builds on the
|
||||
embedded-drawing K3b/K4-prime receiver in [#3891][storage], not the superseded
|
||||
separate-file drawing session. It does not enable sketch commands or complete W38a.
|
||||
|
||||
## Stored meaning
|
||||
|
||||
`Drawing.sketches` contains `Arc<SheetSketch>` records. A record has `id`, `sheet`,
|
||||
`name` and the existing `solidcraft_sketch::Sketch` payload. Its id belongs to the
|
||||
same drawing-wide namespace as the drawing, source and sheet ids. Its `sheet`
|
||||
reference must resolve inside that drawing. Local ids such as `origin`, `p1`
|
||||
and `l1` remain local to the payload and may repeat in a different sketch.
|
||||
`Drawing::sheet_sketch(id)` searches only that drawing; it does not inspect the
|
||||
active model or search other drawings.
|
||||
|
||||
Positions and length dimensions are paper XY millimetres, angles are radians.
|
||||
Changing `Drawing.units` is not a geometry conversion. For example the authored
|
||||
rectangle (15,10) to (55,30) remains 40 by 20 paper mm when units are `in`.
|
||||
There is no view scale or source path in this sheet-owned record.
|
||||
|
||||
Point expression strings and dimension parameter names are retained verbatim.
|
||||
This layer neither evaluates them nor creates a model parameter. A successful
|
||||
read does not establish that a name resolves in the design, that expressions
|
||||
have compatible units, or that constraints solve. Those checks belong to the
|
||||
later receiver-aware read-only evaluation/edit transaction, before tools are
|
||||
enabled. No model evaluation or geometry repair occurs during record loading.
|
||||
|
||||
## Current supported payload
|
||||
|
||||
The first slice admits the shared 2D point/curve/constraint payload: finite
|
||||
bounded points, valid local identities and point/curve references, bounded
|
||||
splines, radii and conic weights, and constraints checked by the existing
|
||||
`Sketch::validate`. Periodic splines use the existing validator. The fixed
|
||||
local origin must remain point zero. Input is not snapped or solved.
|
||||
|
||||
**Explicitly not connected yet:** nonempty links (including generated text),
|
||||
patterns, offsets/freeform offsets and 3D wires, and the model-only slice/3D
|
||||
palette state. They are refused, not dropped. Linked points/curves are also
|
||||
refused. Enabling these auxiliary record families requires their bounded
|
||||
validation and Drawing receiver paths; it is later W38a work. This is not an
|
||||
alternative numeric-only editing mode: no editing mode or command is enabled.
|
||||
|
||||
## Identity, ordering and compatibility
|
||||
|
||||
An absent/empty `sketches` list is omitted on write, retaining the previous
|
||||
record shape. One `drawing/format/pending/sheet-sketches.rs` entry versions the
|
||||
optional addition; there is no new design-format step or manually edited
|
||||
version number. Builds that do not know the pending change refuse the file.
|
||||
|
||||
Records are serialized by numeric drawing object id, independently of their
|
||||
insertion order, without mutating the live vector. Reading adopts that order.
|
||||
Sheet order and all local sketch geometry/ids remain unchanged. Duplicate or
|
||||
zero drawing ids, duplicate local ids and unknown owners are errors. There is
|
||||
no nearest-sheet fallback. New ids allocated by `Drawing::allocate_id` also
|
||||
avoid existing sketch records.
|
||||
|
||||
## Bounded admission
|
||||
|
||||
The encoded drawing still uses the existing 16 MiB limit. `from_value`, used
|
||||
by embedded plain-JSON designs, applies the same new raw record checks before
|
||||
typed sketch decoding. The new admission limits are explicit implementation
|
||||
bounds, not a claim about geometric precision:
|
||||
|
||||
- At most 1,000 sheet-sketch records per drawing.
|
||||
- Each payload uses the shared `MAX_POINTS`, `MAX_CURVES`, `MAX_CONSTRAINTS`
|
||||
and `MAX_SPLINE_POINTS` caps. Their point/curve/constraint and spline-index
|
||||
entries together cannot exceed 80,000 across the drawing.
|
||||
- Stored string values are at most 4,096 bytes; local ids/field names at most
|
||||
512 bytes, and sketch names follow the drawing's 256-byte name rule. Counter
|
||||
maps have at most 64 prefixes. Expressions cannot be blank or contain controls.
|
||||
- Raw payload depth is at most 32 and all sketch records together at most
|
||||
1,280,000 JSON nodes and 16 MiB of string/key bytes. These do not replace the
|
||||
encoded-file cap or make a pre-existing JSON Value allocation bounded.
|
||||
- Constraint checks have a cumulative 2,000,000 work allowance. Slot-length
|
||||
validation is charged conservatively for its nested constraint searches.
|
||||
|
||||
The typed edit boundary repeats array, identity, range, owner and constraint
|
||||
checks. Nonfinite positions/dimensions are errors before a drawing with sketches
|
||||
can be written by `Drawing::to_json`; NaN is not silently stored as JSON null.
|
||||
The shared Sketch type and model-sketch reader are unchanged. No solver, cache,
|
||||
active sketch, source state, external font, dependency or CI setting is added.
|
||||
|
||||
## Acceptance and remaining work
|
||||
|
||||
The tests live in the existing `crates/doc/src/drawing_tests.rs`. Original
|
||||
fixtures cover a paper rectangle and stored expressions; deterministic ordering;
|
||||
drawing/local identity separation; unknown owners; absent/empty sketches; size
|
||||
limits before typed allocation; finite/index/constraint rejection; unsupported
|
||||
auxiliary data; inline-design round trips without model changes; and bounded
|
||||
JSON mutations. Actual executed results belong in the PR, not this design note.
|
||||
|
||||
The command/store increment still depends on W38.0 #6336 and the real K session
|
||||
interfaces. It must supply read-only expression bindings and evaluation, solved
|
||||
state, create/edit/finish/cancel, drawing-local undo/redo and checkpoints, hostile
|
||||
command handling, container reopening and UI/native/browser parity. W38d's later
|
||||
saved-fill integration must retain outer-plus-holes identity after edits. W38b/c/e
|
||||
and source-edge projection remain with their existing owners.
|
||||
|
||||
[issue]: https://github.com/tangency-labs/solidcraft/issues/7082
|
||||
[storage]: https://github.com/tangency-labs/solidcraft/pull/3891
|
||||
Reference in new issue
Block a user