diff --git a/Cargo.lock b/Cargo.lock index 955c654..ff47a40 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -733,6 +733,7 @@ dependencies = [ "ifccad", "rmp-serde", "serde", + "serde_ignored", "serde_json", "web-time", ] @@ -992,6 +993,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serde_ignored" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115dffd5f3853e06e746965a20dcbae6ee747ae30b543d91b0e089668bb07798" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_json" version = "1.0.154" diff --git a/Cargo.toml b/Cargo.toml index 2ecba35..0cbbae2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ repository = "https://github.com/HakanSeven12/opencaddocument" [features] mline-pilot = ["ifcx", "selection-storage"] selection = [] -selection-storage = ["selection", "dep:serde", "dep:rmp-serde"] +selection-storage = ["selection", "dep:serde", "dep:rmp-serde", "dep:serde_ignored", "acadrust/serde"] serde = ["acadrust/serde", "dep:serde"] # IFCX through the ifccad library (OpenAEC Foundation). ifcx = ["dep:ifccad", "dep:web-time"] @@ -17,6 +17,7 @@ ifcx = ["dep:ifccad", "dep:web-time"] [dependencies] acadrust = { git = "https://github.com/hakanaktt/acadrust.git", rev = "c978b989a9f218e281cf923ce1d2668ee4640bd7" } rmp-serde = { version = "=1.3.0", optional = true } +serde_ignored = { version = "=0.1.14", optional = true } serde = { version = "1", features = ["derive"], optional = true } # ifccad only reads and writes IFCX; the mapping to `Document` lives here. ifccad = { git = "https://github.com/OpenAEC-Foundation/ifccad.git", rev = "207a5ad6f24f73e1e53d994d4c3ac52d1e616ab7", optional = true } diff --git a/README.md b/README.md index b0e0933..3e6491f 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,9 @@ DWG and DXF reading and writing come from [acadrust](https://github.com/hakanaktt/acadrust). Enable the `selection` Cargo feature to use `selection::DocumentSelection` for -owned capture and inspection of explicit ModelSpace Line/MLINE selections, +owned capture and reconstruction of explicit Line/MLINE, Point, Circle, Arc, +Ellipse, LwPolyline, Spline, Ray and XLine selections in ModelSpace, paper layouts +and existing local block definitions, with their layers, simple linetypes and MLINESTYLE dependencies. It keeps separate included, external, missing and contextual requirements. See [owned selections](docs/selection.md) and the @@ -68,7 +70,7 @@ also enables `selection` and provides [versioned storage](docs/selection-storage The [reconstruction API](docs/selection-reconstruction.md) builds an independent candidate from an explicit subset and reports the result for each requested root. The optional [MLINE preservation pilot](docs/ifcx-mline-preservation.md) -uses these APIs to save and reopen ModelSpace MLINEs in IFCCAD. +uses these APIs for MLINEs in IFCCAD. Ray/XLine adapter integration remains separate. ## Logical IFCCAD conversion diff --git a/docs/selection-fields.md b/docs/selection-fields.md index 06217b3..c097fd7 100644 --- a/docs/selection-fields.md +++ b/docs/selection-fields.md @@ -1,6 +1,6 @@ # Selection capture field audit -This is the capture boundary against acadrust revision `cec07ce`. Exhaustive +This is the capture boundary against acadrust revision `c978b989a9f218e281cf923ce1d2668ee4640bd7`. Exhaustive struct patterns in capture code force review when supported carriers acquire new fields. These classifications concern owned capture, not a durable byte layout or a promise to insert arbitrary values into another drawing. See @@ -9,6 +9,12 @@ layout or a promise to insert arbitrary values into another drawing. See | Carrier | Retained typed values | Reference/context rules and exclusions | | --- | --- | --- | | `Line` | start, end, thickness, normal | common fields below | +| `Point` | location, thickness, normal, x_axis_angle | common fields; PDMODE/PDSIZE drawing context | +| `Circle`, `Arc` | center, radius, thickness, normal; Arc angles | common fields | +| `Ellipse` | center, major_axis, minor_axis_ratio, start/end parameters, normal | common fields | +| `LwPolyline`, `LwVertex` | vertices, is_closed, plinegen, constant_width, elevation, thickness, normal; each location, bulge, widths, vertex_id | vertex_id is an integer identifier, not a handle | +| `Spline`, `SplineFlags` | degree, all flags, knots, control/fit points, weights, normal, tolerances, tangents, knot_parameterization, cv_frame_visible, dwg_flags1, dwg_scenario, dxf_flags | all geometry/scalars; both definitions retained in typed storage | +| `Ray`, `XLine` | base_point, direction | common fields; no surrogate finite line | | `MLine` | flags, justification, normal, scale_factor, start_point, style_element_count, vertices | style_handle/style_name retained; separate effective style requirement | | `MLineVertex` | position, direction, miter, segments | no reference fields | | `MLineSegment` | parameters, area_fill_parameters | complete float bits, no sorting or regeneration | @@ -63,3 +69,8 @@ Record payloads preserve original fields, while requirements retain interpreted roles and effective defaults separately. No sanitization other than the three declared entity storage/derived fields is allowed. New supported kinds, slots, attachments, storage or reconstruction require their own reviewed boundary. + +The common-only field guards also destructure Vector2/Vector3 and exhaustively +match Color, LineWeight and Transparency. These guards classify fields; geometry +serialization delegates directly to the existing provider model. The dependency +description is shared by capture, durable validation and resource binding. diff --git a/docs/selection-reconstruction.md b/docs/selection-reconstruction.md index c6e2715..78f345e 100644 --- a/docs/selection-reconstruction.md +++ b/docs/selection-reconstruction.md @@ -1,7 +1,8 @@ # Reconstructing an owned selection `DocumentSelection::reconstruct_available` adds explicitly requested -ModelSpace Line and MLINE roots to a candidate cloned from the current Document. +supported roots to a candidate cloned from the current Document, in ModelSpace, +PaperSpace or an existing local block definition. Enable the `selection` Cargo feature to use this API. Capture or reopen the selection before calling it. Reopening uses the optional `selection-storage` feature. @@ -75,7 +76,7 @@ the requested name in the style dictionary and in every rebound MLINE. The creation check compares case-insensitive names against both occupied names and existing references. New names must also fit DWG text lengths -in the target version and encoding. The check inspects typed Line and MLINE records, +in the target version and encoding. The check inspects supported typed roots, block markers, qualified tables and constructor scaffold, including the current layer, linetype and multiline style names in the header. A target with an unqualified name carrier blocks creation. For instance, an existing @@ -134,3 +135,37 @@ The candidate has independent drawing content. Its allocator reserves one batch for the required entities, resources and scaffold. Reserved handles are local to that candidate. History or preservation retention remains the responsibility of the caller. + +## Additional typed leaves + +Point, Circle, Arc, Ellipse, LwPolyline, Spline, Ray and XLine use the same owner, +resource, handle and draw-order planning as Line/MLINE. Identity does not +normalize geometry. Translate delegates to the codec WCS translation, including +OCS centers and polyline elevation; directions, normals and spline tangents +are not translated. Nonfinite geometry or translated results block that root. +Checks also require nonzero normals/directions, positive Circle/Arc radius, +Ellipse ratio in (0,1], two polyline vertices and nonnegative widths. Splines +need a valid control or fit definition: degree/count/domain, monotone knots, +and empty or positive matching weights. Both source definitions remain retained. +These are admission checks, not a second geometry evaluator. + +Point display mode and size must match the target bit-for-bit, with finite +sizes. A mismatch yields ContextMismatch only for Point; other roots continue. +The target header is never changed to make a Point qualify. + +The pinned codec does not yet census Spline/Ray/XLine geometry. A private +reservation adapter temporarily substitutes only those handle-free geometries +with Point images carrying their exact common state, runs the unchanged codec +census, and restores the exact original shared images on success or failure. +Exhaustive field guards qualify that geometry has no extra handles. Raw backing, +common attachments, dangling references, other carriers and allocation floors +remain subject to the existing census. Nothing is inserted as a Point. + +The compact physical gallery exercises all ten root kinds plus a fit-only +Spline in ModelSpace, two layouts and Inner nested in Outer. Both current outer +INSERT transforms survive moving/rotating one between capture and restoration. +Sparse SortEnts insertion is checked after DWG/DXF reopening. DWG retains the +fit-only representation; DXF may add derived control data to a fit-only spline. +The tests check the original fit points independently. Combined control/fit and +nondefault Spline metadata have typed-storage evidence, not a claim of exact +preservation of every field by every physical writer. diff --git a/docs/selection-storage.md b/docs/selection-storage.md index a1d3d0c..131efab 100644 --- a/docs/selection-storage.md +++ b/docs/selection-storage.md @@ -3,7 +3,9 @@ The `selection-storage` Cargo feature enables `selection` and exposes `opencaddocument::selection_storage::{encode, decode}`. A selection can be reopened after the source drawing has been dropped. The feature uses private -DTOs and named MessagePack maps. Model Serde can be enabled separately. +DTOs for legacy payloads and the existing typed model for V4 leaves, using named +MessagePack maps. It enables the provider model Serde internally; Document Serde +remains an independent feature. ```rust use opencaddocument::{ @@ -46,7 +48,7 @@ SortEnts order requires a check against the current target document. | Offset | Size | Value | | --- | ---: | --- | | 0 | 8 | ASCII `OCADSEL` followed by byte `00` | -| 8 | 2 | Big-endian unsigned version, `0001`, `0002` or `0003` | +| 8 | 2 | Big-endian unsigned version, `0001`, `0002`, `0003` or `0004` | | 10 | 1 | Selection kind, `01` | | 11 | 4 | Big-endian unsigned body length | | 15 | Body length | Exactly one MessagePack body | @@ -58,7 +60,7 @@ bytes after the frame yield `TrailingData`. Invalid markers, types, tags and map fields yield `InvalidBody`. Inconsistent selection content yields `InvalidSelection`. The error exposes its category and a byte offset or JSON Pointer when available. The writer selects the earliest version that supports -the owners in the selection. V1 covers ModelSpace. V2 adds `paper_space`, and +the owners and payloads in the selection. V1 covers ModelSpace. V2 adds `paper_space`, and V3 adds `block_definition`. V2 and V3 support distinct owner handles in the same selection. The remaining wire fields are shared with V1. @@ -83,7 +85,8 @@ Unsigned and signed integer types have their usual bit-width bounds. A handle `index32` use unsigned 32-bit integers. A count above that range cannot be encoded. `char32` is a Unicode scalar encoded as an unsigned 32-bit integer. Use string, boolean and nil markers for their respective types. Binary, -extension and physical float markers are rejected. +extension and physical float markers are rejected in V1–V3. V4 admits float64 +only; float32, binary and extension markers remain rejected. | Type | Fields in writer order | | --- | --- | @@ -193,3 +196,42 @@ version decision. The envelope selects the reader before it interprets the payload. Re-encoding a valid alternative marker or map order yields the writer's canonical representation. Independent V1 fixtures and their source generator live under `tests/fixtures/selection/v1/`. + +## V4 common-only leaf model + +A selection containing an Entity payload uses V4, independently of its owners. +Legacy-only selections still choose V1 (ModelSpace), V2 (PaperSpace) or V3 +(local definitions); their field layouts and byte fixtures are unchanged. + +V4 adds the required body field `model_schema: "acadrust-leaf-1"`. Its context +adds required `point_display`, either nil or a named map with `mode: i16` and +`size: f64`. Point requires this context; without a Point it must be nil. +All other body/ledger fields keep the legacy definitions above. + +The new payload tuple is `["entity", ]`. The eight allowed +variants are Point, Circle, Arc, Ellipse, LwPolyline, Spline, Ray and XLine. +The model uses the reviewed acadrust revision +`c978b989a9f218e281cf923ce1d2668ee4640bd7`, with externally tagged enum maps, +named struct maps, scalar flags and float64 geometry. Common raw_record, +graphic_data and has_ds_data are excluded; skipped/unknown input fields are +errors with the first ignored path. Reactors, XDATA and unsupported common +references are rejected even when they deserialize as valid model data. +An unknown schema is UnsupportedVersion; duplicate fields and unknown variants +are errors. The model schema changes only after reviewing this retained surface. + +A private measurement serializer checks the complete borrowed V4 body once, +including legacy resources, map keys and requirements, against the same count, +value, text and depth limits. The bounded writer separately enforces actual +encoded bytes. The decoder preflights the complete body before model allocation; +there is no hidden binary sub-packet with an independent budget. Signed zero +and NaN payload bits are retained exactly; storage does not certify geometry. +Independent Ray/Circle fixtures and their standard-library Python author live +under `tests/fixtures/selection/v4/`. + +V4 enforces these shapes recursively during deserialization: every model struct +(including vectors and struct enum variants) requires a named map. Intentional +sequences such as vertices, control points and payload tuples remain sequences. +An f64 field requires a float64 marker, even when an integer value could be +represented exactly. This also applies to Point display size; integer handles, +flags and legacy bits64 fields keep their integer representation. A shared +Serde adapter enforces these rules without an intermediate geometry tree. diff --git a/docs/selection.md b/docs/selection.md index df37b87..c5a538f 100644 --- a/docs/selection.md +++ b/docs/selection.md @@ -1,6 +1,7 @@ # Owned document selections -`selection::DocumentSelection` captures explicit `Line` and `MLine` roots in +`selection::DocumentSelection` captures explicit `Line`, `MLine`, `Point`, `Circle`, `Arc`, +`Ellipse`, `LwPolyline`, `Spline`, `Ray` and `XLine` roots in ModelSpace, PaperSpace and local block definitions with their supported dependencies. The selection is independent of the source `Document`. Enable the `selection` Cargo feature for capture and reconstruction. The API @@ -107,3 +108,25 @@ through `capture_report()`; there is no duplicate mutable report. A successful capture with `Missing` requirements is intentionally incomplete and does not promise successful reconstruction. See the [field audit](selection-fields.md) for the exact supported boundary. + +## Common-only typed families + +The eight additional families use `SelectionPayload::Entity(Box)`: +the existing public model is the owned payload. No second geometry DTO is +maintained. Line and MLine keep their original payload variants. Other enum +variants, including Line/MLine disguised as Entity, are outside this boundary. +One dependency description defines owner, layer and linetype slots across +capture, storage validation and reconstruction; MLINE adds its style slots. + +Point additionally captures PDMODE/PDSIZE in `SelectionContext.point_display`. +The context is present exactly when Point is selected. Reconstruction checks +that the destination agrees, without changing its global display settings. + +The additional enum variant and public context field require updates to +external exhaustive matches and struct literals. This is a source API change; +it does not claim to compile every existing consumer unchanged. + +The same explicit-resource and destination-owner API can support copying +between drawings. This extension provides the shared machinery, not a new +clipboard UI or automatic mapping of every dependency or entity family. +IFCCAD preservation of Ray/XLine is a separate adapter contribution. diff --git a/src/ifcx/table_style.rs b/src/ifcx/table_style.rs index 3177553..2b8e272 100644 --- a/src/ifcx/table_style.rs +++ b/src/ifcx/table_style.rs @@ -347,21 +347,21 @@ fn named_in( pub(super) fn format_out(writer: &Writer<'_>, source: &CellStyle) -> CellFormat { let sets = |property| source.sets(property); - let mut margins = Margins::default(); - margins.left = - (sets(P::MARGIN_LEFT) || source.margin_override_flags != 0).then_some(source.margin_left); - margins.top = - (sets(P::MARGIN_TOP) || source.margin_override_flags != 0).then_some(source.margin_top); - margins.right = - (sets(P::MARGIN_RIGHT) || source.margin_override_flags != 0).then_some(source.margin_right); - margins.bottom = (sets(P::MARGIN_BOTTOM) || source.margin_override_flags != 0) - .then_some(source.margin_bottom); - margins.horizontal_spacing = (sets(P::MARGIN_HORIZONTAL_SPACING) - || source.margin_override_flags != 0) - .then_some(source.horizontal_spacing); - margins.vertical_spacing = (sets(P::MARGIN_VERTICAL_SPACING) - || source.margin_override_flags != 0) - .then_some(source.vertical_spacing); + let margins = Margins { + left: (sets(P::MARGIN_LEFT) || source.margin_override_flags != 0) + .then_some(source.margin_left), + top: (sets(P::MARGIN_TOP) || source.margin_override_flags != 0) + .then_some(source.margin_top), + right: (sets(P::MARGIN_RIGHT) || source.margin_override_flags != 0) + .then_some(source.margin_right), + bottom: (sets(P::MARGIN_BOTTOM) || source.margin_override_flags != 0) + .then_some(source.margin_bottom), + horizontal_spacing: (sets(P::MARGIN_HORIZONTAL_SPACING) + || source.margin_override_flags != 0) + .then_some(source.horizontal_spacing), + vertical_spacing: (sets(P::MARGIN_VERTICAL_SPACING) || source.margin_override_flags != 0) + .then_some(source.vertical_spacing), + }; let edges = source.applied_border_edges; let border = |flag: Edge, value: &CellBorder| { (edges.contains(flag) || !value.override_flags.is_empty()) diff --git a/src/selection/capture.rs b/src/selection/capture.rs index e1f439a..02c496b 100644 --- a/src/selection/capture.rs +++ b/src/selection/capture.rs @@ -1,4 +1,4 @@ -use super::references::{Reference, SourceIndex}; +use super::references::{describe, EndpointSpec, Reference, SourceIndex}; use super::*; use crate::{ entities::{EntityCommon, EntityType, Line, MLine, MLineSegment, MLineVertex}, @@ -65,6 +65,14 @@ pub(super) fn capture( context: SelectionContext { insertion_units: doc.header.insertion_units, linetype_scale: doc.header.linetype_scale, + point_display: request + .roots + .iter() + .any(|h| matches!(doc.get_entity(*h), Some(EntityType::Point(_)))) + .then_some(SelectionPointDisplay { + mode: doc.header.point_display_mode, + size: doc.header.point_display_size, + }), }, }; let mut capture = Capture { @@ -368,12 +376,12 @@ impl Capture<'_> { ) -> Result<(), SelectionError> { let EntityCommon { handle: _, - layer, - layer_handle, + layer: _, + layer_handle: _, color: _, line_weight: _, - linetype, - linetype_handle, + linetype: _, + linetype_handle: _, linetype_scale: _, transparency: _, color_name: _, @@ -422,29 +430,11 @@ impl Capture<'_> { "entity contains attachments or resource/mode semantics outside capture coverage", )); } - let (role, name) = self.owner(k, *owner_handle, *entity_mode)?; + let (role, _) = self.owner(k, *owner_handle, *entity_mode)?; if role != ContextRole::ModelSpace { // Persist explicit ownership for paper and definition members. *entity_mode = Some(0); } - self.requirement( - Reference { - source: k, - slot: SelectionSlot::Owner, - handle: Some(*owner_handle), - name: Some(name), - kind: SelectionRecordKind::Object, - }, - RequirementDisposition::Context(role), - ); - self.reference(Reference { - source: k, - slot: SelectionSlot::Layer, - handle: *layer_handle, - name: Some(layer.clone()), - kind: SelectionRecordKind::Layer, - })?; - self.linetype(k, SelectionSlot::LineType, *linetype_handle, linetype)?; if raw_record.take().is_some() || had_raw_record { self.evidence( Some(k), @@ -562,8 +552,8 @@ impl Capture<'_> { normal: _, scale_factor: _, start_point: _, - style_handle, - style_name, + style_handle: _, + style_name: _, style_element_count: _, vertices, } = mline; @@ -580,45 +570,24 @@ impl Capture<'_> { } in segments {} } - let (style_handle, style_name) = (*style_handle, style_name.clone()); let had_raw_record = mline.common.raw_record.is_some(); let mut mline = mline.clone(); self.common(k, had_raw_record, &mut mline.common)?; - let effective = if style_handle.is_none_or(|h| h.is_null()) { - self.evidence(Some(k),Some(SelectionSlot::MLineStyle),CaptureEvidenceCode::ResolvedSourceDefault,"absent/null entity style handle uses the actual source header style"); - Some(self.doc.header.current_multiline_style_handle) - } else { - style_handle - }; - // A null current source style is a gap, never a name/default repair. - if effective.is_some_and(|h| h.is_null()) { - self.requirement( - Reference { - source: k, - slot: SelectionSlot::MLineStyle, - handle: effective, - name: Some(style_name), - kind: SelectionRecordKind::Object, - }, - RequirementDisposition::Missing, - ); - } else { - self.reference(Reference { - source: k, - slot: SelectionSlot::MLineStyle, - handle: effective, - name: Some(style_name), - kind: SelectionRecordKind::Object, - })?; - } SelectionPayload::MLine(Box::new(mline)) } + entity if super::entity_policy::is_leaf(entity) => { + super::field_coverage::check(entity); + let had_raw_record = entity.common().raw_record.is_some(); + let mut entity = entity.clone(); + self.common(k, had_raw_record, entity.common_mut())?; + SelectionPayload::Entity(Box::new(entity)) + } _ => { return Err(error( SelectionErrorKind::UnsupportedContent, Some(k), None, - "only Line and MLine roots are supported", + "root family is outside typed selection coverage", )) } } @@ -637,7 +606,7 @@ impl Capture<'_> { color: _, color_name: _, book_name: _, - line_type, + line_type: _, line_weight: _, plot_style, is_plottable: _, @@ -663,7 +632,7 @@ impl Capture<'_> { { return Err(error(SelectionErrorKind::UnsupportedContent,Some(k),None,"xref, material and plot-style layer dependencies are outside capture coverage")); } - self.linetype(k, SelectionSlot::LineType, None, line_type)?; + SelectionPayload::Layer(Box::new(layer.clone())) } SelectionRecordKind::LineType => { @@ -716,24 +685,82 @@ impl Capture<'_> { fill_color: _, flags: _, } = style; - self.registration(k, style)?; - for ( - i, - MLineStyleElement { - offset: _, - color: _, - linetype, - }, - ) in elements.iter().enumerate() - { - self.linetype(k, SelectionSlot::StyleElementLineType(i), None, linetype)?; - } + for MLineStyleElement { + offset: _, + color: _, + linetype: _, + } in elements + {} SelectionPayload::MLineStyle(Box::new(style.clone())) } }; - self.selection - .records - .push(SelectionRecord { key: k, payload }); + let record = SelectionRecord { key: k, payload }; + self.resolve_references(&record)?; + self.selection.records.push(record); + Ok(()) + } + fn resolve_references(&mut self, record: &SelectionRecord) -> Result<(), SelectionError> { + for spec in describe(record)? { + let key = record.key; + match spec.endpoint { + EndpointSpec::Owner { handle } => { + let common = + super::entity_policy::common(&record.payload).expect("root common"); + let (role, name) = self.owner(key, handle, common.entity_mode)?; + self.requirement( + Reference { + source: key, + slot: spec.slot, + handle: Some(handle), + name: Some(name), + kind: spec.target_kind, + }, + RequirementDisposition::Context(role), + ); + } + EndpointSpec::StyleRegistration { .. } => { + let SelectionPayload::MLineStyle(style) = &record.payload else { + unreachable!() + }; + self.registration(key, style)?; + } + EndpointSpec::SourceDefault { name } => { + self.evidence( + Some(key), + Some(spec.slot.clone()), + CaptureEvidenceCode::ResolvedSourceDefault, + "absent/null entity style handle uses the actual source header style", + ); + let handle = Some(self.doc.header.current_multiline_style_handle); + let reference = Reference { + source: key, + slot: spec.slot, + handle, + name: Some(name), + kind: spec.target_kind, + }; + if handle.is_some_and(|h| h.is_null()) { + self.requirement(reference, RequirementDisposition::Missing); + } else { + self.reference(reference)?; + } + } + EndpointSpec::Stored { handle, name } + | EndpointSpec::Inheritance { handle, name, .. } => { + if spec.target_kind == SelectionRecordKind::LineType { + self.linetype(key, spec.slot, handle, &name)?; + } else { + self.reference(Reference { + source: key, + slot: spec.slot, + handle, + name: Some(name), + kind: spec.target_kind, + })?; + } + } + } + } Ok(()) } fn registration( diff --git a/src/selection/entity_policy.rs b/src/selection/entity_policy.rs new file mode 100644 index 0000000..98f9656 --- /dev/null +++ b/src/selection/entity_policy.rs @@ -0,0 +1,154 @@ +use crate::EntityType; + +pub(super) fn common(payload: &super::SelectionPayload) -> Option<&crate::entities::EntityCommon> { + match payload { + super::SelectionPayload::Line(v) => Some(&v.common), + super::SelectionPayload::MLine(v) => Some(&v.common), + super::SelectionPayload::Entity(v) => Some(v.common()), + _ => None, + } +} + +/// Explicit family boundary. New codec variants are never implicitly captured. +pub(super) fn is_leaf(entity: &EntityType) -> bool { + leaf_tag(entity).is_some() +} + +/// Provider Serde variant identity for the closed V4 retained surface. +pub(super) fn leaf_tag(entity: &EntityType) -> Option<&'static str> { + Some(match entity { + EntityType::Point(_) => "Point", + EntityType::Circle(_) => "Circle", + EntityType::Arc(_) => "Arc", + EntityType::Ellipse(_) => "Ellipse", + EntityType::LwPolyline(_) => "LwPolyline", + EntityType::Spline(_) => "Spline", + EntityType::Ray(_) => "Ray", + EntityType::XLine(_) => "XLine", + _ => return None, + }) +} + +/// Durable retained state may not smuggle excluded attachments through model Serde. +pub(super) fn retained_common(c: &crate::entities::EntityCommon) -> bool { + c.extended_data.records().is_empty() + && c.extended_data.raw_dwg_eed.is_empty() + && c.reactors.is_empty() + && c.xdictionary_handle.is_none() + && [ + c.color_book_handle, + c.full_visual_style_handle, + c.face_visual_style_handle, + c.edge_visual_style_handle, + c.material_handle, + c.plotstyle_handle, + ] + .iter() + .all(Option::is_none) + && c.material_flags <= 1 + && c.plotstyle_flags <= 1 + && c.r12_metadata.is_none() + && c.graphic_data.is_none() + && c.raw_record.is_none() + && !c.has_ds_data +} + +fn vector(v: crate::Vector3) -> bool { + v.x.is_finite() && v.y.is_finite() && v.z.is_finite() +} +fn nonzero(v: crate::Vector3) -> bool { + vector(v) && v != crate::Vector3::ZERO +} +fn numbers(values: &[f64]) -> bool { + values.iter().all(|v| v.is_finite()) +} +fn valid_leaf(e: &EntityType) -> bool { + match e { + EntityType::Point(v) => { + vector(v.location) && nonzero(v.normal) && numbers(&[v.thickness, v.x_axis_angle]) + } + EntityType::Circle(v) => { + vector(v.center) + && nonzero(v.normal) + && numbers(&[v.radius, v.thickness]) + && v.radius > 0.0 + } + EntityType::Arc(v) => { + vector(v.center) + && nonzero(v.normal) + && numbers(&[v.radius, v.thickness, v.start_angle, v.end_angle]) + && v.radius > 0.0 + } + EntityType::Ellipse(v) => { + vector(v.center) + && nonzero(v.major_axis) + && nonzero(v.normal) + && numbers(&[v.minor_axis_ratio, v.start_parameter, v.end_parameter]) + && v.minor_axis_ratio > 0.0 + && v.minor_axis_ratio <= 1.0 + } + EntityType::LwPolyline(v) => { + nonzero(v.normal) + && numbers(&[v.elevation, v.thickness, v.constant_width]) + && v.constant_width >= 0.0 + && v.vertices.len() >= 2 + && v.vertices.iter().all(|p| { + numbers(&[ + p.location.x, + p.location.y, + p.bulge, + p.start_width, + p.end_width, + ]) && p.start_width >= 0.0 + && p.end_width >= 0.0 + }) + } + EntityType::Spline(v) => { + let n = v.control_points.len(); + let control = if n == 0 { + v.knots.is_empty() && v.weights.is_empty() && v.fit_points.len() >= 2 + } else { + usize::try_from(v.degree).ok().is_some_and(|d| { + d >= 1 + && d < n + && n.checked_add(d).and_then(|x| x.checked_add(1)) == Some(v.knots.len()) + && v.knots.windows(2).all(|p| p[0] <= p[1]) + && v.knots[d] < v.knots[n] + }) && (v.weights.is_empty() + || (v.weights.len() == n + && v.weights.iter().all(|w| w.is_finite() && *w > 0.0))) + }; + control + && (v.fit_points.is_empty() || v.fit_points.len() >= 2) + && v.control_points + .iter() + .chain(&v.fit_points) + .all(|p| vector(*p)) + && vector(v.normal) + && vector(v.begin_tangent) + && vector(v.end_tangent) + && numbers(&[v.knot_tolerance, v.control_tolerance, v.fit_tolerance]) + && numbers(&v.knots) + } + EntityType::Ray(v) => vector(v.base_point) && nonzero(v.direction), + EntityType::XLine(v) => vector(v.base_point) && nonzero(v.direction), + _ => false, + } +} +/// Preserve identity values; only Translate delegates to the codec's WCS/OCS rules. +pub(super) fn prepare_leaf( + source: &EntityType, + placement: super::SelectionPlacement, +) -> Result { + if !valid_leaf(source) || !retained_common(source.common()) { + return Err("invalid leaf geometry or attachment"); + } + let mut entity = source.clone(); + if let super::SelectionPlacement::Translate(delta) = placement { + entity.as_entity_mut().translate(delta); + } + if !valid_leaf(&entity) { + return Err("nonfinite translated leaf geometry"); + } + Ok(entity) +} diff --git a/src/selection/field_coverage.rs b/src/selection/field_coverage.rs new file mode 100644 index 0000000..3b08f00 --- /dev/null +++ b/src/selection/field_coverage.rs @@ -0,0 +1,167 @@ +//! Exhaustive retained-field guards, independent of geometry serialization. +//! Every non-common field below is retained scalar/geometry (including flags +//! and vertex_id, which is not a CAD handle). Reference-bearing common state is +//! classified by capture::common; source drawing Point display is context. +use crate::entities::{ + Arc, Circle, Ellipse, LwPolyline, LwVertex, Point, Ray, Spline, SplineFlags, XLine, +}; +use crate::EntityType; + +pub(super) fn check(entity: &EntityType) { + match entity { + EntityType::Point(value) => check_point(value), + EntityType::Circle(value) => check_circle(value), + EntityType::Arc(value) => check_arc(value), + EntityType::Ellipse(value) => check_ellipse(value), + EntityType::LwPolyline(value) => check_lwpolyline(value), + EntityType::Spline(value) => check_spline(value), + EntityType::Ray(value) => check_ray(value), + EntityType::XLine(value) => check_xline(value), + _ => {} + } +} + +fn check_point(value: &Point) { + let Point { + common: _, + location: _, + thickness: _, + normal: _, + x_axis_angle: _, + } = value; +} + +fn check_circle(value: &Circle) { + let Circle { + common: _, + center: _, + radius: _, + thickness: _, + normal: _, + } = value; +} + +fn check_arc(value: &Arc) { + let Arc { + common: _, + center: _, + radius: _, + start_angle: _, + end_angle: _, + thickness: _, + normal: _, + } = value; +} + +fn check_ellipse(value: &Ellipse) { + let Ellipse { + common: _, + center: _, + major_axis: _, + minor_axis_ratio: _, + start_parameter: _, + end_parameter: _, + normal: _, + } = value; +} + +fn check_lwpolyline(value: &LwPolyline) { + let LwPolyline { + common: _, + vertices: _, + is_closed: _, + plinegen: _, + constant_width: _, + elevation: _, + thickness: _, + normal: _, + } = value; + for vertex in &value.vertices { + check_lwvertex(vertex); + } +} + +fn check_lwvertex(value: &LwVertex) { + let LwVertex { + location: _, + bulge: _, + start_width: _, + end_width: _, + vertex_id: _, + } = value; +} + +fn check_spline(value: &Spline) { + let Spline { + common: _, + degree: _, + flags: _, + knots: _, + control_points: _, + weights: _, + fit_points: _, + normal: _, + knot_tolerance: _, + control_tolerance: _, + fit_tolerance: _, + begin_tangent: _, + end_tangent: _, + knot_parameterization: _, + cv_frame_visible: _, + dwg_flags1: _, + dwg_scenario: _, + dxf_flags: _, + } = value; + check_splineflags(&value.flags); +} + +fn check_splineflags(value: &SplineFlags) { + let SplineFlags { + closed: _, + periodic: _, + rational: _, + planar: _, + linear: _, + } = value; +} + +fn check_ray(value: &Ray) { + let Ray { + common: _, + base_point: _, + direction: _, + } = value; +} + +fn check_xline(value: &XLine) { + let XLine { + common: _, + base_point: _, + direction: _, + } = value; +} + +// The remaining nested retained carriers contain only scalars; changes force +// the same dependency/model-schema review as a new entity field. +const _: fn(&crate::Vector3) = |v| { + let crate::Vector3 { x: _, y: _, z: _ } = v; +}; +const _: fn(&crate::Vector2) = |v| { + let crate::Vector2 { x: _, y: _ } = v; +}; +const _: fn(&crate::Color) = |v| match v { + crate::Color::ByLayer | crate::Color::ByBlock | crate::Color::None | crate::Color::Index(_) => { + } + crate::Color::Rgb { r: _, g: _, b: _ } => {} +}; +const _: fn(&crate::LineWeight) = |v| match v { + crate::LineWeight::ByLayer + | crate::LineWeight::ByBlock + | crate::LineWeight::Default + | crate::LineWeight::Value(_) => {} +}; +const _: fn(&crate::Transparency) = |v| match v { + crate::Transparency::ByLayer + | crate::Transparency::ByBlock + | crate::Transparency::Explicit(_) => {} +}; diff --git a/src/selection/mod.rs b/src/selection/mod.rs index f18d67d..6071ae1 100644 --- a/src/selection/mod.rs +++ b/src/selection/mod.rs @@ -2,6 +2,8 @@ pub(crate) mod block_definition; mod capture; +mod entity_policy; +mod field_coverage; mod layout; pub mod reconstruct; mod references; @@ -56,6 +58,8 @@ impl CaptureRequest { /// Existing model types, owned independently of the source document. #[derive(Debug, Clone, PartialEq)] pub enum SelectionPayload { + /// Common-only Point/Circle/Arc/Ellipse/LwPolyline/Spline/Ray/XLine model. + Entity(Box), Line(Box), MLine(Box), MLineStyle(Box), @@ -125,6 +129,14 @@ pub struct CaptureEvidence { pub struct SelectionContext { pub insertion_units: i16, pub linetype_scale: f64, + pub point_display: Option, +} + +/// Source drawing settings controlling the display of selected POINT roots. +#[derive(Debug, Clone, PartialEq)] +pub struct SelectionPointDisplay { + pub mode: i16, + pub size: f64, } /// Immutable capture with its sole authoritative evidence report. diff --git a/src/selection/reconstruct/mod.rs b/src/selection/reconstruct/mod.rs index 9673171..76ba429 100644 --- a/src/selection/reconstruct/mod.rs +++ b/src/selection/reconstruct/mod.rs @@ -169,6 +169,7 @@ pub enum ReconstructionBlockerKind { IncompatibleResource, InvalidGeometry, IncompatibleUnits, + ContextMismatch, InvalidPlacement, InvalidOrderAnchor, } @@ -232,6 +233,7 @@ fn construction(error: impl std::fmt::Display) -> ReconstructionError { } mod plan; +mod reservation; use super::references::SourceIndex; pub(super) fn run( @@ -352,8 +354,7 @@ fn run_with_order( None } else { Some( - candidate - .try_reserve_handles(count) + reservation::reserve(&mut candidate, count) .map_err(ReconstructionError::Reservation)?, ) }; @@ -511,6 +512,11 @@ mod tests { #[test] fn late_order_construction_failure_discards_candidate() { + late_order_failure(false); + late_order_failure(true); + } + + fn late_order_failure(generic: bool) { let line = || { EntityType::Line(Line::from_points( Vector3::ZERO, @@ -526,7 +532,11 @@ mod tests { handle: layer.handle, }; source.layers.add(layer).unwrap(); - let mut selected = line(); + let mut selected = if generic { + EntityType::Circle(crate::entities::Circle::new()) + } else { + line() + }; selected.common_mut().layer = "Source walls".into(); selected.common_mut().layer_handle = Some(layer_key.handle); let selected = source.add_entity(selected).unwrap(); diff --git a/src/selection/reconstruct/plan.rs b/src/selection/reconstruct/plan.rs index edfc979..2aec58c 100644 --- a/src/selection/reconstruct/plan.rs +++ b/src/selection/reconstruct/plan.rs @@ -170,6 +170,26 @@ pub(super) fn prepare_root( }; let mut style = None; let mut entity = match catalog.records[&root.root] { + SelectionPayload::Entity(v) => { + if matches!(v.as_ref(), EntityType::Point(_)) { + let target = &catalog.doc.header; + if !context.point_display.as_ref().is_some_and(|p| { + p.mode == target.point_display_mode + && p.size.is_finite() + && target.point_display_size.is_finite() + && p.size.to_bits() == target.point_display_size.to_bits() + }) { + return Err(fail( + K::ContextMismatch, + None, + None, + "Point display context differs or is nonfinite", + )); + } + } + super::super::entity_policy::prepare_leaf(v, root.transform) + .map_err(|message| fail(K::InvalidGeometry, None, None, message))? + } SelectionPayload::Line(v) => { let mut v = (**v).clone(); if !finite(v.normal) diff --git a/src/selection/reconstruct/reservation.rs b/src/selection/reconstruct/reservation.rs new file mode 100644 index 0000000..1f35614 --- /dev/null +++ b/src/selection/reconstruct/reservation.rs @@ -0,0 +1,91 @@ +//! Compatibility census for common-only families not yet inventoried by the +//! pinned codec. Geometry has no handles (see exhaustive field_coverage guards). +//! The codec still inventories the exact common state and every other carrier. +use super::*; + +pub(super) fn reserve( + doc: &mut Document, + count: usize, +) -> Result { + if count == 0 { + return doc.try_reserve_handles(0); + } + let originals: Option> = doc + .entities() + .filter(|e| { + matches!( + e, + EntityType::Spline(_) | EntityType::Ray(_) | EntityType::XLine(_) + ) + }) + .map(|e| { + let handle = e.common().handle; + let original = doc.get_entity_arc(handle)?; + std::ptr::eq(e, original.as_ref()).then_some((handle, original)) + }) + .collect(); + // Validate the entire projection before changing any image. A stale lookup + // or duplicate identity remains the unchanged codec census's responsibility. + let Some(originals) = originals else { + return doc.try_reserve_handles(count); + }; + let mut saved = Vec::with_capacity(originals.len()); + for (handle, original) in originals { + super::super::field_coverage::check(&original); + let mut proxy = crate::entities::Point::new(); + proxy.common = original.common().clone(); + // EntityCommon::clone deliberately drops raw_record; census must see it. + proxy.common.raw_record = original.common().raw_record.clone(); + let previous = doc + .replace_entity_arc(handle, std::sync::Arc::new(EntityType::Point(proxy))) + .expect("same identity"); + saved.push((handle, previous)); + } + let result = doc.try_reserve_handles(count); + // Restore exact shared originals on both success and failure. + for (handle, original) in saved { + doc.replace_entity_arc(handle, original) + .expect("census does not change identities"); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn common_handles_remain_protected_and_exact_images_are_restored() { + let mut doc = Document::new(); + let mut e = EntityType::Ray(crate::entities::Ray::new(Vector3::ZERO, Vector3::UNIT_X)); + let high = Handle::new((1u64 << 53) + 23); + e.common_mut().reactors.push(high); + let h = doc.add_entity(e).unwrap(); + let before = doc.get_entity_arc(h).unwrap(); + let reserved = reserve(&mut doc, 2).unwrap(); + assert!(reserved.get(0).unwrap().value() > high.value()); + assert!(std::sync::Arc::ptr_eq( + &before, + &doc.get_entity_arc(h).unwrap() + )); + } + #[test] + fn unqualified_common_is_not_hidden_by_geometry_projection() { + let mut doc = Document::new(); + let mut e = EntityType::XLine(crate::entities::XLine::new(Vector3::ZERO, Vector3::UNIT_X)); + e.common_mut().graphic_data = Some(vec![1, 2, 3]); + let h = doc.add_entity(e).unwrap(); + let before = doc.get_entity_arc(h).unwrap(); + let floor = doc.next_handle(); + let seed = doc.header.handle_seed; + assert!(matches!( + reserve(&mut doc, 1), + Err(crate::HandleReservationError::UninspectableData { .. }) + )); + assert!(std::sync::Arc::ptr_eq( + &before, + &doc.get_entity_arc(h).unwrap() + )); + assert_eq!(doc.next_handle(), floor); + assert_eq!(doc.header.handle_seed, seed); + } +} diff --git a/src/selection/reconstruct/resources.rs b/src/selection/reconstruct/resources.rs index f98c467..90c915b 100644 --- a/src/selection/reconstruct/resources.rs +++ b/src/selection/reconstruct/resources.rs @@ -121,16 +121,18 @@ impl NameInventory { if let EntityType::MLine(v) = entity { mark(Object, &v.style_name); } - complete &= matches!( - entity, - EntityType::Line(_) + complete &= (super::super::entity_policy::is_leaf(entity) + || matches!( + entity, + EntityType::Line(_) | EntityType::MLine(_) | EntityType::Block(_) | EntityType::BlockEnd(_) // Viewport resource links outside the common fields are // handles or belong to the separate plot-style domain. | EntityType::Viewport(_) - ) && common.raw_record.is_none() + )) + && common.raw_record.is_none() && common.extended_data.records().is_empty() && common.extended_data.raw_dwg_eed.is_empty(); } @@ -330,6 +332,28 @@ impl<'a> Catalog<'a> { ) -> Result { use ReconstructionBlockerKind as K; let error = |code, target, msg| blocked(code, key, Some(slot.clone()), target, msg); + let payload = self + .records + .get(&key) + .ok_or_else(|| error(K::MissingDependency, None, "source record is absent"))?; + let spec = super::super::references::describe_payload(key, payload) + .map_err(|_| error(K::IncompatibleResource, None, "unsupported source payload"))? + .into_iter() + .find(|spec| spec.slot == *slot) + .ok_or_else(|| { + error( + K::MissingDependency, + None, + "slot is outside source coverage", + ) + })?; + if spec.target_kind != kind { + return Err(error( + K::InvalidBinding, + None, + "binding role disagrees with source slot", + )); + } let req = self .slot(key, slot) .ok_or_else(|| error(K::MissingDependency, None, "required slot is absent"))?; diff --git a/src/selection/references.rs b/src/selection/references.rs index 7a2c350..fa01282 100644 --- a/src/selection/references.rs +++ b/src/selection/references.rs @@ -150,3 +150,182 @@ pub(super) struct Reference { pub name: Option, pub kind: SelectionRecordKind, } + +#[derive(Debug, Clone)] +pub(super) struct ReferenceSpec { + pub slot: SelectionSlot, + pub target_kind: SelectionRecordKind, + pub endpoint: EndpointSpec, +} + +#[derive(Debug, Clone)] +pub(super) enum EndpointSpec { + Stored { + handle: Option, + name: String, + }, + Owner { + handle: Handle, + }, + Inheritance { + role: ContextRole, + handle: Option, + name: String, + }, + SourceDefault { + name: String, + }, + StyleRegistration { + handle: Handle, + name: String, + }, +} + +pub(super) fn linetype_role(name: &str) -> Option { + if name.is_empty() || name.eq_ignore_ascii_case("BYLAYER") { + Some(ContextRole::ByLayer) + } else if name.eq_ignore_ascii_case("BYBLOCK") { + Some(ContextRole::ByBlock) + } else { + None + } +} + +fn stored( + slot: SelectionSlot, + kind: SelectionRecordKind, + handle: Option, + name: &str, +) -> ReferenceSpec { + let endpoint = if kind == SelectionRecordKind::LineType { + linetype_role(name).map(|role| EndpointSpec::Inheritance { + role, + handle, + name: name.into(), + }) + } else { + None + } + .unwrap_or_else(|| EndpointSpec::Stored { + handle, + name: name.into(), + }); + ReferenceSpec { + slot, + target_kind: kind, + endpoint, + } +} + +/// Sole slot inventory for capture, validation and reconstruction. +pub(super) fn describe(record: &SelectionRecord) -> Result, SelectionError> { + describe_payload(record.key, &record.payload) +} + +pub(super) fn describe_payload( + key: SelectionRecordKey, + payload: &SelectionPayload, +) -> Result, SelectionError> { + if let SelectionPayload::Entity(entity) = payload { + if !super::entity_policy::is_leaf(entity) { + return Err(SelectionError { + kind: SelectionErrorKind::UnsupportedContent, + source: Some(key), + slot: None, + message: "unsupported generic entity family".into(), + }); + } + } + let mut refs = Vec::new(); + if let Some(c) = super::entity_policy::common(payload) { + refs.push(ReferenceSpec { + slot: SelectionSlot::Owner, + target_kind: SelectionRecordKind::Object, + endpoint: EndpointSpec::Owner { + handle: c.owner_handle, + }, + }); + refs.push(stored( + SelectionSlot::Layer, + SelectionRecordKind::Layer, + c.layer_handle, + &c.layer, + )); + refs.push(stored( + SelectionSlot::LineType, + SelectionRecordKind::LineType, + c.linetype_handle, + &c.linetype, + )); + } + match payload { + SelectionPayload::MLine(v) => refs.push(ReferenceSpec { + slot: SelectionSlot::MLineStyle, + target_kind: SelectionRecordKind::Object, + endpoint: if v.style_handle.is_none_or(|h| h.is_null()) { + EndpointSpec::SourceDefault { + name: v.style_name.clone(), + } + } else { + EndpointSpec::Stored { + handle: v.style_handle, + name: v.style_name.clone(), + } + }, + }), + SelectionPayload::Layer(v) => refs.push(stored( + SelectionSlot::LineType, + SelectionRecordKind::LineType, + None, + &v.line_type, + )), + SelectionPayload::MLineStyle(v) => { + refs.push(ReferenceSpec { + slot: SelectionSlot::StyleRegistration, + target_kind: SelectionRecordKind::Object, + endpoint: EndpointSpec::StyleRegistration { + handle: v.owner, + name: v.name.clone(), + }, + }); + refs.extend(v.elements.iter().enumerate().map(|(i, e)| { + stored( + SelectionSlot::StyleElementLineType(i), + SelectionRecordKind::LineType, + None, + &e.linetype, + ) + })); + } + _ => {} + } + Ok(refs) +} + +#[cfg(test)] +mod description_tests { + use super::*; + + #[test] + fn dependency_slots_are_shared_for_common_roots() { + let entity = crate::entities::Ray::new(crate::Vector3::ZERO, crate::Vector3::UNIT_X); + let record = SelectionRecord { + key: SelectionRecordKey { + kind: SelectionRecordKind::Entity, + handle: Handle::new(50), + }, + payload: SelectionPayload::Entity(Box::new(crate::EntityType::Ray(entity))), + }; + let refs = describe(&record).unwrap(); + assert_eq!( + refs.iter().map(|r| r.slot.clone()).collect::>(), + vec![ + SelectionSlot::Owner, + SelectionSlot::Layer, + SelectionSlot::LineType + ] + ); + assert_eq!(refs[1].target_kind, SelectionRecordKind::Layer); + assert_eq!(refs[2].target_kind, SelectionRecordKind::LineType); + } +} diff --git a/src/selection/storage/frame.rs b/src/selection/storage/frame.rs index d3065a8..159f9aa 100644 --- a/src/selection/storage/frame.rs +++ b/src/selection/storage/frame.rs @@ -8,7 +8,7 @@ pub(super) const BODY_LIMIT: usize = 64 * 1024 * 1024; pub(super) const COUNT_LIMIT: usize = 262_144; pub(super) const VALUE_LIMIT: usize = 1_048_576; pub(super) const STRING_LIMIT: usize = 1_048_576; -const DEPTH_LIMIT: usize = 16; +pub(super) const DEPTH_LIMIT: usize = 16; type Result = std::result::Result; @@ -18,6 +18,7 @@ pub(super) enum Version { V1 = 1, V2 = 2, V3 = 3, + V4 = 4, } impl Version { @@ -54,6 +55,7 @@ pub(super) fn body(bytes: &[u8]) -> Result<(Version, &[u8])> { [0, 1] => Version::V1, [0, 2] => Version::V2, [0, 3] => Version::V3, + [0, 4] => Version::V4, _ => { return Err(error( Kind::UnsupportedVersion, @@ -93,15 +95,16 @@ pub(super) fn body(bytes: &[u8]) -> Result<(Version, &[u8])> { )); } let body = &bytes[HEADER..]; - preflight(body)?; + preflight(body, version)?; Ok((version, body)) } -fn preflight(body: &[u8]) -> Result<()> { +fn preflight(body: &[u8], version: Version) -> Result<()> { let mut scan = Scanner { input: body, pos: 0, remaining_values: VALUE_LIMIT, + floats: version == Version::V4, }; scan.value(0, false)?; if scan.pos != body.len() { @@ -118,6 +121,7 @@ struct Scanner<'a> { input: &'a [u8], pos: usize, remaining_values: usize, + floats: bool, } impl<'a> Scanner<'a> { @@ -172,6 +176,10 @@ impl<'a> Scanner<'a> { } let (len, map) = match marker { 0x00..=0x7f | 0xc0 | 0xc2..=0xc3 | 0xe0..=0xff => return Ok(()), + 0xcb if self.floats => { + self.take(8)?; + return Ok(()); + } 0xcc..=0xd3 => { self.take(1 << ((marker - 0xcc) & 3))?; return Ok(()); @@ -236,7 +244,7 @@ impl BoundedFrame { pub(super) fn finish(mut self) -> Result> { let size = self.bytes.len() - HEADER; self.bytes[11..15].copy_from_slice(&(size as u32).to_be_bytes()); - preflight(&self.bytes[HEADER..])?; + body(&self.bytes)?; Ok(self.bytes) } } diff --git a/src/selection/storage/mod.rs b/src/selection/storage/mod.rs index 2811527..d0661cf 100644 --- a/src/selection/storage/mod.rs +++ b/src/selection/storage/mod.rs @@ -3,6 +3,8 @@ use super::{DocumentSelection, RequirementDisposition}; mod frame; +mod model; +mod strict; mod validate; mod wire; @@ -59,7 +61,7 @@ fn error(kind: SelectionStorageErrorKind, message: impl Into) -> Selecti /// Write one selection using the earliest storage version that can represent its owners. pub fn encode(selection: &DocumentSelection) -> Result> { - let version = selection + let mut version = selection .requirements() .iter() .filter_map(|r| match r.disposition { @@ -68,6 +70,13 @@ pub fn encode(selection: &DocumentSelection) -> Result> { }) .max() .unwrap_or(frame::Version::V1); + if selection + .records() + .iter() + .any(|r| matches!(r.payload, super::SelectionPayload::Entity(_))) + { + version = frame::Version::V4; + } validate::selection(selection, version)?; wire::write(selection, version) } @@ -75,7 +84,7 @@ pub fn encode(selection: &DocumentSelection) -> Result> { /// Read one versioned selection into owned model values. pub fn decode(bytes: &[u8]) -> Result { let (version, body) = frame::body(bytes)?; - let selection = wire::read(body)?; + let selection = wire::read(body, version)?; validate::selection(&selection, version)?; Ok(selection) } diff --git a/src/selection/storage/model.rs b/src/selection/storage/model.rs new file mode 100644 index 0000000..5e9a27a --- /dev/null +++ b/src/selection/storage/model.rs @@ -0,0 +1,313 @@ +//! Direct model transport and one shared budget for the complete V4 body. +use super::{error, frame, Result, SelectionStorageError, SelectionStorageErrorKind as Kind}; +use crate::EntityType; +use serde::{ser, Deserialize, Serialize, Serializer}; + +#[derive(Serialize)] +#[serde(transparent)] +pub(super) struct ModelBorrow<'a>(pub &'a EntityType); +#[derive(Serialize, Deserialize)] +#[serde(transparent)] +pub(super) struct ModelOwned(pub EntityType); + +impl ser::Error for SelectionStorageError { + fn custom(message: T) -> Self { + error(Kind::InvalidSelection, message.to_string()) + } +} +#[derive(Default)] +pub(super) struct ModelBudget { + values: usize, + depth: usize, + max_depth: usize, + largest_container: usize, + largest_string: usize, +} +pub(super) fn measure(value: &T) -> Result { + let mut b = ModelBudget::default(); + value.serialize(&mut b)?; + Ok(b) +} +impl ModelBudget { + fn value(&mut self) -> Result<()> { + self.values += 1; + if self.values > frame::VALUE_LIMIT { + return Err(error(Kind::LimitExceeded, "too many model values")); + } + Ok(()) + } + fn text(&mut self, text: &str) -> Result<()> { + self.value()?; + self.largest_string = self.largest_string.max(text.len()); + if text.len() > frame::STRING_LIMIT { + return Err(error(Kind::LimitExceeded, "model string too long")); + } + Ok(()) + } + fn container(&mut self, len: Option) -> Result> { + let len = + len.ok_or_else(|| error(Kind::InvalidSelection, "model container requires a length"))?; + self.value()?; + self.largest_container = self.largest_container.max(len); + if len > frame::COUNT_LIMIT || self.depth >= frame::DEPTH_LIMIT { + return Err(error(Kind::LimitExceeded, "model count or depth exceeded")); + } + self.depth += 1; + self.max_depth = self.max_depth.max(self.depth); + Ok(Compound { + budget: self, + levels: 1, + }) + } +} +pub(super) struct Compound<'a> { + budget: &'a mut ModelBudget, + levels: usize, +} +impl Compound<'_> { + fn finish(self) -> Result<()> { + self.budget.depth -= self.levels; + Ok(()) + } +} +impl<'a> Serializer for &'a mut ModelBudget { + type Ok = (); + type Error = SelectionStorageError; + type SerializeSeq = Compound<'a>; + type SerializeTuple = Compound<'a>; + type SerializeTupleStruct = Compound<'a>; + type SerializeTupleVariant = Compound<'a>; + type SerializeMap = Compound<'a>; + type SerializeStruct = Compound<'a>; + type SerializeStructVariant = Compound<'a>; + fn serialize_bool(self, _: bool) -> Result<()> { + self.value() + } + fn serialize_i8(self, _: i8) -> Result<()> { + self.value() + } + fn serialize_i16(self, _: i16) -> Result<()> { + self.value() + } + fn serialize_i32(self, _: i32) -> Result<()> { + self.value() + } + fn serialize_i64(self, _: i64) -> Result<()> { + self.value() + } + fn serialize_u8(self, _: u8) -> Result<()> { + self.value() + } + fn serialize_u16(self, _: u16) -> Result<()> { + self.value() + } + fn serialize_u32(self, _: u32) -> Result<()> { + self.value() + } + fn serialize_u64(self, _: u64) -> Result<()> { + self.value() + } + fn serialize_f64(self, _: f64) -> Result<()> { + self.value() + } + fn serialize_f32(self, _: f32) -> Result<()> { + Err(error(Kind::InvalidSelection, "f32 is outside V4 grammar")) + } + fn serialize_char(self, v: char) -> Result<()> { + self.text(v.encode_utf8(&mut [0; 4])) + } + fn serialize_str(self, v: &str) -> Result<()> { + self.text(v) + } + fn serialize_bytes(self, _: &[u8]) -> Result<()> { + Err(error( + Kind::InvalidSelection, + "binary is outside V4 grammar", + )) + } + fn serialize_none(self) -> Result<()> { + self.value() + } + fn serialize_some(self, v: &T) -> Result<()> { + v.serialize(self) + } + fn serialize_unit(self) -> Result<()> { + self.value() + } + fn serialize_unit_struct(self, _: &'static str) -> Result<()> { + self.value() + } + fn serialize_unit_variant(self, _: &'static str, _: u32, variant: &'static str) -> Result<()> { + self.text(variant) + } + fn serialize_newtype_struct(self, _: &'static str, v: &T) -> Result<()> { + v.serialize(self) + } + fn serialize_newtype_variant( + self, + _: &'static str, + _: u32, + variant: &'static str, + v: &T, + ) -> Result<()> { + let c = self.container(Some(1))?; + c.budget.text(variant)?; + v.serialize(&mut *c.budget)?; + c.finish() + } + fn serialize_seq(self, len: Option) -> Result> { + self.container(len) + } + fn serialize_tuple(self, len: usize) -> Result> { + self.container(Some(len)) + } + fn serialize_tuple_struct(self, _: &'static str, len: usize) -> Result> { + self.container(Some(len)) + } + fn serialize_map(self, len: Option) -> Result> { + self.container(len) + } + fn serialize_struct(self, _: &'static str, len: usize) -> Result> { + self.container(Some(len)) + } + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + variant: &'static str, + len: usize, + ) -> Result> { + self.variant(variant, len) + } + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + variant: &'static str, + len: usize, + ) -> Result> { + self.variant(variant, len) + } +} +impl ModelBudget { + fn variant(&mut self, variant: &str, len: usize) -> Result> { + let outer = self.container(Some(1))?; + outer.budget.text(variant)?; + let mut inner = outer.budget.container(Some(len))?; + inner.levels = 2; + Ok(inner) + } +} +impl ser::SerializeSeq for Compound<'_> { + type Ok = (); + type Error = SelectionStorageError; + fn serialize_element(&mut self, v: &T) -> Result<()> { + v.serialize(&mut *self.budget) + } + fn end(self) -> Result<()> { + self.finish() + } +} +impl ser::SerializeTuple for Compound<'_> { + type Ok = (); + type Error = SelectionStorageError; + fn serialize_element(&mut self, v: &T) -> Result<()> { + v.serialize(&mut *self.budget) + } + fn end(self) -> Result<()> { + self.finish() + } +} +impl ser::SerializeTupleStruct for Compound<'_> { + type Ok = (); + type Error = SelectionStorageError; + fn serialize_field(&mut self, v: &T) -> Result<()> { + v.serialize(&mut *self.budget) + } + fn end(self) -> Result<()> { + self.finish() + } +} +impl ser::SerializeTupleVariant for Compound<'_> { + type Ok = (); + type Error = SelectionStorageError; + fn serialize_field(&mut self, v: &T) -> Result<()> { + v.serialize(&mut *self.budget) + } + fn end(self) -> Result<()> { + self.finish() + } +} +impl ser::SerializeMap for Compound<'_> { + type Ok = (); + type Error = SelectionStorageError; + fn serialize_key(&mut self, v: &T) -> Result<()> { + v.serialize(&mut *self.budget) + } + fn serialize_value(&mut self, v: &T) -> Result<()> { + v.serialize(&mut *self.budget) + } + fn end(self) -> Result<()> { + self.finish() + } +} +impl ser::SerializeStruct for Compound<'_> { + type Ok = (); + type Error = SelectionStorageError; + fn serialize_field(&mut self, key: &'static str, v: &T) -> Result<()> { + self.budget.text(key)?; + v.serialize(&mut *self.budget) + } + fn end(self) -> Result<()> { + self.finish() + } +} +impl ser::SerializeStructVariant for Compound<'_> { + type Ok = (); + type Error = SelectionStorageError; + fn serialize_field(&mut self, key: &'static str, v: &T) -> Result<()> { + self.budget.text(key)?; + v.serialize(&mut *self.budget) + } + fn end(self) -> Result<()> { + self.finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn measurement_uses_one_global_budget_and_exact_boundaries() { + assert!(measure(&vec![0u8; frame::COUNT_LIMIT]).is_ok()); + assert_eq!( + measure(&vec![0u8; frame::COUNT_LIMIT + 1]) + .err() + .unwrap() + .kind, + Kind::LimitExceeded + ); + assert!(measure(&"x".repeat(frame::STRING_LIMIT)).is_ok()); + assert_eq!( + measure(&"x".repeat(frame::STRING_LIMIT + 1)) + .err() + .unwrap() + .kind, + Kind::LimitExceeded + ); + assert_eq!( + measure(&vec![vec![0u8; frame::COUNT_LIMIT]; 4]) + .err() + .unwrap() + .kind, + Kind::LimitExceeded + ); + let mut v = serde_json::Value::Null; + for _ in 0..frame::DEPTH_LIMIT { + v = serde_json::json!([v]); + } + assert!(measure(&v).is_ok()); + v = serde_json::json!([v]); + assert_eq!(measure(&v).err().unwrap().kind, Kind::LimitExceeded); + } +} diff --git a/src/selection/storage/strict.rs b/src/selection/storage/strict.rs new file mode 100644 index 0000000..d8645c5 --- /dev/null +++ b/src/selection/storage/strict.rs @@ -0,0 +1,352 @@ +//! Recursive wire-shape enforcement for V4, without projecting model fields. +use serde::de::{self, DeserializeSeed, Visitor}; +pub(super) struct Strict(pub D); +#[derive(Clone, Copy)] +enum Shape { + Any, + Map, + Float, +} +struct Visit { + inner: V, + shape: Shape, +} +impl Visit { + fn any(inner: V) -> Self { + Self { + inner, + shape: Shape::Any, + } + } +} +impl<'de, D: de::Deserializer<'de>> de::Deserializer<'de> for Strict { + type Error = D::Error; + fn deserialize_any>(self, v: V) -> Result { + self.0.deserialize_any(Visit::any(v)) + } + fn deserialize_bool>(self, v: V) -> Result { + self.0.deserialize_bool(Visit::any(v)) + } + fn deserialize_i8>(self, v: V) -> Result { + self.0.deserialize_i8(Visit::any(v)) + } + fn deserialize_i16>(self, v: V) -> Result { + self.0.deserialize_i16(Visit::any(v)) + } + fn deserialize_i32>(self, v: V) -> Result { + self.0.deserialize_i32(Visit::any(v)) + } + fn deserialize_i64>(self, v: V) -> Result { + self.0.deserialize_i64(Visit::any(v)) + } + fn deserialize_i128>(self, v: V) -> Result { + self.0.deserialize_i128(Visit::any(v)) + } + fn deserialize_u8>(self, v: V) -> Result { + self.0.deserialize_u8(Visit::any(v)) + } + fn deserialize_u16>(self, v: V) -> Result { + self.0.deserialize_u16(Visit::any(v)) + } + fn deserialize_u32>(self, v: V) -> Result { + self.0.deserialize_u32(Visit::any(v)) + } + fn deserialize_u64>(self, v: V) -> Result { + self.0.deserialize_u64(Visit::any(v)) + } + fn deserialize_u128>(self, v: V) -> Result { + self.0.deserialize_u128(Visit::any(v)) + } + fn deserialize_f32>(self, v: V) -> Result { + self.0.deserialize_f32(Visit::any(v)) + } + fn deserialize_char>(self, v: V) -> Result { + self.0.deserialize_char(Visit::any(v)) + } + fn deserialize_str>(self, v: V) -> Result { + self.0.deserialize_str(Visit::any(v)) + } + fn deserialize_string>(self, v: V) -> Result { + self.0.deserialize_string(Visit::any(v)) + } + fn deserialize_bytes>(self, v: V) -> Result { + self.0.deserialize_bytes(Visit::any(v)) + } + fn deserialize_byte_buf>(self, v: V) -> Result { + self.0.deserialize_byte_buf(Visit::any(v)) + } + fn deserialize_option>(self, v: V) -> Result { + self.0.deserialize_option(Visit::any(v)) + } + fn deserialize_unit>(self, v: V) -> Result { + self.0.deserialize_unit(Visit::any(v)) + } + fn deserialize_seq>(self, v: V) -> Result { + self.0.deserialize_seq(Visit::any(v)) + } + fn deserialize_map>(self, v: V) -> Result { + self.0.deserialize_map(Visit::any(v)) + } + fn deserialize_identifier>(self, v: V) -> Result { + self.0.deserialize_identifier(Visit::any(v)) + } + fn deserialize_ignored_any>(self, v: V) -> Result { + self.0.deserialize_ignored_any(Visit::any(v)) + } + fn deserialize_f64>(self, v: V) -> Result { + self.0.deserialize_any(Visit { + inner: v, + shape: Shape::Float, + }) + } + fn deserialize_struct>( + self, + _: &'static str, + _: &'static [&'static str], + v: V, + ) -> Result { + self.0.deserialize_any(Visit { + inner: v, + shape: Shape::Map, + }) + } + fn deserialize_unit_struct>( + self, + n: &'static str, + v: V, + ) -> Result { + self.0.deserialize_unit_struct(n, Visit::any(v)) + } + fn deserialize_newtype_struct>( + self, + n: &'static str, + v: V, + ) -> Result { + self.0.deserialize_newtype_struct(n, Visit::any(v)) + } + fn deserialize_tuple>(self, n: usize, v: V) -> Result { + self.0.deserialize_tuple(n, Visit::any(v)) + } + fn deserialize_tuple_struct>( + self, + n: &'static str, + len: usize, + v: V, + ) -> Result { + self.0.deserialize_tuple_struct(n, len, Visit::any(v)) + } + fn deserialize_enum>( + self, + n: &'static str, + variants: &'static [&'static str], + v: V, + ) -> Result { + self.0.deserialize_enum(n, variants, Visit::any(v)) + } + fn is_human_readable(&self) -> bool { + self.0.is_human_readable() + } +} +impl Shape { + fn allow(self, actual: Shape) -> Result<(), E> { + if matches!(self, Self::Any) + || matches!( + (self, actual), + (Self::Map, Self::Map) | (Self::Float, Self::Float) + ) + { + Ok(()) + } else { + Err(E::custom(match self { + Self::Map => "V4 structs require named maps", + Self::Float => "V4 f64 fields require float64 markers", + Self::Any => unreachable!(), + })) + } + } +} +impl<'de, V: Visitor<'de>> Visitor<'de> for Visit { + type Value = V::Value; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.inner.expecting(f) + } + fn visit_bool(self, v: bool) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_bool(v) + } + fn visit_i8(self, v: i8) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_i8(v) + } + fn visit_i16(self, v: i16) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_i16(v) + } + fn visit_i32(self, v: i32) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_i32(v) + } + fn visit_i64(self, v: i64) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_i64(v) + } + fn visit_i128(self, v: i128) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_i128(v) + } + fn visit_u8(self, v: u8) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_u8(v) + } + fn visit_u16(self, v: u16) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_u16(v) + } + fn visit_u32(self, v: u32) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_u32(v) + } + fn visit_u64(self, v: u64) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_u64(v) + } + fn visit_u128(self, v: u128) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_u128(v) + } + fn visit_f32(self, v: f32) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_f32(v) + } + fn visit_f64(self, v: f64) -> Result { + self.shape.allow(Shape::Float)?; + self.inner.visit_f64(v) + } + fn visit_char(self, v: char) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_char(v) + } + fn visit_str(self, v: &str) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_str(v) + } + fn visit_borrowed_str(self, v: &'de str) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_borrowed_str(v) + } + fn visit_string(self, v: String) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_string(v) + } + fn visit_bytes(self, v: &[u8]) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_bytes(v) + } + fn visit_borrowed_bytes(self, v: &'de [u8]) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_borrowed_bytes(v) + } + fn visit_byte_buf(self, v: Vec) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_byte_buf(v) + } + fn visit_unit(self) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_unit() + } + fn visit_none(self) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_none() + } + fn visit_some>(self, d: D) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_some(Strict(d)) + } + fn visit_newtype_struct>(self, d: D) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_newtype_struct(Strict(d)) + } + fn visit_seq>(self, a: A) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_seq(Access(a)) + } + fn visit_map>(self, a: A) -> Result { + self.shape.allow(Shape::Map)?; + self.inner.visit_map(Access(a)) + } + fn visit_enum>(self, a: A) -> Result { + self.shape.allow(Shape::Any)?; + self.inner.visit_enum(Access(a)) + } +} +struct Seed(S); +impl<'de, S: DeserializeSeed<'de>> DeserializeSeed<'de> for Seed { + type Value = S::Value; + fn deserialize>(self, d: D) -> Result { + self.0.deserialize(Strict(d)) + } +} +struct Access(A); +impl<'de, A: de::SeqAccess<'de>> de::SeqAccess<'de> for Access { + type Error = A::Error; + fn next_element_seed>( + &mut self, + s: S, + ) -> Result, A::Error> { + self.0.next_element_seed(Seed(s)) + } + fn size_hint(&self) -> Option { + self.0.size_hint() + } +} +impl<'de, A: de::MapAccess<'de>> de::MapAccess<'de> for Access { + type Error = A::Error; + fn next_key_seed>( + &mut self, + s: S, + ) -> Result, A::Error> { + self.0.next_key_seed(Seed(s)) + } + fn next_value_seed>(&mut self, s: S) -> Result { + self.0.next_value_seed(Seed(s)) + } + fn size_hint(&self) -> Option { + self.0.size_hint() + } +} +impl<'de, A: de::EnumAccess<'de>> de::EnumAccess<'de> for Access { + type Error = A::Error; + type Variant = Access; + fn variant_seed>( + self, + s: S, + ) -> Result<(S::Value, Self::Variant), A::Error> { + let (v, a) = self.0.variant_seed(Seed(s))?; + Ok((v, Access(a))) + } +} +impl<'de, A: de::VariantAccess<'de>> de::VariantAccess<'de> for Access { + type Error = A::Error; + fn unit_variant(self) -> Result<(), A::Error> { + self.0.unit_variant() + } + fn newtype_variant_seed>(self, s: S) -> Result { + self.0.newtype_variant_seed(Seed(s)) + } + fn tuple_variant>(self, n: usize, v: V) -> Result { + self.0.tuple_variant(n, Visit::any(v)) + } + fn struct_variant>( + self, + f: &'static [&'static str], + v: V, + ) -> Result { + self.0.struct_variant( + f, + Visit { + inner: v, + shape: Shape::Map, + }, + ) + } +} diff --git a/src/selection/storage/validate.rs b/src/selection/storage/validate.rs index db757b8..ba3cafb 100644 --- a/src/selection/storage/validate.rs +++ b/src/selection/storage/validate.rs @@ -24,6 +24,7 @@ fn at(path: String, message: impl Into) -> SelectionStorageError { fn record_identity(payload: &SelectionPayload) -> SelectionRecordKey { use SelectionRecordKind::*; let (kind, handle) = match payload { + SelectionPayload::Entity(v) => (Entity, v.common().handle), SelectionPayload::Line(v) => (Entity, v.common.handle), SelectionPayload::MLine(v) => (Entity, v.common.handle), SelectionPayload::MLineStyle(v) => (Object, v.handle), @@ -42,30 +43,10 @@ fn record_name(payload: &SelectionPayload) -> Option<&str> { } } -fn slot_count(payload: &SelectionPayload) -> usize { - match payload { - SelectionPayload::Line(_) => 3, - SelectionPayload::MLine(_) => 4, - SelectionPayload::Layer(_) => 1, - SelectionPayload::LineType(_) => 0, - SelectionPayload::MLineStyle(v) => 1 + v.elements.len(), - } -} - fn source_default(payload: &SelectionPayload) -> bool { matches!(payload, SelectionPayload::MLine(v) if v.style_handle.is_none_or(|h| h.is_null())) } -fn linetype_role(name: &str) -> Option { - if name.is_empty() || name.eq_ignore_ascii_case("BYLAYER") { - Some(ContextRole::ByLayer) - } else if name.eq_ignore_ascii_case("BYBLOCK") { - Some(ContextRole::ByBlock) - } else { - None - } -} - fn matches_source(req: &SelectionRequirement, handle: Option, name: &str) -> bool { req.source_handle == handle && req.source_name.as_deref() == Some(name) } @@ -74,19 +55,22 @@ fn resource_kind( payload: &SelectionPayload, req: &SelectionRequirement, ) -> std::result::Result, &'static str> { + use crate::selection::references::{describe_payload, EndpointSpec}; use RequirementDisposition::*; - use SelectionRecordKind as RecordKind; - use SelectionSlot::*; - let common = match payload { - SelectionPayload::Line(v) => Some(&v.common), - SelectionPayload::MLine(v) => Some(&v.common), - _ => None, - }; - let (kind, name, handle) = match (&req.slot, payload, common) { - (Owner, _, Some(c)) => { + let spec = describe_payload(req.source, payload) + .map_err(|_| "unsupported source payload")? + .into_iter() + .find(|s| s.slot == req.slot) + .ok_or("slot is incompatible with source payload")?; + let kind = spec.target_kind; + let (handle, name, inherited) = match spec.endpoint { + EndpointSpec::Owner { handle: _ } => { + let c = + super::super::entity_policy::common(payload).ok_or("owner without root common")?; let valid_role = match (&req.disposition, req.source_name.as_deref()) { (Context(ContextRole::ModelSpace), Some(name)) => { name.eq_ignore_ascii_case("*Model_Space") + && matches!(c.entity_mode, None | Some(0 | 2)) } (Context(ContextRole::PaperSpace), Some(name)) => { super::super::layout::paper_block_name(name) && c.entity_mode == Some(0) @@ -106,10 +90,10 @@ fn resource_kind( Err("inconsistent block owner requirement") }; } - (StyleRegistration, SelectionPayload::MLineStyle(v), _) => { - return if matches_source(req, Some(v.owner), &v.name) + EndpointSpec::StyleRegistration { handle, name } => { + return if matches_source(req, Some(handle), &name) && (req.disposition == Missing - || (!v.owner.is_null() + || (!handle.is_null() && req.disposition == Context(ContextRole::MLineStyleDictionary))) { Ok(None) @@ -117,38 +101,22 @@ fn resource_kind( Err("inconsistent MLINESTYLE registration requirement") }; } - (Layer, _, Some(c)) => (RecordKind::Layer, c.layer.as_str(), c.layer_handle), - (LineType, _, Some(c)) => (RecordKind::LineType, c.linetype.as_str(), c.linetype_handle), - (LineType, SelectionPayload::Layer(v), _) => { - (RecordKind::LineType, v.line_type.as_str(), None) - } - (StyleElementLineType(i), SelectionPayload::MLineStyle(v), _) => { - let el = v - .elements - .get(*i) - .ok_or("style element index is out of range")?; - (RecordKind::LineType, el.linetype.as_str(), None) - } - (MLineStyle, SelectionPayload::MLine(v), _) => { - let handle = v - .style_handle - .filter(|h| !h.is_null()) - .or(req.source_handle) + EndpointSpec::Stored { handle, name } => (handle, name, None), + EndpointSpec::Inheritance { handle, name, role } => (handle, name, Some(role)), + EndpointSpec::SourceDefault { name } => { + let handle = req + .source_handle .ok_or("effective MLINESTYLE handle is missing from requirement")?; if handle.is_null() && req.disposition != Missing { return Err("a null effective style handle requires a missing disposition"); } - (RecordKind::Object, v.style_name.as_str(), Some(handle)) + (Some(handle), name, None) } - _ => return Err("slot is incompatible with source payload"), }; - if !matches_source(req, handle, name) { + if !matches_source(req, handle, &name) { return Err("requirement disagrees with the stored source handle or name"); } - if let Some(role) = (kind == RecordKind::LineType) - .then(|| linetype_role(name)) - .flatten() - { + if let Some(role) = inherited { return if req.disposition == Context(role) || (req.disposition == Missing && handle.is_some_and(|h| !h.is_null())) { @@ -188,6 +156,13 @@ pub(super) fn selection(s: &DocumentSelection, version: frame::Version) -> Resul if s.namespace.trim().is_empty() { return Err(at("/namespace".into(), "selection namespace is empty")); } + let has_point = s.records.iter().any(|r| matches!(&r.payload, SelectionPayload::Entity(e) if matches!(e.as_ref(),crate::EntityType::Point(_)))); + if has_point != s.context.point_display.is_some() { + return Err(at( + "/context/point_display".into(), + "Point display context must be present exactly when Point is captured", + )); + } let mut records = BTreeMap::new(); let mut identities = BTreeSet::new(); let mut style_dictionary = None; @@ -201,6 +176,18 @@ pub(super) fn selection(s: &DocumentSelection, version: frame::Version) -> Resul "invalid or duplicate record identity", )); } + if let SelectionPayload::Entity(e) = &r.payload { + if version != frame::Version::V4 + || !super::super::entity_policy::is_leaf(e) + || !super::super::entity_policy::retained_common(e.common()) + { + return Err(at( + format!("/records/{i}/payload"), + "unsupported generic family or common attachment", + )); + } + super::super::field_coverage::check(e); + } records.insert(r.key, &r.payload); if let SelectionPayload::MLineStyle(v) = &r.payload { if !v.owner.is_null() && *style_dictionary.get_or_insert(v.owner) != v.owner { @@ -302,7 +289,10 @@ pub(super) fn selection(s: &DocumentSelection, version: frame::Version) -> Resul } } for (i, r) in s.records.iter().enumerate() { - if slot_counts.get(&r.key).copied().unwrap_or(0) != slot_count(&r.payload) { + let expected = super::super::references::describe(r) + .map_err(|e| at(format!("/records/{i}"), e.message))? + .len(); + if slot_counts.get(&r.key).copied().unwrap_or(0) != expected { return Err(at( format!("/records/{i}"), "record does not have exactly its required slots", @@ -413,7 +403,11 @@ fn evidence( slot.is_none() && matches!( payload, - Some(SelectionPayload::Line(_) | SelectionPayload::MLine(_)) + Some( + SelectionPayload::Line(_) + | SelectionPayload::MLine(_) + | SelectionPayload::Entity(_) + ) ), ) } @@ -449,3 +443,37 @@ fn evidence( } Ok(()) } + +#[cfg(test)] +mod model_owner_tests { + use super::*; + #[test] + fn generic_model_owner_rejects_unreviewed_entity_modes() { + let mut source = crate::Document::new(); + let root = source + .add_entity(crate::EntityType::Ray(crate::entities::Ray::new( + crate::Vector3::ZERO, + crate::Vector3::UNIT_X, + ))) + .unwrap(); + let mut request = CaptureRequest::new("mode boundary", vec![root]); + request.external.insert(SelectionRecordKey { + kind: SelectionRecordKind::Layer, + handle: source.layers.get("0").unwrap().handle, + }); + let mut s = DocumentSelection::capture(&source, &request) + .unwrap() + .selection; + assert!(selection(&s, frame::Version::V4).is_ok()); + for mode in [1, 3, 255] { + let SelectionPayload::Entity(e) = &mut s.records[0].payload else { + panic!() + }; + e.common_mut().entity_mode = Some(mode); + assert!( + selection(&s, frame::Version::V4).is_err(), + "unsupported model owner mode {mode}" + ); + } + } +} diff --git a/src/selection/storage/wire.rs b/src/selection/storage/wire.rs index a9640e1..227192c 100644 --- a/src/selection/storage/wire.rs +++ b/src/selection/storage/wire.rs @@ -111,6 +111,7 @@ macro_rules! text_enum { } mod payload; +mod v4; use payload::Payload; text_enum!(RecordKind(SelectionRecordKind) { @@ -233,10 +234,10 @@ struct Projection { string_bytes: usize, } impl Projection { - fn list( + fn list<'a, T, U>( &mut self, - values: &[T], - mut project: impl FnMut(&mut Self, &T) -> Result, + values: &'a [T], + mut project: impl FnMut(&mut Self, &'a T) -> Result, ) -> Result> { if values.len() > frame::COUNT_LIMIT || values.len() > self.array_items { return Err(error(Kind::LimitExceeded, "selection exceeds array budget")); @@ -258,9 +259,22 @@ impl Projection { } } -pub(super) fn read(body: &[u8]) -> Result { +pub(super) fn read(body: &[u8], version: frame::Version) -> Result { + if version == frame::Version::V4 { + return v4::read(body); + } let w: Selection = rmp_serde::from_slice(body).map_err(|e| error(Kind::InvalidBody, e.to_string()))?; + if w.records + .iter() + .any(|r| matches!(r.payload, Payload::Entity(_))) + { + return Err(error(Kind::InvalidBody, "entity requires V4")); + } + from_wire(w) +} + +fn from_wire(w: Selection) -> Result { Ok(DocumentSelection { namespace: w.namespace, roots: w.roots.into_iter().map(Into::into).collect(), @@ -298,11 +312,15 @@ pub(super) fn read(body: &[u8]) -> Result { context: SelectionContext { insertion_units: w.context.insertion_units, linetype_scale: f64::from_bits(w.context.linetype_scale), + point_display: None, }, }) } pub(super) fn write(s: &DocumentSelection, version: frame::Version) -> Result> { + if version == frame::Version::V4 { + return v4::write(s); + } let mut p = Projection { array_items: frame::VALUE_LIMIT, string_bytes: frame::BODY_LIMIT, diff --git a/src/selection/storage/wire/payload.rs b/src/selection/storage/wire/payload.rs index 89d6cc3..0ea7a14 100644 --- a/src/selection/storage/wire/payload.rs +++ b/src/selection/storage/wire/payload.rs @@ -786,6 +786,7 @@ impl LineTypeData { } } tagged!(pub(super) Payload { + "entity" => Entity(data: Box), "line" => Line(data: Box), "mline" => MLine(data: Box), "mline_style" => MLineStyle(data: Box), @@ -796,6 +797,9 @@ impl Payload { pub(super) fn from_model(p: &mut Projection, value: &SelectionPayload) -> Result { Ok(match value { SelectionPayload::Line(v) => Self::Line(Box::new(LineData::from_model(p, v)?)), + SelectionPayload::Entity(_) => { + return Err(invalid("generic entities require selection storage V4")) + } SelectionPayload::MLine(v) => Self::MLine(Box::new(MLineData::from_model(p, v)?)), SelectionPayload::MLineStyle(v) => { Self::MLineStyle(Box::new(StyleData::from_model(p, v)?)) @@ -808,6 +812,7 @@ impl Payload { } pub(super) fn into_model(self) -> Result { Ok(match self { + Self::Entity(v) => SelectionPayload::Entity(Box::new(v.0)), Self::Line(v) => SelectionPayload::Line(Box::new(v.into_model()?)), Self::MLine(v) => SelectionPayload::MLine(Box::new(v.into_model()?)), Self::MLineStyle(v) => SelectionPayload::MLineStyle(Box::new(v.into_model()?)), diff --git a/src/selection/storage/wire/v4.rs b/src/selection/storage/wire/v4.rs new file mode 100644 index 0000000..84b7fc2 --- /dev/null +++ b/src/selection/storage/wire/v4.rs @@ -0,0 +1,204 @@ +use super::super::model::{self, ModelBorrow}; +use super::*; + +const SCHEMA: &str = "acadrust-leaf-1"; +named_map!(PointDisplay { + mode: i16, + size: f64 +}); +named_map!(ContextV4 { insertion_units: i16, linetype_scale: u64, point_display: Option }); +named_map!(SelectionV4 { + model_schema: String, namespace: String, roots: Vec, records: Vec, + requirements: Vec, report: Vec, context: ContextV4, +}); + +enum PathToken { + Key(String), + Index(usize), + Variant, +} +fn path_tokens(path: &serde_ignored::Path<'_>) -> Vec { + use serde_ignored::Path; + let (parent, token) = match path { + Path::Root => return Vec::new(), + Path::Seq { parent, index } => (parent, Some(PathToken::Index(*index))), + Path::Map { parent, key } => (parent, Some(PathToken::Key(key.clone()))), + Path::NewtypeVariant { parent } => (parent, Some(PathToken::Variant)), + Path::Some { parent } | Path::NewtypeStruct { parent } => (parent, None), + }; + let mut tokens = path_tokens(parent); + tokens.extend(token); + tokens +} +fn model_pointer(tokens: &[PathToken], body: &SelectionV4) -> Option { + // serde_ignored omits enum tags. Recover the closed model tag from the + // already-read typed record, without a Value tree or geometry projection. + let model = match tokens { + [PathToken::Key(key), PathToken::Index(i), ..] if key == "records" => { + body.records.get(*i).and_then(|r| match &r.payload { + Payload::Entity(e) => Some(&e.0), + _ => None, + }) + } + _ => None, + }; + let mut parts = Vec::::new(); + let mut variant_seen = false; + for token in tokens { + match token { + PathToken::Key(key) => { + if parts.last().is_some_and(|p| p == "color") + && matches!( + model.map(|e| e.common().color), + Some(crate::Color::Rgb { .. }) + ) + { + parts.push("Rgb".into()); + } + parts.push(key.clone()); + } + PathToken::Index(i) => parts.push(i.to_string()), + PathToken::Variant => { + if variant_seen { + break; + } // Closest known node for an unsupported nested carrier. + let Some(tag) = model.and_then(super::super::super::entity_policy::leaf_tag) else { + break; + }; + parts.push(tag.into()); + variant_seen = true; + } + } + } + Some( + parts + .into_iter() + .map(|p| format!("/{}", p.replace('~', "~0").replace('/', "~1"))) + .collect(), + ) +} + +pub(super) fn read(body: &[u8]) -> Result { + let mut ignored = None; + let mut d = rmp_serde::Deserializer::new(body); + let w: SelectionV4 = serde_ignored::deserialize(super::super::strict::Strict(&mut d), |path| { + if ignored.is_none() { + ignored = Some((path_tokens(&path), path.to_string())); + } + }) + .map_err(|e| error(Kind::InvalidBody, e.to_string()))?; + if let Some((tokens, description)) = ignored { + let mut e = error( + Kind::InvalidBody, + format!("ignored model field at {description}"), + ); + e.path = model_pointer(&tokens, &w); + return Err(e); + } + if w.model_schema != SCHEMA { + return Err(error(Kind::UnsupportedVersion, "unsupported model schema")); + } + let point = w.context.point_display.map(|p| SelectionPointDisplay { + mode: p.mode, + size: p.size, + }); + let mut selection = from_wire(Selection { + namespace: w.namespace, + roots: w.roots, + records: w.records, + requirements: w.requirements, + report: w.report, + context: Context { + insertion_units: w.context.insertion_units, + linetype_scale: w.context.linetype_scale, + }, + })?; + selection.context.point_display = point; + Ok(selection) +} + +enum PayloadBorrow<'a> { + Legacy(Payload), + Entity(ModelBorrow<'a>), +} +impl Serialize for PayloadBorrow<'_> { + fn serialize(&self, s: S) -> std::result::Result { + match self { + Self::Legacy(p) => p.serialize(s), + Self::Entity(p) => ("entity", p).serialize(s), + } + } +} +#[derive(Serialize)] +struct RecordBorrow<'a> { + key: Key, + payload: PayloadBorrow<'a>, +} +#[derive(Serialize)] +struct SelectionBorrow<'a> { + model_schema: &'static str, + namespace: String, + roots: Vec, + records: Vec>, + requirements: Vec, + report: Vec, + context: ContextV4, +} +pub(super) fn write(s: &DocumentSelection) -> Result> { + let mut p = Projection { + array_items: frame::VALUE_LIMIT, + string_bytes: frame::BODY_LIMIT, + }; + let w = SelectionBorrow { + model_schema: SCHEMA, + namespace: p.text(&s.namespace)?, + roots: p.list(&s.roots, |_, k| Ok((*k).into()))?, + records: p.list(&s.records, |p, r| { + Ok(RecordBorrow { + key: r.key.into(), + payload: match &r.payload { + SelectionPayload::Entity(e) => PayloadBorrow::Entity(ModelBorrow(e)), + other => PayloadBorrow::Legacy(Payload::from_model(p, other)?), + }, + }) + })?, + requirements: p.list(&s.requirements, |p, r| { + Ok(Requirement { + source: r.source.into(), + slot: Slot::try_from(&r.slot)?, + source_handle: r.source_handle.map(|h| h.value()), + source_name: p.optional_text(&r.source_name)?, + disposition: (&r.disposition).into(), + }) + })?, + report: p.list(&s.report, |p, e| { + Ok(Evidence { + source: e.source.map(Into::into), + slot: e.slot.as_ref().map(Slot::try_from).transpose()?, + code: EvidenceCode(e.code), + message: p.text(&e.message)?, + }) + })?, + context: ContextV4 { + insertion_units: s.context.insertion_units, + linetype_scale: s.context.linetype_scale.to_bits(), + point_display: s.context.point_display.as_ref().map(|v| PointDisplay { + mode: v.mode, + size: v.size, + }), + }, + }; + model::measure(&w)?; + let mut out = frame::BoundedFrame::new(frame::Version::V4); + if let Err(e) = w.serialize(&mut rmp_serde::Serializer::new(&mut out).with_struct_map()) { + return Err(error( + if out.exceeded { + Kind::LimitExceeded + } else { + Kind::InvalidSelection + }, + e.to_string(), + )); + } + out.finish() +} diff --git a/tests/fixtures/selection/v4/README.md b/tests/fixtures/selection/v4/README.md new file mode 100644 index 0000000..ea01265 --- /dev/null +++ b/tests/fixtures/selection/v4/README.md @@ -0,0 +1,7 @@ +# Independent V4 fixtures + +Run `python make_fixtures.py` with Python 3 (standard library only). The author does not consume Rust writer output. Maps use named model fields, externally tagged EntityType variants, and float64 (0xcb) geometry; legacy context scale remains u64 bits. Ray uses WCS [2,3,4], unit X. Circle uses OCS [2,3,4], normal [0,1,0], radius 2.5 and negative-zero thickness. Both deliberately describe a missing layer. The complete dependency ledger remains validated on read. + +Model schema: acadrust-leaf-1; reviewed provider acadrust b4406bf5f00f113e8580e32c3ff8095b1d1bf322. Frames retain the OCADSEL header, version4, kind1, and a big-endian u32 body length. + +Also qualified against acadrust c978b989a9f218e281cf923ce1d2668ee4640bd7. The retained entity/type/handle-census sources are unchanged from the authoring revision. diff --git a/tests/fixtures/selection/v4/circle.msgpack b/tests/fixtures/selection/v4/circle.msgpack new file mode 100644 index 0000000..cf39fd3 Binary files /dev/null and b/tests/fixtures/selection/v4/circle.msgpack differ diff --git a/tests/fixtures/selection/v4/make_fixtures.py b/tests/fixtures/selection/v4/make_fixtures.py new file mode 100644 index 0000000..b3b1e75 --- /dev/null +++ b/tests/fixtures/selection/v4/make_fixtures.py @@ -0,0 +1,42 @@ +"""Independent V4 fixture author; Python standard library only, no Rust output.""" +import struct, hashlib +from pathlib import Path + +def pack(x): + if x is None: return b'\xc0' + if isinstance(x,bool): return bytes([0xc3 if x else 0xc2]) + if isinstance(x,float): return b'\xcb'+struct.pack('>d',x) + if isinstance(x,int): + if -32<=x<128: return bytes([x&255]) + return b'\xcf'+struct.pack('>Q',x) if x>=0 else b'\xd3'+struct.pack('>q',x) + if isinstance(x,str): + b=x.encode();return (bytes([0xa0+len(b)]) if len(b)<32 else b'\xd9'+bytes([len(b)]))+b + if isinstance(x,list): return bytes([0x90+len(x)])+b''.join(map(pack,x)) + if isinstance(x,dict): + n=len(x);return (bytes([0x80+n]) if n<16 else b'\xde'+struct.pack('>H',n))+b''.join(pack(k)+pack(v) for k,v in x.items()) + raise ValueError(x) + +def vector(x,y,z): return dict(x=float(x),y=float(y),z=float(z)) +def key(kind,handle): return dict(kind=kind,handle=handle) +def common(): + return dict(handle=16,layer='0',layer_handle=None,color='ByLayer',line_weight='ByLayer',linetype='ByLayer',linetype_handle=None, + linetype_scale=1.0,transparency='by_layer',color_name=None,invisible=False,extended_data=dict(records=[]),reactors=[], + xdictionary_handle=None,owner_handle=5,color_book_handle=None,full_visual_style_handle=None,face_visual_style_handle=None, + edge_visual_style_handle=None,material_flags=0,material_handle=None,shadow_flags=0,plotstyle_flags=0,plotstyle_handle=None, + entity_mode=2,r12_metadata=None) +def requirement(slot,handle,name,disposition): + return dict(source=key('entity',16),slot=[slot],source_handle=handle,source_name=name,disposition=disposition) +def fixture(family,geometry): + geometry=dict(common=common(),**geometry) + return dict(model_schema='acadrust-leaf-1',namespace='independent-v4',roots=[key('entity',16)], + records=[dict(key=key('entity',16),payload=['entity',{family:geometry}])], + requirements=[requirement('owner',5,'*Model_Space',['context','model_space']), + requirement('layer',None,'0',['missing']),requirement('linetype',None,'ByLayer',['context','by_layer'])], + report=[dict(source=key('entity',16),slot=['layer'],code='missing_dependency',message='layer absent')], + context=dict(insertion_units=4,linetype_scale=0x3ff0000000000000,point_display=None)) +if __name__=='__main__': + for name,geometry in [('Ray',dict(base_point=vector(2,3,4),direction=vector(1,0,0))), + ('Circle',dict(center=vector(2,3,4),radius=2.5,normal=vector(0,1,0),thickness=-0.0))]: + body=pack(fixture(name,geometry));data=b'OCADSEL\0'+struct.pack('>HBI',4,1,len(body))+body + path=Path(__file__).with_name(name.lower()+'.msgpack');path.write_bytes(data) + print(path.name,len(data),hashlib.sha256(data).hexdigest()) diff --git a/tests/fixtures/selection/v4/ray.msgpack b/tests/fixtures/selection/v4/ray.msgpack new file mode 100644 index 0000000..702ab55 Binary files /dev/null and b/tests/fixtures/selection/v4/ray.msgpack differ diff --git a/tests/mline_pilot.rs b/tests/mline_pilot.rs index 19ab0af..7fb4768 100644 --- a/tests/mline_pilot.rs +++ b/tests/mline_pilot.rs @@ -597,7 +597,26 @@ fn custom_mline_style_and_pattern_reopen_from_snapshot() { } #[test] -fn custom_mline_blocked_by_circle_survives_edit_and_reopen() { +fn custom_mline_is_no_longer_blocked_by_qualified_circle() { + let mut source = custom_mline_source(); + source + .add_entity(EntityType::Circle(opencaddocument::entities::Circle::new())) + .unwrap(); + let drawing = Ifcx.export_ifccad(&source).unwrap().drawing; + let (out, context) = Ifcx.import_ifccad_preserving(&drawing).unwrap(); + assert_eq!(context.blocked_entities().count(), 0); + assert!(out + .document + .entities() + .any(|e| matches!(e, EntityType::MLine(_)))); + assert!(out + .document + .entities() + .any(|e| matches!(e, EntityType::Circle(_)))); +} + +#[test] +fn custom_mline_blocked_by_unqualified_entity_survives_edit_and_reopen() { use opencaddocument::entities::Circle; use opencaddocument::ifccad::{ encode_ifccad_document, load_ifccad_bytes, IfccadPreservationBinding, @@ -609,6 +628,17 @@ fn custom_mline_blocked_by_circle_survives_edit_and_reopen() { source .add_entity(EntityType::Circle(Circle::from_center_radius(center, 2.0))) .unwrap(); + // Circle is now qualified by typed selection. Keep this test about a + // genuinely unqualified name carrier, while retaining the editable circle. + source + .add_entity(EntityType::Solid( + opencaddocument::entities::Solid::triangle( + Vector3::ZERO, + Vector3::UNIT_X, + Vector3::UNIT_Y, + ), + )) + .unwrap(); let (bytes, losses) = Ifcx.write(&source).unwrap(); assert!(losses.is_empty(), "{losses:?}"); let file = load_ifccad_bytes(&bytes, Default::default()).unwrap(); diff --git a/tests/selection_leaf_capture.rs b/tests/selection_leaf_capture.rs new file mode 100644 index 0000000..a1e3945 --- /dev/null +++ b/tests/selection_leaf_capture.rs @@ -0,0 +1,178 @@ +#![cfg(feature = "selection")] + +#[path = "support/selection_leaf.rs"] +mod support; + +use opencaddocument::selection::DocumentSelection; + +macro_rules! captures_leaf { + ($test:ident, $tag:literal) => { + #[test] + fn $test() { + let case = support::leaf_cases() + .into_iter() + .find(|(tag, _)| *tag == $tag) + .unwrap(); + let (source, request) = support::source_with_leaves(vec![case]); + let captured = DocumentSelection::capture(&source, &request); + assert!( + captured.is_ok(), + "{} capture failed: {:?}", + $tag, + captured.err() + ); + drop(source); + assert_eq!(captured.unwrap().selection.roots().len(), 1); + } + }; +} + +captures_leaf!(captures_point, "POINT"); +captures_leaf!(captures_circle, "CIRCLE"); +captures_leaf!(captures_arc, "ARC"); +captures_leaf!(captures_ellipse, "ELLIPSE"); +captures_leaf!(captures_lwpolyline, "LWPOLYLINE"); +captures_leaf!(captures_spline, "SPLINE"); +captures_leaf!(captures_ray, "RAY"); +captures_leaf!(captures_xline, "XLINE"); + +#[test] +fn all_leaf_families_share_entity_payload() { + use opencaddocument::selection::SelectionPayload; + use std::collections::BTreeSet; + let (source, request) = support::source_with_leaves(support::leaf_cases()); + let capture = DocumentSelection::capture(&source, &request).unwrap(); + drop(source); + let kinds: BTreeSet<_> = capture + .selection + .records() + .iter() + .filter_map(|record| match &record.payload { + SelectionPayload::Entity(entity) => Some(entity.as_entity().entity_type()), + _ => None, + }) + .collect(); + assert_eq!(capture.selection.roots().len(), 8); + assert_eq!( + kinds, + BTreeSet::from([ + "POINT", + "CIRCLE", + "ARC", + "ELLIPSE", + "LWPOLYLINE", + "SPLINE", + "RAY", + "XLINE" + ]) + ); +} + +#[test] +fn unsupported_family_is_located_error() { + use opencaddocument::selection::SelectionErrorKind; + use opencaddocument::{entities::Insert, EntityType}; + let (source, request) = support::source_with_leaves(vec![( + "INSERT", + EntityType::Insert(Insert::new("unused", opencaddocument::Vector3::ZERO)), + )]); + let error = DocumentSelection::capture(&source, &request).unwrap_err(); + assert_eq!(error.kind, SelectionErrorKind::UnsupportedContent); + assert_eq!(error.source.unwrap().handle, request.roots[0]); +} + +#[test] +fn point_display_context_is_captured_only_when_needed() { + let point = support::leaf_cases() + .into_iter() + .find(|(tag, _)| *tag == "POINT") + .unwrap(); + let (mut source, request) = support::source_with_leaves(vec![point]); + source.header.point_display_mode = 3; + source.header.point_display_size = -5.0; + let capture = DocumentSelection::capture(&source, &request).unwrap(); + let context = capture + .selection + .context() + .point_display + .as_ref() + .expect("POINT display context"); + assert_eq!(context.mode, 3); + assert_eq!(context.size.to_bits(), (-5.0_f64).to_bits()); + let circle = support::leaf_cases() + .into_iter() + .find(|(tag, _)| *tag == "CIRCLE") + .unwrap(); + let (source, request) = support::source_with_leaves(vec![circle]); + assert!(DocumentSelection::capture(&source, &request) + .unwrap() + .selection + .context() + .point_display + .is_none()); +} + +#[test] +fn legacy_line_mline_payloads_unchanged() { + use opencaddocument::entities::{Line, MLine}; + use opencaddocument::selection::SelectionPayload; + use opencaddocument::{EntityType, Vector3}; + let (source, request) = support::source_with_leaves(vec![ + ( + "LINE", + EntityType::Line(Line::from_points(Vector3::ZERO, Vector3::UNIT_X)), + ), + ( + "MLINE", + EntityType::MLine(MLine::from_points(&[Vector3::ZERO, Vector3::UNIT_X])), + ), + ]); + let capture = DocumentSelection::capture(&source, &request).unwrap(); + assert!(capture + .selection + .records() + .iter() + .any(|r| matches!(r.payload, SelectionPayload::Line(_)))); + assert!(capture + .selection + .records() + .iter() + .any(|r| matches!(r.payload, SelectionPayload::MLine(_)))); +} + +#[test] +fn attachments_are_not_silently_serialized() { + use opencaddocument::selection::SelectionErrorKind; + use opencaddocument::Handle; + for case in support::leaf_cases() { + let (mut source, request) = support::source_with_leaves(vec![case]); + source + .get_entity_mut(request.roots[0]) + .unwrap() + .common_mut() + .reactors + .push(Handle::new(999)); + let err = DocumentSelection::capture(&source, &request).unwrap_err(); + assert_eq!(err.kind, SelectionErrorKind::UnsupportedContent); + assert_eq!(err.source.unwrap().handle, request.roots[0]); + } +} + +#[test] +fn graphics_exclusion_is_reported_for_new_roots() { + use opencaddocument::selection::CaptureEvidenceCode; + for case in support::leaf_cases() { + let (mut source, request) = support::source_with_leaves(vec![case]); + source + .get_entity_mut(request.roots[0]) + .unwrap() + .common_mut() + .graphic_data = Some(vec![1, 2, 3]); + let capture = DocumentSelection::capture(&source, &request).unwrap(); + assert!(capture + .selection + .capture_report() + .iter() + .any(|e| e.code == CaptureEvidenceCode::ExcludedGraphics)); + } +} diff --git a/tests/selection_leaf_readback.rs b/tests/selection_leaf_readback.rs new file mode 100644 index 0000000..771c410 --- /dev/null +++ b/tests/selection_leaf_readback.rs @@ -0,0 +1,653 @@ +#![cfg(feature = "selection-storage")] +#[path = "support/selection_leaf.rs"] +mod support; +use opencaddocument::selection::*; +use opencaddocument::{Document, EntityType, Vector3}; +use std::collections::BTreeMap; +fn capture(cases: Vec<(&str, EntityType)>) -> DocumentSelection { + let (source, request) = support::source_with_leaves(cases); + let s = DocumentSelection::capture(&source, &request) + .unwrap() + .selection; + opencaddocument::selection_storage::decode( + &opencaddocument::selection_storage::encode(&s).unwrap(), + ) + .unwrap() +} +fn request( + s: &DocumentSelection, + target: &Document, + transform: SelectionPlacement, +) -> ReconstructionRequest { + ReconstructionRequest { + model_space: target.header.model_space_block_handle, + coordinates: CoordinatePolicy::DrawingCoordinates, + roots: s + .roots() + .iter() + .map(|&root| RootReconstruction { + root, + transform, + order: SelectionDrawOrder::Append, + layer: Some(target.layers.get("0").unwrap().handle), + linetype: None, + appearance: RootAppearanceOverrides::default(), + }) + .collect(), + resources: BTreeMap::new(), + external: vec![], + } +} +fn applied( + s: &DocumentSelection, + target: &Document, + transform: SelectionPlacement, +) -> Vec { + let out = s + .reconstruct_available(target, &request(s, target, transform)) + .unwrap(); + out.roots + .iter() + .map(|r| match r.status { + RootReconstructionStatus::Applied { entity, .. } => { + out.document.get_entity(entity).unwrap().clone() + } + _ => panic!("{:?}", r.status), + }) + .collect() +} +#[test] +fn identity_keeps_leaf_fields() { + let s = capture(support::leaf_cases()); + let values = applied(&s, &Document::new(), SelectionPlacement::Identity); + for (original, restored) in support::leaf_cases().iter().map(|(_, e)| e).zip(values) { + let mut expected = original.clone(); + *expected.common_mut() = restored.common().clone(); + assert_eq!(restored, expected); + } +} +#[test] +fn wcs_translation_respects_ocs() { + let mut cases = support::leaf_cases(); + for (_, e) in &mut cases { + match e { + EntityType::Circle(v) => { + v.center = Vector3::new(2.0, 3.0, 4.0); + v.normal = Vector3::UNIT_Y; + } + EntityType::Arc(v) => { + v.center = Vector3::new(2.0, 3.0, 4.0); + v.normal = Vector3::UNIT_Y; + } + EntityType::LwPolyline(v) => { + v.normal = Vector3::UNIT_Y; + v.elevation = 4.0; + } + EntityType::Ray(v) => v.base_point = Vector3::new(2.0, 3.0, 4.0), + EntityType::XLine(v) => v.base_point = Vector3::new(2.0, 3.0, 4.0), + _ => {} + } + } + let s = capture(cases); + for e in applied( + &s, + &Document::new(), + SelectionPlacement::Translate(Vector3::new(8.0, 2.0, 0.0)), + ) { + match e { + EntityType::Circle(v) => { + assert_eq!(v.center, Vector3::new(-6.0, 3.0, 6.0)); + assert_eq!(v.normal, Vector3::UNIT_Y); + assert_eq!(v.radius, 1.0); + } + EntityType::Arc(v) => { + assert_eq!(v.center, Vector3::new(-6.0, 3.0, 6.0)); + assert_eq!(v.normal, Vector3::UNIT_Y); + } + EntityType::LwPolyline(v) => { + assert_eq!(v.vertices[0].location.x, -6.0); + assert_eq!(v.elevation, 6.0); + assert_eq!(v.vertices[0].bulge, 0.5); + } + EntityType::Ray(v) => { + assert_eq!(v.base_point, Vector3::new(10.0, 5.0, 4.0)); + assert_eq!(v.direction, Vector3::UNIT_X); + } + EntityType::XLine(v) => { + assert_eq!(v.base_point, Vector3::new(10.0, 5.0, 4.0)); + assert_eq!(v.direction, Vector3::UNIT_Y); + } + _ => {} + } + } +} +#[test] +fn invalid_leaf_or_overflow_is_blocked() { + let mut bad = opencaddocument::entities::Point::new(); + bad.location.x = f64::NAN; + let s = capture(vec![("POINT", EntityType::Point(bad))]); + let target = Document::new(); + let out = s + .reconstruct_available(&target, &request(&s, &target, SelectionPlacement::Identity)) + .unwrap(); + assert!( + matches!(&out.roots[0].status,RootReconstructionStatus::Blocked { reasons } if reasons[0].kind==ReconstructionBlockerKind::InvalidGeometry) + ); + assert_eq!(out.document, target); +} + +#[test] +fn point_display_context_blocks_only_point() { + let (mut source, req) = + support::source_with_leaves(support::leaf_cases().into_iter().take(2).collect()); + source.header.point_display_mode = 3; + source.header.point_display_size = -5.0; + let s = DocumentSelection::capture(&source, &req).unwrap().selection; + let mut target = Document::new(); + let out = s + .reconstruct_available(&target, &request(&s, &target, SelectionPlacement::Identity)) + .unwrap(); + assert!( + matches!(&out.roots[0].status,RootReconstructionStatus::Blocked { reasons } if reasons[0].kind==ReconstructionBlockerKind::ContextMismatch) + ); + assert!(matches!( + out.roots[1].status, + RootReconstructionStatus::Applied { .. } + )); + assert_eq!(out.document.header.point_display_mode, 0); + assert_eq!(out.document.header.point_display_size, 0.0); + target.header.point_display_mode = 3; + target.header.point_display_size = -5.0; + assert_eq!(applied(&s, &target, SelectionPlacement::Identity).len(), 2); + target.header.point_display_size = f64::NAN; + let out = s + .reconstruct_available(&target, &request(&s, &target, SelectionPlacement::Identity)) + .unwrap(); + assert!( + matches!(&out.roots[0].status,RootReconstructionStatus::Blocked { reasons } if reasons[0].kind==ReconstructionBlockerKind::ContextMismatch) + ); +} +#[test] +fn geometry_structure_boundaries_and_large_finite_direction() { + use opencaddocument::entities::*; + let mut cases = Vec::new(); + let mut p = Point::new(); + p.normal = Vector3::ZERO; + cases.push(("POINT", EntityType::Point(p))); + let mut c = Circle::new(); + c.radius = 0.0; + cases.push(("CIRCLE", EntityType::Circle(c))); + let mut a = Arc::new(); + a.radius = -1.0; + cases.push(("ARC", EntityType::Arc(a))); + let mut e = Ellipse::new(); + e.minor_axis_ratio = 2.0; + cases.push(("ELLIPSE", EntityType::Ellipse(e))); + let mut l = LwPolyline::from_points(vec![ + opencaddocument::Vector2::ZERO, + opencaddocument::Vector2::UNIT_X, + ]); + l.vertices[0].start_width = -1.0; + cases.push(("LWPOLYLINE", EntityType::LwPolyline(l))); + cases.push(("SPLINE", EntityType::Spline(Spline::new()))); + cases.push(( + "RAY", + EntityType::Ray(Ray::new(Vector3::ZERO, Vector3::ZERO)), + )); + cases.push(( + "XLINE", + EntityType::XLine(XLine::new(Vector3::ZERO, Vector3::ZERO)), + )); + let s = capture(cases); + let target = Document::new(); + let out = s + .reconstruct_available(&target, &request(&s, &target, SelectionPlacement::Identity)) + .unwrap(); + assert!(out.roots.iter().all(|r| matches!(&r.status,RootReconstructionStatus::Blocked { reasons } if reasons[0].kind==ReconstructionBlockerKind::InvalidGeometry))); + assert_eq!(out.document, target); + for field in [0, 1, 2, 3] { + let (_, mut entity) = support::leaf_cases().remove(5); + let EntityType::Spline(v) = &mut entity else { + unreachable!() + }; + match field { + 0 => v.knots.pop().map(|_| ()).unwrap(), + 1 => v.knots = vec![0.0, 1.0, 0.0, 1.0], + 2 => v.weights = vec![1.0], + _ => v.weights = vec![1.0, -1.0], + } + let s = capture(vec![("SPLINE", entity)]); + let out = s + .reconstruct_available(&target, &request(&s, &target, SelectionPlacement::Identity)) + .unwrap(); + assert!(matches!( + out.roots[0].status, + RootReconstructionStatus::Blocked { .. } + )); + } + let mut ray = Ray::new(Vector3::new(f64::MAX, 0.0, 0.0), Vector3::UNIT_X); + ray.direction = Vector3::new(f64::MAX, f64::MAX, 0.0); + let s = capture(vec![("RAY", EntityType::Ray(ray))]); + assert_eq!(applied(&s, &target, SelectionPlacement::Identity).len(), 1); + let out = s + .reconstruct_available( + &target, + &request( + &s, + &target, + SelectionPlacement::Translate(Vector3::new(f64::MAX, 0.0, 0.0)), + ), + ) + .unwrap(); + assert!( + matches!(&out.roots[0].status,RootReconstructionStatus::Blocked { reasons } if reasons[0].kind==ReconstructionBlockerKind::InvalidGeometry) + ); + assert_eq!(out.document, target); +} + +fn gallery_cases() -> Vec<(&'static str, EntityType)> { + use opencaddocument::entities::{Line, MLine, Spline}; + let mut cases = support::leaf_cases(); + cases.push(( + "LINE", + EntityType::Line(Line::from_points( + Vector3::new(2.0, 3.0, 0.0), + Vector3::new(7.0, 5.0, 0.0), + )), + )); + cases.push(( + "MLINE", + EntityType::MLine(MLine::from_points(&[ + Vector3::new(2.0, 3.0, 0.0), + Vector3::new(7.0, 5.0, 0.0), + ])), + )); + cases.push(( + "FIT_SPLINE", + EntityType::Spline(Spline::from_fit_points(vec![ + Vector3::new(10.0, 0.0, 0.0), + Vector3::new(12.0, 3.0, 0.0), + Vector3::new(15.0, 0.0, 0.0), + ])), + )); + cases +} +fn add_definition(doc: &mut Document, name: &str) -> opencaddocument::Handle { + let mut block = opencaddocument::tables::BlockRecord::new(name); + block.handle = doc.allocate_handle(); + block.block_entity_handle = doc.allocate_handle(); + block.block_end_handle = doc.allocate_handle(); + let handle = block.handle; + doc.block_records.add(block).unwrap(); + handle +} +fn add_member( + doc: &mut Document, + mut entity: EntityType, + owner: opencaddocument::Handle, +) -> opencaddocument::Handle { + entity.common_mut().owner_handle = owner; + doc.add_entity(entity).unwrap() +} +fn layout(doc: &Document, name: &str) -> (opencaddocument::Handle, opencaddocument::Handle) { + doc.objects + .iter() + .find_map(|(&h, o)| match o { + opencaddocument::objects::ObjectType::Layout(l) if l.name == name => { + Some((h, l.block_record)) + } + _ => None, + }) + .unwrap() +} +fn numeric(v: f64, w: f64) { + assert!((v - w).abs() < 1e-9, "{v} != {w}"); +} +fn point(v: Vector3, w: Vector3) { + numeric(v.x, w.x); + numeric(v.y, w.y); + numeric(v.z, w.z); +} +fn geometry_oracle(expected: &EntityType, actual: &EntityType) { + match (expected, actual) { + (EntityType::Point(a), EntityType::Point(b)) => { + point(a.location, b.location); + point(a.normal, b.normal); + numeric(a.thickness, b.thickness); + } + (EntityType::Circle(a), EntityType::Circle(b)) => { + point(a.center, b.center); + point(a.normal, b.normal); + numeric(a.radius, b.radius); + } + (EntityType::Arc(a), EntityType::Arc(b)) => { + point(a.center, b.center); + point(a.normal, b.normal); + numeric(a.radius, b.radius); + numeric(a.start_angle, b.start_angle); + numeric(a.end_angle, b.end_angle); + } + (EntityType::Ellipse(a), EntityType::Ellipse(b)) => { + point(a.center, b.center); + point(a.major_axis, b.major_axis); + point(a.normal, b.normal); + numeric(a.minor_axis_ratio, b.minor_axis_ratio); + numeric(a.start_parameter, b.start_parameter); + numeric(a.end_parameter, b.end_parameter); + } + (EntityType::LwPolyline(a), EntityType::LwPolyline(b)) => { + assert_eq!(a.vertices.len(), b.vertices.len()); + point(a.normal, b.normal); + numeric(a.elevation, b.elevation); + for (a, b) in a.vertices.iter().zip(&b.vertices) { + numeric(a.location.x, b.location.x); + numeric(a.location.y, b.location.y); + numeric(a.bulge, b.bulge); + numeric(a.start_width, b.start_width); + numeric(a.end_width, b.end_width); + assert_eq!(a.vertex_id, b.vertex_id); + } + } + (EntityType::Spline(a), EntityType::Spline(b)) => { + assert_eq!(a.degree, b.degree); + if !a.control_points.is_empty() { + assert_eq!(a.control_points.len(), b.control_points.len()); + } + assert_eq!(a.fit_points.len(), b.fit_points.len()); + for (a, b) in a.control_points.iter().zip(&b.control_points) { + point(*a, *b); + } + for (a, b) in a.fit_points.iter().zip(&b.fit_points) { + point(*a, *b); + } + if !a.control_points.is_empty() { + assert_eq!(a.knots, b.knots); + assert_eq!(a.weights, b.weights); + } + } + (EntityType::Ray(a), EntityType::Ray(b)) => { + point(a.base_point, b.base_point); + point(a.direction, b.direction); + } + (EntityType::XLine(a), EntityType::XLine(b)) => { + point(a.base_point, b.base_point); + point(a.direction, b.direction); + } + (EntityType::Line(a), EntityType::Line(b)) => { + point(a.start, b.start); + point(a.end, b.end); + } + (EntityType::MLine(a), EntityType::MLine(b)) => { + assert_eq!(a.vertices.len(), b.vertices.len()); + for (a, b) in a.vertices.iter().zip(&b.vertices) { + point(a.position, b.position); + point(a.direction, b.direction); + point(a.miter, b.miter); + } + numeric(a.scale_factor, b.scale_factor); + } + _ => panic!("family mismatch: {expected:?} versus {actual:?}"), + } +} +fn mixed_gallery(format: &dyn opencaddocument::Format, extension: &str) { + use opencaddocument::{entities::Insert, Handle}; + let mut target = Document::new(); + target.add_layout("Sheet B").unwrap(); + let inner = add_definition(&mut target, "Inner"); + let outer = add_definition(&mut target, "Outer"); + add_member( + &mut target, + EntityType::Insert(Insert::new("Inner", Vector3::new(4.0, 5.0, 0.0))), + outer, + ); + let placements = [50.0, 60.0].map(|x| { + target + .add_entity(EntityType::Insert(Insert::new( + "Outer", + Vector3::new(x, 10.0, 0.0), + ))) + .unwrap() + }); + let owners = [ + target.header.model_space_block_handle, + layout(&target, "Layout1").1, + layout(&target, "Sheet B").1, + inner, + ]; + let anchors = owners.map(|owner| { + add_member( + &mut target, + EntityType::Line(opencaddocument::Line::from_points( + Vector3::new(-100.0, 0.0, 0.0), + Vector3::new(-100.0, 1.0, 0.0), + )), + owner, + ) + }); + // Explicit sparse SortEnts rank on each existing anchor. + for (owner, anchor) in owners.into_iter().zip(anchors) { + let ext = target.ensure_extension_dictionary(owner); + let h = target.allocate_handle(); + let mut sort = opencaddocument::objects::SortEntitiesTable::for_block(owner); + sort.owner_handle = ext; + sort.handle = h; + sort.add_entry(anchor, opencaddocument::Handle::new(1)); + target.objects.insert( + h, + opencaddocument::objects::ObjectType::SortEntitiesTable(sort), + ); + let Some(opencaddocument::objects::ObjectType::Dictionary(d)) = + target.objects.get_mut(&ext) + else { + panic!() + }; + d.add_entry( + opencaddocument::objects::SortEntitiesTable::DICTIONARY_KEY, + h, + ); + } + let mut source = target.clone(); + let model = source.header.model_space_block_handle; + let sheet_a = layout(&source, "Layout1").1; + let sheet_b = layout(&source, "Sheet B").1; + let mut groups = Vec::new(); + let mut all = Vec::new(); + for owner in [model, sheet_a, sheet_b, inner] { + let roots = gallery_cases() + .into_iter() + .map(|(_, e)| add_member(&mut source, e, owner)) + .collect::>(); + all.extend_from_slice(&roots); + groups.push(roots); + } + let mut capture_request = CaptureRequest::new("mixed-gallery", all); + capture_request.external.insert(SelectionRecordKey { + kind: SelectionRecordKind::Layer, + handle: source.layers.get("0").unwrap().handle, + }); + let selection = DocumentSelection::capture(&source, &capture_request) + .unwrap() + .selection; + let bytes = opencaddocument::selection_storage::encode(&selection).unwrap(); + drop(source); + let selection = opencaddocument::selection_storage::decode(&bytes).unwrap(); + let EntityType::Insert(moving) = target.get_entity_mut(placements[0]).unwrap() else { + panic!() + }; + moving.insert_point = Vector3::new(35.0, -15.0, 4.0); + moving.rotation = std::f64::consts::FRAC_PI_3; + let baseline = target.clone(); + let style = selection + .records() + .iter() + .find(|r| matches!(r.payload, SelectionPayload::MLineStyle(_))) + .unwrap() + .key; + let mut results = Vec::new(); + for (index, handles) in groups.iter().enumerate() { + let mut req = request(&selection, &target, SelectionPlacement::Identity); + req.roots.retain(|r| handles.contains(&r.root.handle)); + for root in &mut req.roots { + root.order = SelectionDrawOrder::Before(anchors[index]); + } + // One shared native style reused for each owner; bindings stay centralized. + req.resources.insert( + style, + ResourceAction::Reuse(target.header.current_multiline_style_handle), + ); + let outcome = match index { + 0 => selection.reconstruct_available(&target, &req), + 1 | 2 => selection.reconstruct_paperspace( + &target, + &PaperSpaceReconstructionRequest { + layout: layout(&target, if index == 1 { "Layout1" } else { "Sheet B" }).0, + coordinates: req.coordinates, + roots: req.roots, + resources: req.resources, + external: req.external, + }, + ), + _ => selection.reconstruct_in_block_definition( + &target, + &BlockDefinitionReconstructionRequest { + block_record: inner, + coordinates: req.coordinates, + roots: req.roots, + resources: req.resources, + external: req.external, + }, + ), + } + .unwrap(); + let restored = outcome + .roots + .iter() + .map(|r| match r.status { + RootReconstructionStatus::Applied { entity, .. } => entity, + _ => panic!("{:?}", r.status), + }) + .collect::>(); + assert_eq!(restored.len(), gallery_cases().len()); + results.push(restored); + target = outcome.document; + } + for h in placements { + assert_eq!(target.get_entity(h), baseline.get_entity(h)); + } + let (cad, losses) = format.write(&target).unwrap(); + assert!(losses.is_empty(), "{losses:?}"); + let (reopened, losses) = format.read(&cad).unwrap(); + assert!(losses.is_empty(), "{losses:?}"); + for (index, handles) in results.iter().enumerate() { + let owner = match index { + 0 => reopened.header.model_space_block_handle, + 1 => layout(&reopened, "Layout1").1, + 2 => layout(&reopened, "Sheet B").1, + _ => reopened.block_records.get("Inner").unwrap().handle, + }; + let ext = reopened.extension_dictionary_handle(owner).unwrap(); + let opencaddocument::objects::ObjectType::Dictionary(d) = &reopened.objects[&ext] else { + panic!() + }; + let sort = d + .get(opencaddocument::objects::SortEntitiesTable::DICTIONARY_KEY) + .unwrap(); + let opencaddocument::objects::ObjectType::SortEntitiesTable(sort) = + &reopened.objects[&sort] + else { + panic!() + }; + let mut ordered = reopened + .block_records + .iter() + .find(|b| b.handle == owner) + .unwrap() + .entity_handles + .clone(); + ordered.sort_by_key(|h| sort.effective_sort_handle(*h)); + let actual = ordered + .into_iter() + .filter(|h| handles.contains(h) || *h == anchors[index]) + .collect::>(); + let mut expected_order = handles.clone(); + expected_order.push(anchors[index]); + assert_eq!(actual, expected_order); + for ((_, expected), handle) in gallery_cases().iter().zip(handles) { + let actual = reopened.get_entity(*handle).unwrap(); + assert_eq!(actual.common().owner_handle, owner); + assert_eq!(actual.common().layer, "0"); + geometry_oracle(expected, actual); + } + } + let current = reopened + .entities() + .filter_map(|e| match e { + EntityType::Insert(i) if i.block_name == "Outer" => Some((i.insert_point, i.rotation)), + _ => None, + }) + .collect::>(); + assert_eq!(current.len(), 2); + assert!(current + .iter() + .any(|(p, r)| *p == Vector3::new(35.0, -15.0, 4.0) + && (*r - std::f64::consts::FRAC_PI_3).abs() < 1e-12)); + assert!(current + .iter() + .any(|(p, r)| *p == Vector3::new(60.0, 10.0, 0.0) && *r == 0.0)); + if let Some(dir) = std::env::var_os("SELECTION_REVIEW_DIR") { + std::fs::write( + std::path::PathBuf::from(dir).join(format!("selection-gallery.{extension}")), + cad, + ) + .unwrap(); + } +} +#[test] +fn mixed_gallery_dwg_preserves_current_nested_placements() { + mixed_gallery(&opencaddocument::Dwg, "dwg"); +} +#[test] +fn mixed_gallery_dxf_preserves_current_nested_placements() { + mixed_gallery(&opencaddocument::Dxf, "dxf"); +} + +#[test] +fn malformed_unselected_leaf_in_another_owner_is_an_error_not_a_panic() { + use opencaddocument::entities::{Ray, XLine}; + let s = capture( + support::leaf_cases() + .into_iter() + .filter(|(name, _)| *name == "CIRCLE") + .collect(), + ); + for duplicate in [false, true] { + let mut target = Document::new(); + let a = target + .add_entity_to_layout( + EntityType::Ray(Ray::new(Vector3::ZERO, Vector3::UNIT_X)), + "Layout1", + ) + .unwrap(); + if duplicate { + let b = target + .add_entity_to_layout( + EntityType::XLine(XLine::new(Vector3::ZERO, Vector3::UNIT_Y)), + "Layout1", + ) + .unwrap(); + target.get_entity_mut(b).unwrap().common_mut().handle = a; + } else { + target.get_entity_mut(a).unwrap().common_mut().handle = + opencaddocument::Handle::new(999); + } + let before = target.clone(); + let floor = target.next_handle(); + let seed = target.header.handle_seed; + assert!(s + .reconstruct_available(&target, &request(&s, &target, SelectionPlacement::Identity)) + .is_err()); + assert_eq!(target, before); + assert_eq!(target.next_handle(), floor); + assert_eq!(target.header.handle_seed, seed); + } +} diff --git a/tests/selection_leaf_storage.rs b/tests/selection_leaf_storage.rs new file mode 100644 index 0000000..6cb139b --- /dev/null +++ b/tests/selection_leaf_storage.rs @@ -0,0 +1,341 @@ +#![cfg(feature = "selection-storage")] +#[path = "support/selection_leaf.rs"] +mod support; + +use opencaddocument::selection::{DocumentSelection, SelectionPayload}; +use opencaddocument::selection_storage::{decode, encode}; + +#[test] +fn v4_roundtrips_all_eight_families_after_source_drop() { + let (source, request) = support::source_with_leaves(support::leaf_cases()); + let selection = DocumentSelection::capture(&source, &request) + .unwrap() + .selection; + drop(source); + let bytes = encode(&selection).expect("generic V4 storage"); + assert_eq!(&bytes[8..10], &[0, 4]); + let restored = decode(&bytes).unwrap(); + assert_eq!(restored, selection); + assert_eq!( + restored + .records() + .iter() + .filter(|r| matches!(r.payload, SelectionPayload::Entity(_))) + .count(), + 8 + ); +} + +#[test] +fn float_bits_survive_generic_storage() { + use opencaddocument::{entities::Point, EntityType, Vector3}; + let values = [ + -0.0, + f64::from_bits(0x7ff8_0000_0000_0042), + f64::from_bits(0xfff8_0000_0000_0099), + ]; + let mut point = Point::new(); + point.location = Vector3::new(values[0], values[1], values[2]); + let (source, request) = support::source_with_leaves(vec![("POINT", EntityType::Point(point))]); + let selection = DocumentSelection::capture(&source, &request) + .unwrap() + .selection; + let restored = decode(&encode(&selection).unwrap()).unwrap(); + let point = restored + .records() + .iter() + .find_map(|r| match &r.payload { + SelectionPayload::Entity(e) => match e.as_ref() { + EntityType::Point(v) => Some(v), + _ => None, + }, + _ => None, + }) + .unwrap(); + assert_eq!( + [ + point.location.x.to_bits(), + point.location.y.to_bits(), + point.location.z.to_bits() + ], + values.map(f64::to_bits) + ); +} + +#[test] +fn legacy_owner_version_stays_unchanged() { + use opencaddocument::{entities::Line, EntityType, Vector3}; + let (source, request) = support::source_with_leaves(vec![( + "LINE", + EntityType::Line(Line::from_points(Vector3::ZERO, Vector3::UNIT_X)), + )]); + let selection = DocumentSelection::capture(&source, &request) + .unwrap() + .selection; + let bytes = encode(&selection).unwrap(); + assert_eq!(&bytes[8..10], &[0, 1]); + assert_eq!(decode(&bytes).unwrap(), selection); +} + +fn one(name: &str) -> Vec { + let cases = support::leaf_cases() + .into_iter() + .filter(|(n, _)| *n == name) + .collect(); + let (source, request) = support::source_with_leaves(cases); + encode( + &DocumentSelection::capture(&source, &request) + .unwrap() + .selection, + ) + .unwrap() +} +fn framed(body: &[u8], version: u8) -> Vec { + let mut b = b"OCADSEL\0".to_vec(); + b.extend_from_slice(&[0, version, 1]); + b.extend_from_slice(&(body.len() as u32).to_be_bytes()); + b.extend_from_slice(body); + b +} +fn changed(name: &str, f: impl FnOnce(&mut serde_json::Value)) -> Vec { + let bytes = one(name); + let mut v: serde_json::Value = rmp_serde::from_slice(&bytes[15..]).unwrap(); + f(&mut v); + framed(&rmp_serde::to_vec_named(&v).unwrap(), 4) +} +#[test] +fn v4_checks_actual_model_schema() { + let b = changed("RAY", |v| v["model_schema"] = "future".into()); + assert_eq!( + decode(&b).unwrap_err().kind, + opencaddocument::selection_storage::SelectionStorageErrorKind::UnsupportedVersion + ); +} +#[test] +fn rejects_ignored_model_and_skipped_raw_fields() { + for key in ["future_geometry", "raw_record"] { + let b = changed("RAY", |v| { + v["records"][0]["payload"][1]["Ray"]["common"][key] = serde_json::json!({"x":1}) + }); + let e = decode(&b).unwrap_err(); + assert!(e.message.contains("ignored"), "{e}"); + assert!(e.path.unwrap().contains(key)); + } + let b = changed("LWPOLYLINE", |v| { + v["records"][0]["payload"][1]["LwPolyline"]["vertices"][0]["new_field"] = 3.into() + }); + assert!(decode(&b).unwrap_err().message.contains("ignored")); +} +#[test] +fn point_context_roundtrips_and_is_required() { + let cases = support::leaf_cases() + .into_iter() + .filter(|(n, _)| *n == "POINT") + .collect(); + let (mut source, request) = support::source_with_leaves(cases); + source.header.point_display_mode = 3; + source.header.point_display_size = -5.0; + let s = DocumentSelection::capture(&source, &request) + .unwrap() + .selection; + assert_eq!( + decode(&encode(&s).unwrap()) + .unwrap() + .context() + .point_display, + s.context().point_display + ); + for remove in [false, true] { + let b = changed("POINT", |v| { + if remove { + v["context"] + .as_object_mut() + .unwrap() + .remove("point_display"); + } else { + v["context"]["point_display"] = serde_json::Value::Null; + } + }); + assert!(decode(&b).is_err()); + } +} +#[test] +fn rejects_inconsistent_root_ledger_and_attachments() { + for b in [ + changed("RAY", |v| v["requirements"].as_array_mut().unwrap().clear()), + changed("RAY", |v| { + v["records"][0]["payload"][1]["Ray"]["common"]["reactors"] = serde_json::json!([900]) + }), + changed("RAY", |v| v["roots"][0]["handle"] = 999.into()), + ] { + assert!(decode(&b).is_err()); + } +} +#[test] +fn rejects_float32_binary_extensions_and_legacy_float64() { + for body in [vec![0xca, 0, 0, 0, 0], vec![0xc4, 0], vec![0xd4, 0, 0]] { + assert!(decode(&framed(&body, 4)).is_err()); + } + let b = one("RAY"); + for version in [1, 2, 3] { + assert!(decode(&framed(&b[15..], version)).is_err()); + } +} +#[test] +fn mixed_legacy_and_entity_uses_v4() { + use opencaddocument::{entities::Line, EntityType, Vector3}; + let mut cases = support::leaf_cases(); + cases.push(( + "LINE", + EntityType::Line(Line::from_points(Vector3::ZERO, Vector3::UNIT_X)), + )); + let (source, request) = support::source_with_leaves(cases); + let s = DocumentSelection::capture(&source, &request) + .unwrap() + .selection; + let b = encode(&s).unwrap(); + assert_eq!(b[9], 4); + assert_eq!(decode(&b).unwrap(), s); +} + +#[test] +fn reads_independently_authored_v4_fixtures() { + for bytes in [ + include_bytes!("fixtures/selection/v4/ray.msgpack").as_slice(), + include_bytes!("fixtures/selection/v4/circle.msgpack").as_slice(), + ] { + let s = decode(bytes).unwrap(); + assert_eq!(s.roots().len(), 1); + assert_eq!(decode(&encode(&s).unwrap()).unwrap(), s); + match &s.records()[0].payload { + SelectionPayload::Entity(e) => match e.as_ref() { + opencaddocument::EntityType::Ray(v) => { + assert_eq!(v.base_point, opencaddocument::Vector3::new(2.0, 3.0, 4.0)); + assert_eq!(v.direction, opencaddocument::Vector3::UNIT_X); + } + opencaddocument::EntityType::Circle(v) => { + assert_eq!(v.radius, 2.5); + assert_eq!(v.thickness.to_bits(), (-0.0f64).to_bits()); + } + _ => panic!(), + }, + _ => panic!(), + } + } +} +#[test] +fn rejects_duplicate_model_fields_and_unknown_variants() { + let bytes = one("RAY"); + let body = &bytes[15..]; + let at = body.windows(4).position(|w| w == b"\xa3Ray").unwrap(); + let map_at = at + 4; + assert_eq!(body[map_at], 0x83); + let mut model: serde_json::Value = rmp_serde::from_slice(body).unwrap(); + let entity = model["records"][0]["payload"][1]["Ray"].clone(); + for alias in ["FutureRay", "Line", "MLine"] { + model["records"][0]["payload"][1] = serde_json::json!({alias:entity}); + assert!(decode(&framed(&rmp_serde::to_vec_named(&model).unwrap(), 4)).is_err()); + } + // Duplicate a top-level model field by inserting its encoded bytes at map start. + let mut duplicate = body.to_vec(); + duplicate[map_at] = 0x84; + let field = [ + vec![0xaa], + b"base_point".to_vec(), + rmp_serde::to_vec_named(&serde_json::json!({"x":1.0,"y":2.0,"z":3.0})).unwrap(), + ] + .concat(); + duplicate.splice(map_at + 1..map_at + 1, field); + assert!(decode(&framed(&duplicate, 4)) + .unwrap_err() + .message + .contains("duplicate field")); +} +#[test] +fn v4_preflight_applies_global_limits() { + use opencaddocument::selection_storage::SelectionStorageErrorKind as K; + for (marker, limit) in [(0xdd, 262_144u32), (0xdf, 262_144), (0xdb, 1_048_576)] { + let mut body = vec![marker]; + body.extend_from_slice(&(limit + 1).to_be_bytes()); + assert_eq!( + decode(&framed(&body, 4)).unwrap_err().kind, + K::LimitExceeded + ); + } + let mut body = vec![0x91; 17]; + body.push(0xc0); + assert_eq!( + decode(&framed(&body, 4)).unwrap_err().kind, + K::LimitExceeded + ); + // Two legal large containers together exceed the one shared value budget. + let mut body = vec![0x94]; + for _ in 0..4 { + body.push(0xdd); + body.extend_from_slice(&262_144u32.to_be_bytes()); + body.resize(body.len() + 262_144, 0xc0); + } + assert_eq!( + decode(&framed(&body, 4)).unwrap_err().kind, + K::LimitExceeded + ); +} + +#[test] +fn spline_nondefault_fields_and_both_definitions_are_retained() { + let (_, mut e) = support::leaf_cases().remove(5); + let opencaddocument::EntityType::Spline(v) = &mut e else { + panic!() + }; + v.fit_points = vec![ + opencaddocument::Vector3::ZERO, + opencaddocument::Vector3::UNIT_Y, + ]; + v.weights = vec![1.0, 2.0]; + v.flags.rational = true; + v.flags.planar = true; + v.flags.closed = true; + v.knot_tolerance = 1e-7; + v.control_tolerance = 2e-7; + v.fit_tolerance = 3e-7; + v.begin_tangent = opencaddocument::Vector3::UNIT_X; + v.end_tangent = opencaddocument::Vector3::UNIT_Y; + v.knot_parameterization = 15; + v.cv_frame_visible = true; + v.dwg_flags1 = 1024; + v.dwg_scenario = Some(1); + v.dxf_flags = 2048; + let (source, req) = support::source_with_leaves(vec![("SPLINE", e)]); + let s = DocumentSelection::capture(&source, &req).unwrap().selection; + drop(source); + assert_eq!(decode(&encode(&s).unwrap()).unwrap(), s); +} + +#[test] +fn ignored_field_paths_resolve_in_the_actual_wire_body() { + for bytes in [ + changed("RAY", |v| { + v["records"][0]["payload"][1]["Ray"]["future~/field"] = 42.into() + }), + changed("RAY", |v| { + v["records"][0]["payload"][1]["Ray"]["common"]["future"] = 42.into() + }), + changed("LWPOLYLINE", |v| { + v["records"][0]["payload"][1]["LwPolyline"]["vertices"][0]["future"] = 42.into() + }), + changed("RAY", |v| { + v["records"][0]["payload"][1]["Ray"]["common"]["color"] = + serde_json::json!({"Rgb":{"r":1,"g":2,"b":3,"future":42}}) + }), + ] { + let body: serde_json::Value = rmp_serde::from_slice(&bytes[15..]).unwrap(); + let e = decode(&bytes).unwrap_err(); + let path = e.path.expect("model field location"); + assert_eq!( + body.pointer(&path), + Some(&serde_json::json!(42)), + "{path}: {}", + e.message + ); + } +} diff --git a/tests/selection_storage.rs b/tests/selection_storage.rs index 3e0b6a5..e2f32c0 100644 --- a/tests/selection_storage.rs +++ b/tests/selection_storage.rs @@ -29,7 +29,7 @@ fn replace(body: &[u8], before: &[u8], after: &[u8]) -> Vec { fn rejects_wrong_magic_version_kind_before_body() { for (index, value, kind) in [ (0, 0, Kind::InvalidEnvelope), - (9, 4, Kind::UnsupportedVersion), + (9, 5, Kind::UnsupportedVersion), (10, 2, Kind::UnsupportedKind), ] { let mut data = frame(&[0xc1]); diff --git a/tests/selection_strict_model.rs b/tests/selection_strict_model.rs new file mode 100644 index 0000000..68dc52e --- /dev/null +++ b/tests/selection_strict_model.rs @@ -0,0 +1,87 @@ +#![cfg(feature = "selection-storage")] +use opencaddocument::selection_storage::decode; +fn bytes(mutator: impl FnOnce(&mut serde_json::Value)) -> Vec { + let fixture = include_bytes!("fixtures/selection/v4/ray.msgpack"); + let mut body: serde_json::Value = rmp_serde::from_slice(&fixture[15..]).unwrap(); + mutator(&mut body); + let payload = rmp_serde::to_vec_named(&body).unwrap(); + let mut result = fixture[..11].to_vec(); + result.extend_from_slice(&(payload.len() as u32).to_be_bytes()); + result.extend(payload); + result +} +#[test] +fn reject_positional_ray_struct() { + let b = bytes(|v| { + let ray = &v["records"][0]["payload"][1]["Ray"]; + let seq = serde_json::json!([ray["common"], ray["base_point"], ray["direction"]]); + v["records"][0]["payload"][1]["Ray"] = seq; + }); + assert!(decode(&b).is_err(), "V4 accepted positional Ray struct"); +} +#[test] +fn reject_positional_vector_struct() { + let b = bytes(|v| { + v["records"][0]["payload"][1]["Ray"]["base_point"] = serde_json::json!([2.0, 3.0, 4.0]) + }); + assert!(decode(&b).is_err(), "V4 accepted positional Vector3 struct"); +} +#[test] +fn reject_lossy_integer_for_float_geometry() { + let b = bytes(|v| { + v["records"][0]["payload"][1]["Ray"]["base_point"]["x"] = + serde_json::json!(9_007_199_254_740_993u64) + }); + assert!( + decode(&b).is_err(), + "integer geometry must not coerce to f64" + ); +} +#[test] +fn reject_integer_point_display_size() { + let mut p = opencaddocument::entities::Point::new(); + p.location = opencaddocument::Vector3::UNIT_X; + let mut source = opencaddocument::Document::new(); + let h = source + .add_entity(opencaddocument::EntityType::Point(p)) + .unwrap(); + let mut req = opencaddocument::selection::CaptureRequest::new("point", vec![h]); + req.external + .insert(opencaddocument::selection::SelectionRecordKey { + kind: opencaddocument::selection::SelectionRecordKind::Layer, + handle: source.layers.get("0").unwrap().handle, + }); + let s = opencaddocument::selection::DocumentSelection::capture(&source, &req) + .unwrap() + .selection; + let b = opencaddocument::selection_storage::encode(&s).unwrap(); + let mut v: serde_json::Value = rmp_serde::from_slice(&b[15..]).unwrap(); + v["context"]["point_display"]["size"] = serde_json::json!(1); + let payload = rmp_serde::to_vec_named(&v).unwrap(); + let mut b = b[..11].to_vec(); + b.extend_from_slice(&(payload.len() as u32).to_be_bytes()); + b.extend(payload); + assert!( + decode(&b).is_err(), + "Point display must require float64 too" + ); +} + +#[test] +fn rgb_variant_requires_a_named_map() { + let valid = bytes(|v| { + v["records"][0]["payload"][1]["Ray"]["common"]["color"] = + serde_json::json!({"Rgb":{"r":1,"g":2,"b":3}}) + }); + assert!(decode(&valid).is_ok()); + let invalid = bytes(|v| { + v["records"][0]["payload"][1]["Ray"]["common"]["color"] = serde_json::json!({"Rgb":[1,2,3]}) + }); + assert!(decode(&invalid).is_err()); +} +#[test] +fn exact_integer_geometry_still_requires_float64() { + let invalid = + bytes(|v| v["records"][0]["payload"][1]["Ray"]["base_point"]["x"] = serde_json::json!(1)); + assert!(decode(&invalid).is_err()); +} diff --git a/tests/support/selection_leaf.rs b/tests/support/selection_leaf.rs new file mode 100644 index 0000000..37eb5ce --- /dev/null +++ b/tests/support/selection_leaf.rs @@ -0,0 +1,51 @@ +use opencaddocument::entities::{ + Arc, Circle, Ellipse, LwPolyline, LwVertex, Point, Ray, Spline, XLine, +}; +use opencaddocument::selection::{CaptureRequest, SelectionRecordKey, SelectionRecordKind}; +use opencaddocument::{Document, EntityType, Handle, Vector2, Vector3}; + +pub fn leaf_cases() -> Vec<(&'static str, EntityType)> { + let mut polyline = LwPolyline::new(); + polyline.vertices = vec![ + LwVertex::new(Vector2::new(2.0, 3.0)), + LwVertex::new(Vector2::new(7.0, 5.0)), + ]; + polyline.vertices[0].vertex_id = 17; + polyline.vertices[0].bulge = 0.5; + let mut spline = Spline::new(); + spline.degree = 1; + spline.control_points = vec![Vector3::new(2.0, 3.0, 0.0), Vector3::new(7.0, 5.0, 0.0)]; + spline.knots = vec![0.0, 0.0, 1.0, 1.0]; + vec![ + ("POINT", EntityType::Point(Point::new())), + ("CIRCLE", EntityType::Circle(Circle::new())), + ("ARC", EntityType::Arc(Arc::new())), + ("ELLIPSE", EntityType::Ellipse(Ellipse::new())), + ("LWPOLYLINE", EntityType::LwPolyline(polyline)), + ("SPLINE", EntityType::Spline(spline)), + ( + "RAY", + EntityType::Ray(Ray::new(Vector3::new(2.0, 3.0, 0.0), Vector3::UNIT_X)), + ), + ( + "XLINE", + EntityType::XLine(XLine::new(Vector3::new(2.0, 3.0, 0.0), Vector3::UNIT_Y)), + ), + ] +} + +pub fn source_with_leaves(cases: Vec<(&str, EntityType)>) -> (Document, CaptureRequest) { + let mut source = Document::new(); + let roots: Vec = cases + .into_iter() + .map(|(_, e)| source.add_entity(e).unwrap()) + .collect(); + let mut request = CaptureRequest::new("leaf-source", roots); + // CAD layer 0 may carry a native Normal plot-style reference. Its content + // is deliberately external, as it is on the preserving IFCCAD route. + request.external.insert(SelectionRecordKey { + kind: SelectionRecordKind::Layer, + handle: source.layers.get("0").unwrap().handle, + }); + (source, request) +}