From 0e16d77dcd741077f6b98f98e435a83f53ed52d0 Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:36:43 +0100 Subject: [PATCH 1/7] Saving keeps the associative network a BricsCAD parametric block depends on BricsCAD keeps the visibility states of its parametric blocks in objects of its own classes, which are read here as raw records. They reach the block's ACAD_ASSOCNETWORK variables by handle, and the variables list them as reactors. The graph sync that runs on save rebuilt every scope's network under new handles and dropped its value dependencies, so BricsCAD found its objects pointing at erased variables and dropped every parameter of the drawing. A network whose variables list a raw record as reactor is now written back as it was read, as long as the editor's model of that scope still equals the one the network holds; a scope the user changed is rebuilt as before. Kept networks go back under the rebuilt root network. --- src/scene/dwg_native_constraints.rs | 296 ++++++++++++----- .../raw_dependents_tests.rs | 303 ++++++++++++++++++ tests/fixtures/bricscad/README.md | 32 ++ tests/fixtures/bricscad/visibility-states.dwg | Bin 0 -> 22349 bytes 4 files changed, 546 insertions(+), 85 deletions(-) create mode 100644 src/scene/dwg_native_constraints/raw_dependents_tests.rs create mode 100644 tests/fixtures/bricscad/README.md create mode 100644 tests/fixtures/bricscad/visibility-states.dwg diff --git a/src/scene/dwg_native_constraints.rs b/src/scene/dwg_native_constraints.rs index 02365a1a42..8db93cd4cc 100644 --- a/src/scene/dwg_native_constraints.rs +++ b/src/scene/dwg_native_constraints.rs @@ -4194,38 +4194,7 @@ impl Scene { } pub(crate) fn load_named_parameters_from_document(&mut self) { - self.named_parameters = ParameterTable::new(); - let mut variables: Vec<_> = self - .document - .objects - .values() - .filter_map(|object| match object { - ObjectType::Associative(AssociativeObject { - handle, - data: AssociativeData::Variable(variable), - .. - }) => Some((*handle, variable)), - _ => None, - }) - .collect(); - variables.sort_by_key(|(handle, _)| handle.value()); - let model_network = native_scope_network_handle( - &self.document, - self.document.header.model_space_block_handle, - ); - for (_, variable) in variables { - if model_network.is_none_or(|network| variable.action.owning_network != network) { - continue; - } - let source = if variable.expression.trim().is_empty() { - numeric_value(&variable.value).map(|value| value.to_string()) - } else { - Some(variable.expression.clone()) - }; - if let Some(source) = source { - let _ = self.named_parameters.set(&variable.name, &source); - } - } + self.named_parameters = model_network_parameters(&self.document); } pub(crate) fn load_parametric_constraints_from_document(&mut self) { @@ -4300,6 +4269,8 @@ impl Scene { .map(|&owner| native_scope_network_handle(&self.document, owner).is_some()) .collect() }; + let raw_dependents = networks_raw_objects_depend_on(&self.document); + let mut kept_networks = Vec::new(); let mut scopes = Vec::new(); for (owner, existing) in owners.into_iter().zip(existing_networks) { let runtime = self @@ -4307,6 +4278,18 @@ impl Scene { .iter() .find(|set| set.scope.owner_handle(&self.document) == owner) .cloned(); + if existing { + if let Some(network) = stored_network_to_keep( + &self.document, + owner, + runtime.as_ref(), + &self.named_parameters, + &raw_dependents, + ) { + kept_networks.push(network); + continue; + } + } let set = match runtime { Some(set) => Some(set), None if existing => { @@ -4355,6 +4338,7 @@ impl Scene { ); let root_network_handle = self.document.allocate_handle(); let mut child_networks = Vec::new(); + let rebuilt_scopes = scopes.len(); for (index, (owner, set, variables, groups, foreign)) in scopes.into_iter().enumerate() { let parameters = if set.local_parameters.is_empty() { &self.named_parameters @@ -4376,6 +4360,19 @@ impl Scene { child_networks.push(handle); } } + // The kept networks go under the new root after the rebuilt ones, + // unchanged apart from where they sit in it. + for (offset, network) in kept_networks.into_iter().enumerate() { + if let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Network(kept), + .. + })) = self.document.objects.get_mut(&network) + { + kept.action.owning_network = root_network_handle; + kept.action.action_index = (rebuilt_scopes + offset) as i32 + 1; + child_networks.push(network); + } + } if child_networks.is_empty() { return; } @@ -4431,63 +4428,189 @@ impl Scene { let mut hasher = DefaultHasher::new(); hash_parameter_table(&self.named_parameters, &mut hasher); for set in &self.parametric_constraints { - set.scope.hash(&mut hasher); - for constraint in &set.constraints { - constraint.id.hash(&mut hasher); - (constraint.kind as u16).hash(&mut hasher); - constraint.refs.hash(&mut hasher); - match &constraint.driving_param { - None => 0u8.hash(&mut hasher), - Some(DrivingValue::Literal(value)) => { - 1u8.hash(&mut hasher); - value.to_bits().hash(&mut hasher); - } - Some(DrivingValue::Named(name)) => { - 2u8.hash(&mut hasher); - name.hash(&mut hasher); - } - } - constraint.enabled.hash(&mut hasher); - match constraint.native_origin { - None => 0u8.hash(&mut hasher), - Some(origin) => { - 1u8.hash(&mut hasher); - origin.group.hash(&mut hasher); - origin.node.hash(&mut hasher); - } - } - constraint.rigid_points.len().hash(&mut hasher); - for (reference, point) in &constraint.rigid_points { - reference.hash(&mut hasher); - hash_vector(point, &mut hasher); - } - constraint.distance_direction_type.hash(&mut hasher); - match constraint.distance_direction { - None => 0u8.hash(&mut hasher), - Some(direction) => { - 1u8.hash(&mut hasher); - hash_vector(&direction, &mut hasher); - } - } - match constraint.axis_direction { - None => 0u8.hash(&mut hasher), - Some(direction) => { - 1u8.hash(&mut hasher); - hash_vector(&direction, &mut hasher); - } - } - constraint.angle_sector.hash(&mut hasher); + hash_constraint_set(set, &mut hasher); + } + hasher.finish() + } +} + +/// Hashes one scope's share of the model `constraint_model_fingerprint` +/// covers. Dimension links are hashed in id order, so two sets with the same +/// links hash alike whatever order their maps hold them in. +fn hash_constraint_set(set: &ParametricConstraintSet, hasher: &mut DefaultHasher) { + set.scope.hash(hasher); + for constraint in &set.constraints { + constraint.id.hash(hasher); + (constraint.kind as u16).hash(hasher); + constraint.refs.hash(hasher); + match &constraint.driving_param { + None => 0u8.hash(hasher), + Some(DrivingValue::Literal(value)) => { + 1u8.hash(hasher); + value.to_bits().hash(hasher); } - hash_parameter_table(&set.local_parameters, &mut hasher); - set.dimensions.len().hash(&mut hasher); - for (id, dimension) in &set.dimensions { - id.hash(&mut hasher); - dimension.hash(&mut hasher); + Some(DrivingValue::Named(name)) => { + 2u8.hash(hasher); + name.hash(hasher); } - set.retained_standard_groups.hash(&mut hasher); } - hasher.finish() + constraint.enabled.hash(hasher); + match constraint.native_origin { + None => 0u8.hash(hasher), + Some(origin) => { + 1u8.hash(hasher); + origin.group.hash(hasher); + origin.node.hash(hasher); + } + } + constraint.rigid_points.len().hash(hasher); + for (reference, point) in &constraint.rigid_points { + reference.hash(hasher); + hash_vector(point, hasher); + } + constraint.distance_direction_type.hash(hasher); + match constraint.distance_direction { + None => 0u8.hash(hasher), + Some(direction) => { + 1u8.hash(hasher); + hash_vector(&direction, hasher); + } + } + match constraint.axis_direction { + None => 0u8.hash(hasher), + Some(direction) => { + 1u8.hash(hasher); + hash_vector(&direction, hasher); + } + } + constraint.angle_sector.hash(hasher); + } + hash_parameter_table(&set.local_parameters, hasher); + let mut dimensions: Vec<_> = set.dimensions.iter().collect(); + dimensions.sort_unstable_by_key(|(id, _)| **id); + dimensions.len().hash(hasher); + for (id, dimension) in dimensions { + id.hash(hasher); + dimension.hash(hasher); + } + set.retained_standard_groups.hash(hasher); +} + +fn constraint_set_hash(set: &ParametricConstraintSet) -> u64 { + let mut hasher = DefaultHasher::new(); + hash_constraint_set(set, &mut hasher); + hasher.finish() +} + +/// The networks whose variables an object kept only as its raw record lists +/// as a reactor. Such an object reaches the variables by handle and cannot be +/// re-pointed, so rebuilding the network under new handles would leave it +/// pointing at erased objects. BricsCAD keeps the visibility states and other +/// parameters of its parametric blocks this way: its own objects, which this +/// program reads as raw records, read and drive the block's variables. +fn networks_raw_objects_depend_on(document: &Document) -> FxHashSet { + document + .objects + .values() + .filter_map(|object| match object { + ObjectType::Associative(AssociativeObject { + reactors, + data: AssociativeData::Variable(variable), + .. + }) if reactors.iter().any(|reactor| { + matches!( + document.objects.get(reactor), + Some(ObjectType::Unknown { .. }) + ) + }) => + { + Some(variable.action.owning_network) + } + _ => None, + }) + .collect() +} + +/// The stored network of `owner` when it is written back as it was read: raw +/// objects depend on it (see `networks_raw_objects_depend_on`) and the +/// editor's model of the scope still equals the one the network holds. For +/// model space that includes the drawing's parameter table, which is read +/// from the model-space network. A scope the user changed is rebuilt as +/// before. +fn stored_network_to_keep( + document: &Document, + owner: Handle, + runtime: Option<&ParametricConstraintSet>, + named_parameters: &ParameterTable, + raw_dependents: &FxHashSet, +) -> Option { + if raw_dependents.is_empty() { + return None; + } + let network = native_scope_network_handle(document, owner)?; + if !raw_dependents.contains(&network) { + return None; + } + let mut parameters = if owner == document.header.model_space_block_handle { + let loaded = loaded_named_parameters(document); + if has_pending_surfaces(document) || *named_parameters != loaded { + return None; + } + loaded + } else { + // A block scope reads its parameters into a table of its own. + ParameterTable::new() + }; + let Some(runtime) = runtime else { + return Some(network); + }; + let stored = native_constraint_set(document, owner, &mut parameters)?; + (constraint_set_hash(runtime) == constraint_set_hash(&stored)).then_some(network) +} + +/// The drawing's parameter table as opening the drawing builds it: the +/// variables of the model-space network, then whatever reading each scope's +/// constraints adopts into it. +fn loaded_named_parameters(document: &Document) -> ParameterTable { + let mut parameters = model_network_parameters(document); + for record in document.block_records.iter() { + native_constraint_set(document, record.handle, &mut parameters); + } + parameters +} + +/// The named variables of the model-space network as a parameter table. +fn model_network_parameters(document: &Document) -> ParameterTable { + let mut parameters = ParameterTable::new(); + let Some(model_network) = + native_scope_network_handle(document, document.header.model_space_block_handle) + else { + return parameters; + }; + let mut variables: Vec<_> = document + .objects + .values() + .filter_map(|object| match object { + ObjectType::Associative(AssociativeObject { + handle, + data: AssociativeData::Variable(variable), + .. + }) if variable.action.owning_network == model_network => Some((*handle, variable)), + _ => None, + }) + .collect(); + variables.sort_by_key(|(handle, _)| handle.value()); + for (_, variable) in variables { + let source = if variable.expression.trim().is_empty() { + numeric_value(&variable.value).map(|value| value.to_string()) + } else { + Some(variable.expression.clone()) + }; + if let Some(source) = source { + let _ = parameters.set(&variable.name, &source); + } } + parameters } /// Hashes a parameter table in insertion order: each parameter's name, @@ -4508,6 +4631,9 @@ fn hash_vector(vector: &Vector3, hasher: &mut DefaultHasher) { vector.z.to_bits().hash(hasher); } +#[cfg(test)] +mod raw_dependents_tests; + #[cfg(test)] mod tests { use super::super::parametric_constraints::{ diff --git a/src/scene/dwg_native_constraints/raw_dependents_tests.rs b/src/scene/dwg_native_constraints/raw_dependents_tests.rs new file mode 100644 index 0000000000..6f578ef12d --- /dev/null +++ b/src/scene/dwg_native_constraints/raw_dependents_tests.rs @@ -0,0 +1,303 @@ +//! A network that objects kept only as raw records depend on is written back +//! with its handles while the editor has not changed its scope. +//! +//! BricsCAD keeps the visibility states of its parametric blocks in objects of +//! its own classes. They are read here as raw records and reach the block's +//! associative variables by handle, so a rebuild under new handles leaves them +//! pointing at erased variables and BricsCAD drops the block's parameters. + +use super::*; +use document::entities::Line; + +/// The objects `bind_raw_network` adds. +struct Bound { + network: Handle, + variable: Handle, + raw: Handle, +} + +/// Give `owner` a network with one variable, `look_1` = 1, that lists a raw +/// object as its reactor, the way BricsCAD's variables list the objects that +/// read them. +fn bind_raw_network(document: &mut Document, owner: Handle) -> Bound { + let dictionary = document.ensure_extension_dictionary(owner); + let [network, variable, raw] = [(); 3].map(|_| document.allocate_handle()); + document.objects.insert( + raw, + ObjectType::Unknown { + type_name: "BDMDBCONFIGVARREACTOR".to_string(), + handle: raw, + owner: dictionary, + raw_dxf_codes: None, + raw_dwg_data: Some(vec![0; 8]), + raw_dwg_handle_bits: 0, + raw_dwg_version: None, + }, + ); + document.objects.insert( + network, + ObjectType::Associative(AssociativeObject { + handle: network, + owner: dictionary, + reactors: vec![dictionary], + dxf_name: "ACDBASSOCNETWORK".to_string(), + cpp_class_name: "AcDbAssocNetwork".to_string(), + data: AssociativeData::Network(AssocNetwork { + action: AssocAction { + class_version: 2, + ..Default::default() + }, + network_action_index: 1, + actions: vec![AssocActionDependency { + is_owned: true, + dependency: variable, + }], + ..Default::default() + }), + ..Default::default() + }), + ); + document.objects.insert( + variable, + ObjectType::Associative(AssociativeObject { + handle: variable, + owner: network, + reactors: vec![raw], + dxf_name: "ACDBASSOCVARIABLE".to_string(), + cpp_class_name: "AcDbAssocVariable".to_string(), + data: AssociativeData::Variable(AssocVariable { + action: AssocAction { + class_version: 2, + owning_network: network, + action_index: 1, + ..Default::default() + }, + class_version: 2, + name: "look_1".to_string(), + evaluator: "AcDbCalc:1.0".to_string(), + value: AssocEvalVariant { + code: 40, + value: AssocEvalValue::Real(1.0), + }, + ..Default::default() + }), + ..Default::default() + }), + ); + if let Some(ObjectType::Dictionary(dictionary)) = document.objects.get_mut(&dictionary) { + dictionary.add_entry(NETWORK_DICTIONARY_KEY, network); + } + Bound { + network, + variable, + raw, + } +} + +/// A scene with one block definition holding a line. +fn block_scene() -> (Scene, Handle) { + let mut scene = Scene::new(); + scene.define_block_raw( + "states", + Vector3::ZERO, + vec![EntityType::Line(Line::from_points( + Vector3::ZERO, + Vector3::UNIT_X, + ))], + ); + let block = scene.document.block_records.get("states").unwrap().handle; + (scene, block) +} + +/// Read the drawing's parameters and constraints as opening a file does. +fn read_as_opened(scene: &mut Scene) { + scene.load_named_parameters_from_document(); + scene.load_parametric_constraints_from_document(); +} + +fn variable_value(document: &Document, network: Handle, name: &str) -> Option { + document.objects.values().find_map(|object| match object { + ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + }) if variable.action.owning_network == network && variable.name == name => { + numeric_value(&variable.value) + } + _ => None, + }) +} + +#[test] +fn a_block_network_raw_objects_depend_on_keeps_its_handles() { + let (mut scene, block) = block_scene(); + let bound = bind_raw_network(&mut scene.document, block); + read_as_opened(&mut scene); + let network = scene.document.objects.get(&bound.network).cloned(); + let variable = scene.document.objects.get(&bound.variable).cloned(); + + scene.sync_native_parametric_graph(); + + assert_eq!( + native_scope_network_handle(&scene.document, block), + Some(bound.network), + "the block keeps its network" + ); + assert_eq!(scene.document.objects.get(&bound.network).cloned(), network); + assert_eq!( + scene.document.objects.get(&bound.variable).cloned(), + variable, + "the variable the raw object reads is written back as it was read" + ); + assert!(matches!( + scene.document.objects.get(&bound.raw), + Some(ObjectType::Unknown { .. }) + )); +} + +#[test] +fn a_model_space_network_raw_objects_depend_on_keeps_its_handles() { + // A drawing that is itself a BricsCAD parametric block keeps its + // parameters in the model-space network, which is also where the + // drawing's own parameter table is read from. + let mut scene = Scene::new(); + let model = scene.document.header.model_space_block_handle; + let bound = bind_raw_network(&mut scene.document, model); + read_as_opened(&mut scene); + assert!( + scene.named_parameters.get("look_1").is_some(), + "opening reads the variable into the drawing's parameters" + ); + let variable = scene.document.objects.get(&bound.variable).cloned(); + + scene.sync_native_parametric_graph(); + + assert_eq!( + native_scope_network_handle(&scene.document, model), + Some(bound.network) + ); + assert_eq!( + scene.document.objects.get(&bound.variable).cloned(), + variable + ); +} + +#[test] +fn a_parameter_changed_in_such_a_scope_is_still_written() { + let (mut scene, block) = block_scene(); + let bound = bind_raw_network(&mut scene.document, block); + read_as_opened(&mut scene); + scene + .parametric_constraint_set_mut(ParametricScope::Block(block)) + .local_parameters + .set("look_1", "0") + .unwrap(); + + scene.sync_native_parametric_graph(); + + let network = + native_scope_network_handle(&scene.document, block).expect("the block still has a network"); + assert_ne!(network, bound.network, "a changed scope is rebuilt"); + assert_eq!( + variable_value(&scene.document, network, "look_1"), + Some(0.0) + ); +} + +#[test] +fn a_changed_drawing_parameter_rebuilds_the_model_space_network() { + let mut scene = Scene::new(); + let model = scene.document.header.model_space_block_handle; + let bound = bind_raw_network(&mut scene.document, model); + read_as_opened(&mut scene); + scene.named_parameters.set("look_1", "0").unwrap(); + + scene.sync_native_parametric_graph(); + + let network = native_scope_network_handle(&scene.document, model) + .expect("model space still has a network"); + assert_ne!(network, bound.network, "a changed scope is rebuilt"); + assert_eq!( + variable_value(&scene.document, network, "look_1"), + Some(0.0) + ); +} + +#[test] +fn a_bricscad_parametric_block_keeps_the_variables_its_objects_read_through_a_dwg_save() { + // tests/fixtures/bricscad/README.md describes the drawing. + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/bricscad/visibility-states.dwg" + ); + let bytes = std::fs::read(path).expect("read the fixture"); + let mut scene = Scene::new(); + scene.document = + crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes) + .expect("open the fixture"); + read_as_opened(&mut scene); + + // Each variable with its name, network and the objects listed as its + // reactors: BricsCAD's objects, and the value dependency of a variable + // another one's expression reads. + let variables = |document: &Document| { + let mut rows: Vec<(Handle, String, Handle, Vec)> = document + .objects + .values() + .filter_map(|object| match object { + ObjectType::Associative(AssociativeObject { + handle, + reactors, + data: AssociativeData::Variable(variable), + .. + }) => Some(( + *handle, + variable.name.clone(), + variable.action.owning_network, + reactors.clone(), + )), + _ => None, + }) + .collect(); + rows.sort_by_key(|row| row.0); + rows + }; + let value_dependencies = |document: &Document| { + document + .objects + .values() + .filter(|object| { + matches!( + object, + ObjectType::Associative(AssociativeObject { + data: AssociativeData::ValueDependency(_), + .. + }) + ) + }) + .count() + }; + let before = variables(&scene.document); + assert_eq!( + before.len(), + 18, + "six variables in each of the three blocks" + ); + assert_eq!(value_dependencies(&scene.document), 6); + + scene.sync_native_parametric_graph(); + let saved = crate::io::save_to_bytes(&scene.document, "dwg", scene.document.version) + .expect("save as DWG"); + let reopened = crate::io::load_bytes_finalized(std::path::Path::new("saved.dwg"), saved) + .expect("open the saved DWG"); + + assert_eq!(variables(&reopened), before); + assert_eq!(value_dependencies(&reopened), 6); + for (handle, name, _, reactors) in &before { + for reactor in reactors { + assert!( + reopened.objects.contains_key(reactor), + "{name} ({handle:?}) lists {reactor:?}, which the saved drawing lost" + ); + } + } +} diff --git a/tests/fixtures/bricscad/README.md b/tests/fixtures/bricscad/README.md new file mode 100644 index 0000000000..35d41144bd --- /dev/null +++ b/tests/fixtures/bricscad/README.md @@ -0,0 +1,32 @@ +A parametric block with visibility states, made in BricsCAD V26 (Linux, German +user interface) and saved there as DWG 2018 (AC1032). + +The block `ocs-bricscad-visibility-block` holds a 10 × 10 frame, a circle with a +cross through it and the text `LABEL`. It has two visibility parameters, set up +with `VISIBILITYSTATES` on the drawing that became the block: + +| Parameter | States | Objects the second state hides | +|---|---|---| +| `LAMP` | `On`, `Off` | the circle and the two cross lines | +| `LABEL` | `Shown`, `Hidden` | the text | + +`visibility-states.dwg` inserts the block three times along the x axis: + +| Handle | At | `LAMP` | `LABEL` | Block | +|---|---|---|---|---| +| `EE` | 0, 0 | `On` | `Shown` | the definition itself | +| `146` | 20, 0 | `Off` | `Shown` | `*U2` | +| `19E` | 40, 0 | `Off` | `Hidden` | `*U3` | + +What the file shows about how BricsCAD stores such a block: + +- A reference in a state other than the definition's shows an anonymous copy + (`*U2`, `*U3`) with every member of the definition in the same order. The + members a state hides sit on the layer `*SUPPRESS`, which is frozen and off. +- The parameters live in objects of BricsCAD's own classes (`BDMDB…`, + `BdmDb…`, `BDMOBJECT`) under `BDM_DATABASE` in the extension dictionary of + the definition, of each copy and of model space. Each block also has an + `ACAD_ASSOCNETWORK` whose variables (`LAMP`, `look_1`, `Unterdrücken_1`, …) + those objects read and drive. The variables list them as reactors and the + objects reach the variables by handle, so the variables must keep their + handles when the drawing is saved. diff --git a/tests/fixtures/bricscad/visibility-states.dwg b/tests/fixtures/bricscad/visibility-states.dwg new file mode 100644 index 0000000000000000000000000000000000000000..6a05c3f8f5af6158bd406f3f8cdc90149246857d GIT binary patch literal 22349 zcmc$`4M0@Y)-b&G`J2Q1z+o6*h95bc84yr#eed_(`@GM0 zV4t6T_SrvcueJ7CYp*r7yrI^NbO;>7Xg>jnA2y)>>6ep;S%E{r)P6{}p+R4{L{$M!jwq0|_wq#Y?|H?$@{f+O-e+_XhT9P%-vz z+TA_|`WYGj{JfQ;COjXPP^~(fos{(W^iyLVcL;+Xr2#1NDYosx2DxDrKqhAWcORQw z6UXY*QEIGLSLk$1#zyg$Fnr*0W`1-cUV>_zGim`eVSz+o_Z}mbx>D${mDFGO@;zH9 z0RNWt=v%LU67SjUUH@_+r;Hv*6asDlEXl#Ya{I4*^Iw|!H$TUk{+-VM`=4X~|7FnK z1;fAjIS&6{o4Eh@?BD#{_%ET&f3*JJ@VOJZKO@s7s5JA{^=}~=Kwt-^O6yq^ba@H`j$C&DD`>4N?{2VQIYdl1OC z;kQ-z6eu;nzs@8q>%ja#zvlLjFz|j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cf)5e@4sA3AdA$oK7rN8ft(`h6#reWx#6*?i{WhTk9C`u+YWaqN_(Y0hby#rz|& z70b1gd|k%|)Mpn~*5wbs*P1`Clz!y>{k^Xqf9BAUi0VPr)sxA($xDYWA67qRMfOAA zT=t%N?$dp7_a+wY2!Hgab01mI>mTn{;V&xn zKS13S%+}T8t^tETGZ&!fD*gy7#w5UgZ^&$e0u7PnM(s9});8ZUZ$!c3ss)Y(HARbS zy@`rWq)fmR@nzvof*Op2l+k4{j)FGVfCplMel#+GfzA{IVSL^XNAD(B+bx@9ZYcv&&X2o#57y6==` zTYU{(X1o-ws%IOfxMG<}^C}n2ud8ilMcxRrL&L2{HRVII%W5|6pV7>f4Zj#ymR!n} z4p5K4f(0uUESOR=cm4twE2_0nzWCs2P1*mo%@NFcdl+N3#(*3alA2qPlUM?r;bM&8 zk6qXpz|_lN8DrJcd&hi^VvaPkM`B(|PO5@H4r_!&?9G%OiCAW7)eC}pHOw Date: Mon, 23 Nov 2026 10:52:21 +0100 Subject: [PATCH 2/7] Properties show the visibility states of a BricsCAD parametric block reference BricsCAD keeps the visibility parameters of its parametric blocks in objects of its own classes, which are read as raw records. A new scene module decodes the few it needs from their DWG bytes (2010 and later): each object is a list of named properties, with names and text in the string stream and object references in the handle stream. From them it reads a block's visibility parameters, their states and the state the block shows, and the block an anonymous copy was made from. A reference to such a block now shows one read-only row per parameter in the Custom section, with the state it shows and the states as tooltip, and its Name row names the block rather than the *U copy a reference in another state shows. --- src/app/bricscad_visibility_tests.rs | 97 ++++++ src/app/control/block_ops.rs | 12 +- src/app/mod.rs | 2 + src/app/properties.rs | 1 + src/app/visibility.rs | 25 ++ src/scene/bricscad_parameters.rs | 448 +++++++++++++++++++++++++ src/scene/bricscad_parameters/tests.rs | 134 ++++++++ src/scene/mod.rs | 1 + 8 files changed, 719 insertions(+), 1 deletion(-) create mode 100644 src/app/bricscad_visibility_tests.rs create mode 100644 src/scene/bricscad_parameters.rs create mode 100644 src/scene/bricscad_parameters/tests.rs diff --git a/src/app/bricscad_visibility_tests.rs b/src/app/bricscad_visibility_tests.rs new file mode 100644 index 0000000000..cabb023715 --- /dev/null +++ b/src/app/bricscad_visibility_tests.rs @@ -0,0 +1,97 @@ +//! A reference to a BricsCAD parametric block names the block and shows its +//! visibility parameters in Properties, also when it shows an anonymous copy +//! of the block in another state. + +use super::*; +use crate::scene::model::object::PropValue; +use document::Handle; + +/// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README), opened +/// the way the application opens a file. +fn opened() -> OpenCADStudio { + let mut app = OpenCADStudio::new_for_test(); + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/bricscad/visibility-states.dwg" + ); + app.automation_op(&serde_json::json!({"op": "open", "path": path}).to_string()); + let i = app.active_tab; + assert!( + app.tabs[i] + .scene + .document + .block_records + .get("ocs-bricscad-visibility-block") + .is_some(), + "the fixture did not open" + ); + app +} + +fn select(app: &mut OpenCADStudio, references: &[u64]) { + let i = app.active_tab; + app.tabs[i].scene.selected.clear(); + for (index, &reference) in references.iter().enumerate() { + app.tabs[i] + .scene + .select_entity(Handle::from(reference), index == 0); + } + app.tabs[i].selected_handle = (references.len() == 1).then(|| Handle::from(references[0])); + app.refresh_properties(); +} + +/// The visibility rows as label, value and tooltip. +fn visibility_rows(app: &OpenCADStudio) -> Vec<(String, String, String)> { + app.tabs[app.active_tab] + .properties + .sections + .iter() + .flat_map(|section| §ion.props) + .filter(|property| property.field == "bricscad_visibility") + .map(|property| match &property.value { + PropValue::ReadOnlyWithTooltip { value, tooltip } => { + (property.label.clone(), value.clone(), tooltip.clone()) + } + other => panic!("{} is {other:?}", property.label), + }) + .collect() +} + +fn block_name(app: &OpenCADStudio) -> String { + let row = app.tabs[app.active_tab] + .properties + .sections + .iter() + .flat_map(|section| §ion.props) + .find(|property| property.field == "block") + .expect("no block row"); + match &row.value { + PropValue::EditChoice { value, .. } | PropValue::ReadOnly(value) => value.clone(), + other => panic!("block row is {other:?}"), + } +} + +fn rows(lamp: &str, label: &str) -> Vec<(String, String, String)> { + vec![ + ("LAMP".into(), lamp.into(), "On, Off".into()), + ("LABEL".into(), label.into(), "Shown, Hidden".into()), + ] +} + +#[test] +fn a_reference_shows_the_states_it_was_set_to_and_names_its_block() { + let mut app = opened(); + for (reference, lamp, label) in [ + (0xEE, "On", "Shown"), + (0x146, "Off", "Shown"), + (0x19E, "Off", "Hidden"), + ] { + select(&mut app, &[reference]); + assert_eq!(visibility_rows(&app), rows(lamp, label), "{reference:X}"); + assert_eq!( + block_name(&app), + "ocs-bricscad-visibility-block", + "{reference:X} shows its block's name, not its copy's" + ); + } +} diff --git a/src/app/control/block_ops.rs b/src/app/control/block_ops.rs index 06d8f20183..fd535414ee 100644 --- a/src/app/control/block_ops.rs +++ b/src/app/control/block_ops.rs @@ -242,6 +242,16 @@ pub(crate) fn resolve_effective_block( } } + // 5. Fallback: a copy BricsCAD made of one of its parametric blocks, for a + // reference in another state, names that block in its own objects. The + // steps above find nothing for it or the copy itself. + if let Some(original) = evaluated_handle + .filter(|copy| def_handle.is_none_or(|definition| definition == *copy)) + .and_then(|copy| crate::scene::bricscad_parameters::original_block(doc, copy)) + { + def_handle = Some(original); + } + if let Some(def_h) = def_handle { if let Some(def_rec) = doc.block_records.iter().find(|r| r.handle == def_h) { let true_name = doc @@ -258,7 +268,7 @@ pub(crate) fn resolve_effective_block( } } - // 5. Fallback: check AcDbDynamicBlockTrueName XData on Insert or evaluated BlockRecord + // 6. Fallback: check AcDbDynamicBlockTrueName XData on Insert or evaluated BlockRecord let xdata_true_name = insert .common .extended_data diff --git a/src/app/mod.rs b/src/app/mod.rs index 58b53ed716..542bf13e07 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -36,6 +36,8 @@ mod block_test; #[cfg(test)] mod block_test_tests; mod block_visibility; +#[cfg(test)] +mod bricscad_visibility_tests; pub(crate) mod calc; mod command_driver; mod extraction_catalog; diff --git a/src/app/properties.rs b/src/app/properties.rs index 4e0fb56e5f..08dc63885b 100644 --- a/src/app/properties.rs +++ b/src/app/properties.rs @@ -1073,6 +1073,7 @@ impl OpenCADStudio { custom_properties.extend(Self::visibility_property(doc, handle)); } custom_properties.extend(Self::visible_blocks_property(doc, handle)); + custom_properties.extend(Self::bricscad_visibility_properties(doc, handle)); if !custom_properties.is_empty() { sections.push(crate::scene::model::object::PropSection { title: t!("Custom").into_owned(), diff --git a/src/app/visibility.rs b/src/app/visibility.rs index eb1365d9e0..1f503d594f 100644 --- a/src/app/visibility.rs +++ b/src/app/visibility.rs @@ -626,6 +626,31 @@ impl OpenCADStudio { }) } + /// The visibility parameters of a reference to a BricsCAD parametric + /// block, one read-only row each with the state the reference shows and + /// the parameter's states as tooltip. They are read from BricsCAD's own + /// objects, which are kept as they were read, so they are not changed + /// here. + pub(super) fn bricscad_visibility_properties( + doc: &document::Document, + handle: Handle, + ) -> Vec { + crate::scene::bricscad_parameters::reference_parameters(doc, handle) + .into_iter() + .map(|parameter| Property { + value: PropValue::ReadOnlyWithTooltip { + value: parameter + .current + .and_then(|index| parameter.states.get(index).cloned()) + .unwrap_or_default(), + tooltip: parameter.states.join(", "), + }, + label: parameter.name, + field: "bricscad_visibility", + }) + .collect() + } + /// Recompute the visibility grip for the active tab's single selection and /// append it (as a Triangle grip) to `selected_grips`. Clears it when the /// selection is not a dynamic-block reference. `wo` is the world offset diff --git a/src/scene/bricscad_parameters.rs b/src/scene/bricscad_parameters.rs new file mode 100644 index 0000000000..f7fddeb470 --- /dev/null +++ b/src/scene/bricscad_parameters.rs @@ -0,0 +1,448 @@ +//! Visibility states of BricsCAD parametric blocks, read from the objects +//! BricsCAD keeps them in. +//! +//! BricsCAD stores a parametric block's parameters in objects of its own +//! classes under `BDM_DATABASE` in the block's extension dictionary. They are +//! read as raw records (`ObjectType::Unknown`); this module decodes the few it +//! needs from their DWG bytes (DWG 2010 and later): +//! +//! - `BDMDBFEATUREMANAGER` (`FEATURE_MANAGER`) lists the block's features. +//! - A `BDMDBFEATUREDATA` of type `BdmConfigurationFeature` whose table type +//! is `VisibilityStates` is one visibility parameter: its name and the state +//! the block shows (`LastKeyValue`). +//! - Its `BDMDBCONFIGURATIONTABLE` names the states (`KeyValues`). +//! - The `BdmDbPersIdManager` (`PERSIDMANAGER`) of an anonymous copy names the +//! block it was made from (`original.block`). +//! +//! A reference in a state other than the definition's shows such a copy, whose +//! own features hold the state it shows; the members a state hides sit on the +//! layer `*SUPPRESS` there. +//! +//! Each of these objects is a list of named properties. The data stream holds +//! the count and, per property, a type byte and the value. Names and text +//! values are in the string stream and object references in the handle +//! stream, in the order the properties name them. + +use document::objects::ObjectType; +use document::{Document, DxfVersion, EntityType, Handle}; + +/// A visibility parameter of a BricsCAD parametric block. +#[derive(Debug, Clone, PartialEq)] +pub struct VisibilityParameter { + pub name: String, + pub states: Vec, + /// The state the block shows, by index into `states`. + pub current: Option, +} + +/// The visibility parameters of block record `block`, in the order its feature +/// list holds them. Empty for a block BricsCAD did not make parametric, and +/// for one whose objects cannot be read. +pub fn visibility_parameters(document: &Document, block: Handle) -> Vec { + let Some(manager) = database_entry(document, block, "FEATURE_MANAGER") else { + return Vec::new(); + }; + let Some(Value::List(features)) = + properties(document, manager).and_then(|p| p.take("Features")) + else { + return Vec::new(); + }; + features + .iter() + .filter_map(|feature| match feature { + Value::Object(handle) => visibility_parameter(document, *handle), + _ => None, + }) + .collect() +} + +/// The visibility parameters of the block reference `insert`, in the states +/// it shows. +pub fn reference_parameters(document: &Document, insert: Handle) -> Vec { + let Some(EntityType::Insert(reference)) = document.get_entity(insert) else { + return Vec::new(); + }; + document + .block_records + .get(&reference.block_name) + .map(|record| visibility_parameters(document, record.handle)) + .unwrap_or_default() +} + +/// The block an anonymous copy of a BricsCAD parametric block was made from. +pub fn original_block(document: &Document, block: Handle) -> Option { + let manager = database_entry(document, block, "PERSIDMANAGER")?; + match properties(document, manager)?.take("original.block")? { + Value::Object(original) if !original.is_null() && original != block => Some(original), + _ => None, + } +} + +fn visibility_parameter(document: &Document, feature: Handle) -> Option { + let feature = properties(document, feature)?; + if feature.text("Feature_type")? != "BdmConfigurationFeature" + || feature.text("TableType")? != "VisibilityStates" + { + return None; + } + let Value::Object(table) = feature.get("ConfigTable")? else { + return None; + }; + let table = properties(document, *table)?; + let Value::List(keys) = table.get("KeyValues")? else { + return None; + }; + let states: Vec = keys + .iter() + .map(|key| match key { + Value::Text(state) => Some(state.clone()), + _ => None, + }) + .collect::>()?; + let name = table + .text("KeyName") + .or_else(|| feature.text("Name"))? + .to_string(); + let current = feature + .text("LastKeyValue") + .and_then(|shown| states.iter().position(|state| state == shown)); + Some(VisibilityParameter { + name, + states, + current, + }) +} + +/// Entry `key` of the `BDM_DATABASE` dictionary in `block`'s extension +/// dictionary. +fn database_entry(document: &Document, block: Handle, key: &str) -> Option { + let dictionary = |handle: Handle| match document.objects.get(&handle)? { + ObjectType::Dictionary(dictionary) => Some(dictionary), + _ => None, + }; + let extension = dictionary(document.extension_dictionary_handle(block)?)?; + dictionary(extension.get("BDM_DATABASE")?)?.get(key) +} + +/// A property value of a BricsCAD object. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Value { + Text(String), + Integer(i32), + Real(f64), + Flag(bool), + Byte(u8), + /// A handle written as its bytes in the data stream. + Raw(Vec), + /// A reference through the handle stream. + Object(Handle), + List(Vec), + Map(Vec<(Value, Value)>), +} + +/// The named properties of one BricsCAD object, in stored order. +#[derive(Debug, Clone, PartialEq, Default)] +pub(crate) struct Properties(pub(crate) Vec<(String, Value)>); + +impl Properties { + pub(crate) fn get(&self, name: &str) -> Option<&Value> { + self.0 + .iter() + .find(|(key, _)| key == name) + .map(|(_, value)| value) + } + + fn take(mut self, name: &str) -> Option { + let index = self.0.iter().position(|(key, _)| key == name)?; + Some(self.0.swap_remove(index).1) + } + + fn text(&self, name: &str) -> Option<&str> { + match self.get(name)? { + Value::Text(text) => Some(text), + _ => None, + } + } +} + +/// The properties of the BricsCAD object `handle`, decoded from the DWG +/// record it was read from. `None` for any other object, a record from a DXF +/// file or a DWG before 2010, and a record that does not decode in full. +pub(crate) fn properties(document: &Document, handle: Handle) -> Option { + let ObjectType::Unknown { + raw_dwg_data: Some(data), + raw_dwg_handle_bits, + raw_dwg_version: Some(version), + .. + } = document.objects.get(&handle)? + else { + return None; + }; + decode(data, *raw_dwg_handle_bits, *version) +} + +/// Decode one object record: the merged data, string and handle streams as +/// the DWG reader keeps them, without the size prefixes and the CRC. +pub(crate) fn decode(data: &[u8], handle_bits: i64, version: DxfVersion) -> Option { + if version < DxfVersion::AC1024 { + return None; + } + let total = data.len().checked_mul(8)?; + let handles_at = total.checked_sub(usize::try_from(handle_bits).ok()?)?; + let mut main = Bits::new(data, 0, handles_at); + main.object_type()?; + let own = main.handle(0)?; + // Extended data: blocks of a size, an application handle and the bytes, + // until a size of 0. + loop { + let size = main.bit_short()?; + if size <= 0 { + break; + } + main.handle(0)?; + for _ in 0..size { + main.byte()?; + } + } + let reactors = main.bit_long()?; + let has_extension_dictionary = !main.bit()?; + if version >= DxfVersion::AC1027 { + main.bit()?; + } + + let (strings_at, strings_end) = string_stream(data, handles_at)?; + if main.pos > strings_at { + return None; + } + main.end = strings_at; + let mut handles = Bits::new(data, handles_at, total); + handles.handle(own)?; // owner + for _ in 0..reactors { + handles.handle(own)?; + } + if has_extension_dictionary { + handles.handle(own)?; + } + let mut reader = Reader { + main, + strings: Bits::new(data, strings_at, strings_end), + handles, + own, + }; + let properties = reader.properties()?; + // A record that leaves data unread was not one of these property lists. + (reader.main.pos == reader.main.end).then_some(properties) +} + +/// The bit range of the string stream, which ends where the data stream's +/// last bit says whether there is one. +fn string_stream(data: &[u8], handles_at: usize) -> Option<(usize, usize)> { + let flag = handles_at.checked_sub(1)?; + if !Bits::new(data, flag, handles_at).bit()? { + return Some((flag, flag)); + } + let size_at = flag.checked_sub(16)?; + let mut size = usize::from(Bits::new(data, size_at, flag).raw_short()?); + let mut start = size_at; + if size & 0x8000 != 0 { + let high_at = size_at.checked_sub(16)?; + let high = usize::from(Bits::new(data, high_at, size_at).raw_short()?); + size = (size & 0x7FFF) | (high << 15); + start = high_at; + } + Some((start.checked_sub(size)?, start)) +} + +struct Reader<'a> { + main: Bits<'a>, + strings: Bits<'a>, + handles: Bits<'a>, + own: u64, +} + +impl Reader<'_> { + fn properties(&mut self) -> Option { + let count = self.main.bit_long()?; + let mut properties = Vec::new(); + for _ in 0..count { + let name = self.text()?; + let kind = self.main.byte()?; + properties.push((name, self.value(kind, 0)?)); + } + Some(Properties(properties)) + } + + fn value(&mut self, kind: u8, depth: u8) -> Option { + // Lists and maps nest at most a level or two; a deeper one is not + // a property list. + if depth > 4 { + return None; + } + Some(match kind { + 2 => Value::Text(self.text()?), + 3 => Value::Integer(self.main.bit_long()?), + 4 => Value::Real(self.main.bit_double()?), + 5 => Value::Flag(self.main.bit()?), + 6 => Value::Byte(self.main.byte()?), + 7 => { + let length = self.main.byte()?; + Value::Raw( + (0..length) + .map(|_| self.main.byte()) + .collect::>()?, + ) + } + 8 => { + self.main.byte()?; // the kind of reference + Value::Object(Handle::from(self.handles.handle(self.own)?)) + } + 9 => { + let element = self.main.byte()?; + let count = self.count()?; + Value::List( + (0..count) + .map(|_| self.value(element, depth + 1)) + .collect::>()?, + ) + } + 10 => { + let key = self.main.byte()?; + let value = self.main.byte()?; + let count = self.count()?; + Value::Map( + (0..count) + .map(|_| Some((self.value(key, depth + 1)?, self.value(value, depth + 1)?))) + .collect::>()?, + ) + } + _ => return None, + }) + } + + /// An element count. Every element takes at least one bit of one of the + /// streams, so a count beyond the record's bits is not one. + fn count(&mut self) -> Option { + let count = usize::try_from(self.main.bit_long()?).ok()?; + (count <= self.main.data.len() * 8).then_some(count) + } + + /// A string from the string stream: a length, then UTF-16 code units. + fn text(&mut self) -> Option { + let length = usize::try_from(self.strings.bit_short()?).ok()?; + if length * 16 > self.strings.end - self.strings.pos { + return None; + } + let units: Vec = (0..length) + .map(|_| self.strings.raw_short()) + .collect::>()?; + Some(String::from_utf16_lossy(&units)) + } +} + +/// A bit range of a record, read most significant bit first. +struct Bits<'a> { + data: &'a [u8], + pos: usize, + end: usize, +} + +impl<'a> Bits<'a> { + fn new(data: &'a [u8], pos: usize, end: usize) -> Self { + Self { + data, + pos, + end: end.min(data.len() * 8), + } + } + + fn bit(&mut self) -> Option { + if self.pos >= self.end { + return None; + } + let bit = self.data[self.pos / 8] >> (7 - self.pos % 8) & 1; + self.pos += 1; + Some(bit == 1) + } + + fn bits(&mut self, count: u32) -> Option { + (0..count).try_fold(0, |value, _| Some(value << 1 | u32::from(self.bit()?))) + } + + fn byte(&mut self) -> Option { + self.bits(8).map(|value| value as u8) + } + + fn raw_short(&mut self) -> Option { + Some(u16::from_le_bytes([self.byte()?, self.byte()?])) + } + + fn raw_long(&mut self) -> Option { + Some(u32::from_le_bytes([ + self.byte()?, + self.byte()?, + self.byte()?, + self.byte()?, + ])) + } + + fn bit_short(&mut self) -> Option { + Some(match self.bits(2)? { + 0 => self.raw_short()? as i16, + 1 => i16::from(self.byte()?), + 2 => 0, + _ => 256, + }) + } + + fn bit_long(&mut self) -> Option { + match self.bits(2)? { + 0 => Some(self.raw_long()? as i32), + 1 => Some(i32::from(self.byte()?)), + 2 => Some(0), + _ => None, + } + } + + fn bit_double(&mut self) -> Option { + match self.bits(2)? { + 0 => { + let mut bytes = [0; 8]; + for byte in &mut bytes { + *byte = self.byte()?; + } + Some(f64::from_le_bytes(bytes)) + } + 1 => Some(1.0), + 2 => Some(0.0), + _ => None, + } + } + + /// The object type of a DWG 2010 or later record. + fn object_type(&mut self) -> Option { + match self.bits(2)? { + 0 => self.byte().map(u16::from), + 1 => self.byte().map(|byte| 0x1F0 + u16::from(byte)), + _ => self.raw_short(), + } + } + + /// A handle reference; the offset codes count from `reference`. + fn handle(&mut self, reference: u64) -> Option { + let form = self.byte()?; + let mut value = 0u64; + for _ in 0..form & 0x0F { + value = value << 8 | u64::from(self.byte()?); + } + Some(match form >> 4 { + 0x6 => reference.checked_add(1)?, + 0x8 => reference.checked_sub(1)?, + 0xA => reference.checked_add(value)?, + 0xC => reference.checked_sub(value)?, + _ => value, + }) + } +} + +#[cfg(test)] +mod tests; diff --git a/src/scene/bricscad_parameters/tests.rs b/src/scene/bricscad_parameters/tests.rs new file mode 100644 index 0000000000..393ec3cc1b --- /dev/null +++ b/src/scene/bricscad_parameters/tests.rs @@ -0,0 +1,134 @@ +use super::*; + +/// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README). +fn fixture() -> Document { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/bricscad/visibility-states.dwg" + ); + let bytes = std::fs::read(path).expect("read the fixture"); + crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes) + .expect("open the fixture") +} + +fn block(document: &Document, name: &str) -> Handle { + document.block_records.get(name).unwrap().handle +} + +/// The block reference with handle `value`. +fn reference(value: u64) -> Handle { + Handle::from(value) +} + +/// Each parameter as its name and the state it shows. +fn shown(parameters: &[VisibilityParameter]) -> Vec<(&str, &str)> { + parameters + .iter() + .map(|parameter| { + ( + parameter.name.as_str(), + parameter + .current + .map_or("?", |index| parameter.states[index].as_str()), + ) + }) + .collect() +} + +#[test] +fn the_definition_names_its_parameters_their_states_and_the_ones_it_shows() { + let document = fixture(); + let parameters = + visibility_parameters(&document, block(&document, "ocs-bricscad-visibility-block")); + assert_eq!( + parameters, + vec![ + VisibilityParameter { + name: "LAMP".into(), + states: vec!["On".into(), "Off".into()], + current: Some(0), + }, + VisibilityParameter { + name: "LABEL".into(), + states: vec!["Shown".into(), "Hidden".into()], + current: Some(0), + }, + ] + ); +} + +#[test] +fn each_reference_shows_the_states_it_was_set_to() { + let document = fixture(); + assert_eq!( + shown(&reference_parameters(&document, reference(0xEE))), + [("LAMP", "On"), ("LABEL", "Shown")] + ); + assert_eq!( + shown(&reference_parameters(&document, reference(0x146))), + [("LAMP", "Off"), ("LABEL", "Shown")] + ); + assert_eq!( + shown(&reference_parameters(&document, reference(0x19E))), + [("LAMP", "Off"), ("LABEL", "Hidden")] + ); +} + +#[test] +fn a_copy_names_the_block_it_was_made_from() { + let document = fixture(); + let definition = block(&document, "ocs-bricscad-visibility-block"); + for copy in ["*U2", "*U3"] { + assert_eq!( + original_block(&document, block(&document, copy)), + Some(definition), + "{copy}" + ); + } + assert_eq!(original_block(&document, definition), None); +} + +#[test] +fn other_blocks_and_references_have_no_parameters() { + let document = fixture(); + let model = document.header.model_space_block_handle; + assert!(visibility_parameters(&document, model).is_empty()); + assert_eq!(original_block(&document, model), None); + let line = document + .entities() + .find(|entity| matches!(entity, EntityType::Line(_))) + .unwrap() + .common() + .handle; + assert!(reference_parameters(&document, line).is_empty()); +} + +#[test] +fn a_cut_record_decodes_to_nothing_rather_than_a_wrong_answer() { + let document = fixture(); + let mut records = 0; + for object in document.objects.values() { + let ObjectType::Unknown { + type_name, + raw_dwg_data: Some(data), + raw_dwg_handle_bits, + raw_dwg_version: Some(version), + .. + } = object + else { + continue; + }; + if type_name != "BDMDBCONFIGURATIONTABLE" { + continue; + } + let whole = decode(data, *raw_dwg_handle_bits, *version).expect("the whole record"); + assert!(whole.get("KeyValues").is_some()); + records += 1; + for length in 0..data.len() { + // Shorter by whole bytes: the streams no longer line up. + let _ = decode(&data[..length], *raw_dwg_handle_bits, *version); + } + assert_eq!(decode(data, *raw_dwg_handle_bits, DxfVersion::AC1021), None); + } + assert_eq!(records, 6, "two tables in each of the three blocks"); +} diff --git a/src/scene/mod.rs b/src/scene/mod.rs index 41e5a9a332..79430524e6 100644 --- a/src/scene/mod.rs +++ b/src/scene/mod.rs @@ -26,6 +26,7 @@ pub(crate) mod block_point_parameter; pub(crate) mod block_properties_table; pub mod block_service; pub mod block_visibility; +pub(crate) mod bricscad_parameters; pub mod cache; pub mod compare; pub mod convert; From 675d7bd29529574d805a71a44a6a7771693d89fc Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:53:35 +0100 Subject: [PATCH 3/7] Properties switch the visibility states of a BricsCAD parametric block reference A reference to a BricsCAD parametric block now lists each visibility parameter's states in Properties, and a state picked there is shown the way BricsCAD shows it, so BricsCAD reads the reference in that state, keeps its parameters and goes on from there: - the reference shows the block when the states are the block's own, a copy of the block that shows them when there is one (BricsCAD shares copies too), or a new anonymous copy: the block's members and every object under its extension dictionary (BricsCAD's parameter objects, the associative network, the draw order) cloned under new handles, with the states set as BricsCAD sets them in its own copies; - its attributes move on or off *SUPPRESS with their definitions; - its entry in model space (a BmAssemblyParameters feature reached through a BDMOBJECT) lists every parameter set on it, as BricsCAD keeps it, and is created, with model space's own parameter objects when there are none. A block BricsCAD never copied gets the tag BricsCAD gives it on its first copy. Picking works for several references at once and is one undo step. Writing BricsCAD's objects needs their records encoded again: the decoder moves into scene::bricscad_parameters::record, keeps everything needed to write a record back bit for bit, and encodes. Besides the plain property lists it reads the constraint manager, BDMOBJECT and the object dependency. --- src/app/block_parameter_properties.rs | 23 +- src/app/bricscad_visibility_tests.rs | 116 +- src/app/properties.rs | 10 +- src/app/visibility.rs | 104 +- src/scene/block_parameter_properties.rs | 2 + src/scene/bricscad_parameters.rs | 431 ++---- src/scene/bricscad_parameters/record.rs | 925 ++++++++++++ src/scene/bricscad_parameters/record_tests.rs | 117 ++ src/scene/bricscad_parameters/switch.rs | 1288 +++++++++++++++++ src/scene/bricscad_parameters/switch_tests.rs | 458 ++++++ src/scene/bricscad_parameters/tests.rs | 15 +- src/scene/model/object.rs | 3 + 12 files changed, 3103 insertions(+), 389 deletions(-) create mode 100644 src/scene/bricscad_parameters/record.rs create mode 100644 src/scene/bricscad_parameters/record_tests.rs create mode 100644 src/scene/bricscad_parameters/switch.rs create mode 100644 src/scene/bricscad_parameters/switch_tests.rs diff --git a/src/app/block_parameter_properties.rs b/src/app/block_parameter_properties.rs index a4f74eda62..4d288d6ff2 100644 --- a/src/app/block_parameter_properties.rs +++ b/src/app/block_parameter_properties.rs @@ -45,8 +45,13 @@ impl OpenCADStudio { } else { None }; - let definition = - |handle| crate::scene::block_actions::instance::definition(&tab.scene.document, handle); + // A BricsCAD parametric block's references, whether they show the + // block or a copy of it, share the block. + let definition = |handle| { + crate::scene::bricscad_parameters::master_block(&tab.scene.document, handle).or_else( + || crate::scene::block_actions::instance::definition(&tab.scene.document, handle), + ) + }; let first = definition(handles[0])?; handles .iter() @@ -71,6 +76,12 @@ impl OpenCADStudio { let doc = &tab.scene.document; let mut rows = native::properties(doc, None, tab.id, insert); rows.extend(Self::indexed_visibility_property(doc, tab.id, insert)); + rows.extend(Self::bricscad_visibility_properties( + doc, + tab.id, + insert, + editor_session.is_none(), + )); rows }; let key = |value: &PropValue| match value { @@ -175,6 +186,8 @@ impl OpenCADStudio { .document .dynamic_visibility_for_insert(key.insert) .map(|(definition, _)| definition) + } else if matches!(key.component, BlockParameterComponent::Bricscad(_)) { + crate::scene::bricscad_parameters::master_block(&tab.scene.document, key.insert) } else { crate::scene::block_actions::instance::definition(&tab.scene.document, key.insert) }; @@ -229,6 +242,9 @@ impl OpenCADStudio { (BlockParameterComponent::Visibility(_), Input::Choice(state)) => { Self::stage_visibility_property(source, target, state) } + (BlockParameterComponent::Bricscad(_), Input::Choice(state)) => { + Self::stage_bricscad_visibility(source, target, state) + } _ => native::evaluate(source, None, target, input), }?; if let Some(next) = next { @@ -242,6 +258,9 @@ impl OpenCADStudio { (BlockParameterComponent::Visibility(_), Input::Choice(state)) => { Self::stage_visibility_property(&tab.scene.document, key, state) } + (BlockParameterComponent::Bricscad(_), Input::Choice(state)) => { + Self::stage_bricscad_visibility(&tab.scene.document, key, state) + } _ => native::evaluate(&tab.scene.document, baseline, key, input), } }; diff --git a/src/app/bricscad_visibility_tests.rs b/src/app/bricscad_visibility_tests.rs index cabb023715..413129b209 100644 --- a/src/app/bricscad_visibility_tests.rs +++ b/src/app/bricscad_visibility_tests.rs @@ -1,9 +1,10 @@ -//! A reference to a BricsCAD parametric block names the block and shows its +//! A reference to a BricsCAD parametric block names the block and lists its //! visibility parameters in Properties, also when it shows an anonymous copy -//! of the block in another state. +//! of the block in another state, and a state picked there is shown the way +//! BricsCAD shows it. use super::*; -use crate::scene::model::object::PropValue; +use crate::scene::model::object::{BlockParameterComponent, BlockParameterKey, PropValue}; use document::Handle; /// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README), opened @@ -40,23 +41,46 @@ fn select(app: &mut OpenCADStudio, references: &[u64]) { app.refresh_properties(); } -/// The visibility rows as label, value and tooltip. -fn visibility_rows(app: &OpenCADStudio) -> Vec<(String, String, String)> { +/// The visibility rows as label, shown state and states, with their keys. +fn visibility_rows(app: &OpenCADStudio) -> Vec<(String, String, Vec, BlockParameterKey)> { app.tabs[app.active_tab] .properties .sections .iter() .flat_map(|section| §ion.props) - .filter(|property| property.field == "bricscad_visibility") - .map(|property| match &property.value { - PropValue::ReadOnlyWithTooltip { value, tooltip } => { - (property.label.clone(), value.clone(), tooltip.clone()) - } - other => panic!("{} is {other:?}", property.label), + .filter_map(|property| match &property.value { + PropValue::BlockChoice { + key, + selected, + options, + .. + } if matches!(key.component, BlockParameterComponent::Bricscad(_)) => Some(( + property.label.clone(), + options + .get(*selected) + .cloned() + .unwrap_or_else(|| "*VARIES*".into()), + options.clone(), + *key, + )), + _ => None, }) .collect() } +fn shown(app: &OpenCADStudio) -> Vec<(String, String)> { + visibility_rows(app) + .into_iter() + .map(|(label, state, ..)| (label, state)) + .collect() +} + +fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter() + .map(|(a, b)| (a.to_string(), b.to_string())) + .collect() +} + fn block_name(app: &OpenCADStudio) -> String { let row = app.tabs[app.active_tab] .properties @@ -71,15 +95,18 @@ fn block_name(app: &OpenCADStudio) -> String { } } -fn rows(lamp: &str, label: &str) -> Vec<(String, String, String)> { - vec![ - ("LAMP".into(), lamp.into(), "On, Off".into()), - ("LABEL".into(), label.into(), "Shown, Hidden".into()), - ] +/// Pick `state` in the list of `parameter`, as a click in Properties does. +fn pick(app: &mut OpenCADStudio, parameter: &str, state: &str) { + let (_, _, options, key) = visibility_rows(app) + .into_iter() + .find(|(label, ..)| label == parameter) + .unwrap_or_else(|| panic!("no {parameter} row")); + let index = options.iter().position(|option| option == state).unwrap(); + let _ = app.update(Message::PropBlockChoice { key, index }); } #[test] -fn a_reference_shows_the_states_it_was_set_to_and_names_its_block() { +fn a_reference_lists_the_states_it_was_set_to_and_names_its_block() { let mut app = opened(); for (reference, lamp, label) in [ (0xEE, "On", "Shown"), @@ -87,7 +114,14 @@ fn a_reference_shows_the_states_it_was_set_to_and_names_its_block() { (0x19E, "Off", "Hidden"), ] { select(&mut app, &[reference]); - assert_eq!(visibility_rows(&app), rows(lamp, label), "{reference:X}"); + assert_eq!( + shown(&app), + pairs(&[("LAMP", lamp), ("LABEL", label)]), + "{reference:X}" + ); + let rows = visibility_rows(&app); + assert_eq!(rows[0].2, ["On", "Off"]); + assert_eq!(rows[1].2, ["Shown", "Hidden"]); assert_eq!( block_name(&app), "ocs-bricscad-visibility-block", @@ -95,3 +129,49 @@ fn a_reference_shows_the_states_it_was_set_to_and_names_its_block() { ); } } + +#[test] +fn a_state_picked_in_properties_is_shown_and_undone_in_one_step() { + let mut app = opened(); + let i = app.active_tab; + let before = app.tabs[i].scene.document.clone(); + select(&mut app, &[0xEE]); + pick(&mut app, "LABEL", "Hidden"); + assert_eq!(shown(&app), pairs(&[("LAMP", "On"), ("LABEL", "Hidden")])); + assert!(app.tabs[i].dirty); + let _ = app.update(Message::Undo); + select(&mut app, &[0xEE]); + assert_eq!(shown(&app), pairs(&[("LAMP", "On"), ("LABEL", "Shown")])); + assert!( + app.tabs[i] + .scene + .document + .block_records + .get("*U4") + .is_none(), + "undo takes the new copy away" + ); + assert_eq!( + app.tabs[i].scene.document.block_records.iter().count(), + before.block_records.iter().count() + ); +} + +#[test] +fn references_selected_together_switch_together() { + let mut app = opened(); + select(&mut app, &[0xEE, 0x146]); + assert_eq!( + shown(&app), + pairs(&[("LAMP", "*VARIES*"), ("LABEL", "Shown")]) + ); + pick(&mut app, "LABEL", "Hidden"); + for (reference, lamp) in [(0xEE, "On"), (0x146, "Off")] { + select(&mut app, &[reference]); + assert_eq!( + shown(&app), + pairs(&[("LAMP", lamp), ("LABEL", "Hidden")]), + "{reference:X}" + ); + } +} diff --git a/src/app/properties.rs b/src/app/properties.rs index 08dc63885b..4a4eeb66c7 100644 --- a/src/app/properties.rs +++ b/src/app/properties.rs @@ -1073,7 +1073,15 @@ impl OpenCADStudio { custom_properties.extend(Self::visibility_property(doc, handle)); } custom_properties.extend(Self::visible_blocks_property(doc, handle)); - custom_properties.extend(Self::bricscad_visibility_properties(doc, handle)); + // A BricsCAD parametric block's states, switched from a list + // outside the Block Editor and Test Block. + custom_properties.extend(Self::bricscad_visibility_properties( + doc, + self.tabs[i].id, + handle, + self.tabs[i].active_block_edit_session().is_none() + && self.tabs[i].block_test.is_none(), + )); if !custom_properties.is_empty() { sections.push(crate::scene::model::object::PropSection { title: t!("Custom").into_owned(), diff --git a/src/app/visibility.rs b/src/app/visibility.rs index 1f503d594f..85e6e3fd96 100644 --- a/src/app/visibility.rs +++ b/src/app/visibility.rs @@ -120,6 +120,15 @@ fn visibility_revision(parameter: &BlockVisibilityParameter) -> u64 { hash.finish() } +/// Identifies a BricsCAD visibility parameter by its name and states, so a +/// list built for one block is not applied to a parameter that changed. +fn bricscad_revision(parameter: &crate::scene::bricscad_parameters::VisibilityParameter) -> u64 { + let mut hash = std::collections::hash_map::DefaultHasher::new(); + parameter.name.hash(&mut hash); + parameter.states.hash(&mut hash); + hash.finish() +} + fn visibility_label(parameter: &BlockVisibilityParameter) -> String { if parameter.name.trim().is_empty() { "Visibility1".into() @@ -627,30 +636,95 @@ impl OpenCADStudio { } /// The visibility parameters of a reference to a BricsCAD parametric - /// block, one read-only row each with the state the reference shows and - /// the parameter's states as tooltip. They are read from BricsCAD's own - /// objects, which are kept as they were read, so they are not changed - /// here. + /// block, one row each with the state the reference shows. With + /// `editable`, a reference that can be switched (see + /// `bricscad_parameters::can_switch`) gets a list of the states; any + /// other shows the state with the states as tooltip. pub(super) fn bricscad_visibility_properties( doc: &document::Document, + document: u64, handle: Handle, + editable: bool, ) -> Vec { - crate::scene::bricscad_parameters::reference_parameters(doc, handle) + use crate::scene::bricscad_parameters as bricscad; + let parameters = bricscad::reference_parameters(doc, handle); + if parameters.is_empty() { + return Vec::new(); + } + let master = bricscad::master_block(doc, handle) + .filter(|_| editable && bricscad::can_switch(doc, handle)); + let master_parameters = master + .map(|master| bricscad::visibility_parameters(doc, master)) + .unwrap_or_default(); + parameters .into_iter() - .map(|parameter| Property { - value: PropValue::ReadOnlyWithTooltip { - value: parameter - .current - .and_then(|index| parameter.states.get(index).cloned()) - .unwrap_or_default(), - tooltip: parameter.states.join(", "), - }, - label: parameter.name, - field: "bricscad_visibility", + .map(|parameter| { + let feature = master_parameters + .iter() + .find(|shown| shown.name == parameter.name && shown.states == parameter.states) + .map(|shown| shown.feature); + let value = match (master, feature) { + (Some(definition), Some(feature)) => PropValue::BlockChoice { + key: BlockParameterKey { + document, + definition, + insert: handle, + batch_generation: None, + editor_session: None, + parameter: feature, + component: BlockParameterComponent::Bricscad(bricscad_revision( + ¶meter, + )), + }, + selected: parameter.current.unwrap_or(usize::MAX), + options: parameter.states.clone(), + description: String::new(), + }, + _ => PropValue::ReadOnlyWithTooltip { + value: parameter + .current + .and_then(|index| parameter.states.get(index).cloned()) + .unwrap_or_default(), + tooltip: parameter.states.join(", "), + }, + }; + Property { + value, + label: parameter.name, + field: "bricscad_visibility", + } }) .collect() } + /// Show state `state` of the BricsCAD visibility parameter `key` names on + /// a copy of `doc`; `None` when the reference shows it already. + pub(super) fn stage_bricscad_visibility( + doc: &document::Document, + key: BlockParameterKey, + state: usize, + ) -> Result, &'static str> { + use crate::scene::bricscad_parameters as bricscad; + const INVALID: &str = "Select supported targets belonging to this block."; + if bricscad::master_block(doc, key.insert) != Some(key.definition) { + return Err(INVALID); + } + let parameter = bricscad::visibility_parameters(doc, key.definition) + .into_iter() + .find(|parameter| parameter.feature == key.parameter) + .ok_or(INVALID)?; + if key.component != BlockParameterComponent::Bricscad(bricscad_revision(¶meter)) { + return Err(INVALID); + } + let state = parameter.states.get(state).ok_or(INVALID)?; + let mut scene = crate::scene::Scene::new(); + scene.document = doc.clone(); + match scene.set_bricscad_visibility(key.insert, ¶meter.name, state)? { + true => Ok(Some(scene.document)), + false => Ok(None), + } + } + /// Recompute the visibility grip for the active tab's single selection and /// append it (as a Triangle grip) to `selected_grips`. Clears it when the /// selection is not a dynamic-block reference. `wo` is the world offset diff --git a/src/scene/block_parameter_properties.rs b/src/scene/block_parameter_properties.rs index 9acb4d3731..daf89a0955 100644 --- a/src/scene/block_parameter_properties.rs +++ b/src/scene/block_parameter_properties.rs @@ -190,6 +190,7 @@ pub(crate) fn component_id(component: &Component) -> String { Component::Angle => "Angle".to_owned(), Component::Flip => "Flip".to_owned(), Component::Visibility(_) => "Visibility".to_owned(), + Component::Bricscad(_) => "BricscadVisibility".to_owned(), Component::TableRow(_) => "TableRow".to_owned(), Component::LookupOutput { column, .. } => format!("Lookup{column}"), } @@ -376,6 +377,7 @@ pub(crate) fn evaluate( } Component::Flip | Component::Visibility(_) + | Component::Bricscad(_) | Component::TableRow(_) | Component::LookupOutput { .. } => unreachable!(), } diff --git a/src/scene/bricscad_parameters.rs b/src/scene/bricscad_parameters.rs index f7fddeb470..434466ba26 100644 --- a/src/scene/bricscad_parameters.rs +++ b/src/scene/bricscad_parameters.rs @@ -18,13 +18,18 @@ //! own features hold the state it shows; the members a state hides sit on the //! layer `*SUPPRESS` there. //! -//! Each of these objects is a list of named properties. The data stream holds -//! the count and, per property, a type byte and the value. Names and text -//! values are in the string stream and object references in the handle -//! stream, in the order the properties name them. +//! [`record`] decodes and encodes the objects; `switch` changes the state a +//! reference shows the way BricsCAD does. use document::objects::ObjectType; -use document::{Document, DxfVersion, EntityType, Handle}; +use document::{Document, EntityType, Handle}; + +pub(crate) mod record; +mod switch; + +pub(crate) use switch::can_switch; + +use record::{Properties, Record}; /// A visibility parameter of a BricsCAD parametric block. #[derive(Debug, Clone, PartialEq)] @@ -33,71 +38,86 @@ pub struct VisibilityParameter { pub states: Vec, /// The state the block shows, by index into `states`. pub current: Option, + /// The parameter's feature in the block it was read from. + pub feature: Handle, } /// The visibility parameters of block record `block`, in the order its feature /// list holds them. Empty for a block BricsCAD did not make parametric, and /// for one whose objects cannot be read. pub fn visibility_parameters(document: &Document, block: Handle) -> Vec { - let Some(manager) = database_entry(document, block, "FEATURE_MANAGER") else { - return Vec::new(); - }; - let Some(Value::List(features)) = - properties(document, manager).and_then(|p| p.take("Features")) - else { - return Vec::new(); - }; - features - .iter() - .filter_map(|feature| match feature { - Value::Object(handle) => visibility_parameter(document, *handle), - _ => None, - }) + features(document, block) + .into_iter() + .filter_map(|feature| visibility_parameter(document, feature)) .collect() } /// The visibility parameters of the block reference `insert`, in the states /// it shows. pub fn reference_parameters(document: &Document, insert: Handle) -> Vec { + shown_block(document, insert) + .map(|block| visibility_parameters(document, block)) + .unwrap_or_default() +} + +/// The block an anonymous copy of a BricsCAD parametric block was made from. +pub fn original_block(document: &Document, block: Handle) -> Option { + let manager = database_entry(document, block, "PERSIDMANAGER")?; + let original = properties(document, manager)? + .get("original.block")? + .object()?; + (!original.is_null() && original != block).then_some(original) +} + +/// The BricsCAD parametric block a reference shows, or shows a copy of. +pub fn master_block(document: &Document, insert: Handle) -> Option { + let block = shown_block(document, insert)?; + let master = original_block(document, block).unwrap_or(block); + (!visibility_parameters(document, master).is_empty()).then_some(master) +} + +/// The block record a reference shows. +fn shown_block(document: &Document, insert: Handle) -> Option { let Some(EntityType::Insert(reference)) = document.get_entity(insert) else { - return Vec::new(); + return None; }; document .block_records .get(&reference.block_name) - .map(|record| visibility_parameters(document, record.handle)) - .unwrap_or_default() + .map(|record| record.handle) } -/// The block an anonymous copy of a BricsCAD parametric block was made from. -pub fn original_block(document: &Document, block: Handle) -> Option { - let manager = database_entry(document, block, "PERSIDMANAGER")?; - match properties(document, manager)?.take("original.block")? { - Value::Object(original) if !original.is_null() && original != block => Some(original), - _ => None, - } +/// The features of `block`'s feature manager, in stored order. +fn features(document: &Document, block: Handle) -> Vec { + database_entry(document, block, "FEATURE_MANAGER") + .and_then(|manager| properties(document, manager)) + .and_then(|manager| { + Some( + manager + .get("Features")? + .items()? + .iter() + .filter_map(record::Value::object) + .collect(), + ) + }) + .unwrap_or_default() } fn visibility_parameter(document: &Document, feature: Handle) -> Option { + let handle = feature; let feature = properties(document, feature)?; if feature.text("Feature_type")? != "BdmConfigurationFeature" || feature.text("TableType")? != "VisibilityStates" { return None; } - let Value::Object(table) = feature.get("ConfigTable")? else { - return None; - }; - let table = properties(document, *table)?; - let Value::List(keys) = table.get("KeyValues")? else { - return None; - }; - let states: Vec = keys + let table = properties(document, feature.get("ConfigTable")?.object()?)?; + let states: Vec = table + .get("KeyValues")? + .items()? .iter() - .map(|key| match key { - Value::Text(state) => Some(state.clone()), - _ => None, - }) + .map(|state| state.text().map(str::to_string)) .collect::>()?; let name = table .text("KeyName") @@ -110,66 +130,27 @@ fn visibility_parameter(document: &Document, feature: Handle) -> Option Option { +fn database_entry(document: &Document, owner: Handle, key: &str) -> Option { let dictionary = |handle: Handle| match document.objects.get(&handle)? { ObjectType::Dictionary(dictionary) => Some(dictionary), _ => None, }; - let extension = dictionary(document.extension_dictionary_handle(block)?)?; + let extension = dictionary(document.extension_dictionary_handle(owner)?)?; dictionary(extension.get("BDM_DATABASE")?)?.get(key) } -/// A property value of a BricsCAD object. -#[derive(Debug, Clone, PartialEq)] -pub(crate) enum Value { - Text(String), - Integer(i32), - Real(f64), - Flag(bool), - Byte(u8), - /// A handle written as its bytes in the data stream. - Raw(Vec), - /// A reference through the handle stream. - Object(Handle), - List(Vec), - Map(Vec<(Value, Value)>), -} - -/// The named properties of one BricsCAD object, in stored order. -#[derive(Debug, Clone, PartialEq, Default)] -pub(crate) struct Properties(pub(crate) Vec<(String, Value)>); - -impl Properties { - pub(crate) fn get(&self, name: &str) -> Option<&Value> { - self.0 - .iter() - .find(|(key, _)| key == name) - .map(|(_, value)| value) - } - - fn take(mut self, name: &str) -> Option { - let index = self.0.iter().position(|(key, _)| key == name)?; - Some(self.0.swap_remove(index).1) - } - - fn text(&self, name: &str) -> Option<&str> { - match self.get(name)? { - Value::Text(text) => Some(text), - _ => None, - } - } -} - -/// The properties of the BricsCAD object `handle`, decoded from the DWG -/// record it was read from. `None` for any other object, a record from a DXF -/// file or a DWG before 2010, and a record that does not decode in full. -pub(crate) fn properties(document: &Document, handle: Handle) -> Option { +/// The record of the BricsCAD object `handle`, decoded from the DWG record it +/// was read from. `None` for any other object, a record from a DXF file or a +/// DWG before 2010, and a record that does not decode in full. +pub(crate) fn record(document: &Document, handle: Handle) -> Option { let ObjectType::Unknown { + type_name, raw_dwg_data: Some(data), raw_dwg_handle_bits, raw_dwg_version: Some(version), @@ -178,271 +159,23 @@ pub(crate) fn properties(document: &Document, handle: Handle) -> Option Option { - if version < DxfVersion::AC1024 { - return None; - } - let total = data.len().checked_mul(8)?; - let handles_at = total.checked_sub(usize::try_from(handle_bits).ok()?)?; - let mut main = Bits::new(data, 0, handles_at); - main.object_type()?; - let own = main.handle(0)?; - // Extended data: blocks of a size, an application handle and the bytes, - // until a size of 0. - loop { - let size = main.bit_short()?; - if size <= 0 { - break; - } - main.handle(0)?; - for _ in 0..size { - main.byte()?; - } - } - let reactors = main.bit_long()?; - let has_extension_dictionary = !main.bit()?; - if version >= DxfVersion::AC1027 { - main.bit()?; - } - - let (strings_at, strings_end) = string_stream(data, handles_at)?; - if main.pos > strings_at { - return None; - } - main.end = strings_at; - let mut handles = Bits::new(data, handles_at, total); - handles.handle(own)?; // owner - for _ in 0..reactors { - handles.handle(own)?; - } - if has_extension_dictionary { - handles.handle(own)?; - } - let mut reader = Reader { - main, - strings: Bits::new(data, strings_at, strings_end), - handles, - own, - }; - let properties = reader.properties()?; - // A record that leaves data unread was not one of these property lists. - (reader.main.pos == reader.main.end).then_some(properties) + record::decode(type_name, data, *raw_dwg_handle_bits, *version) } -/// The bit range of the string stream, which ends where the data stream's -/// last bit says whether there is one. -fn string_stream(data: &[u8], handles_at: usize) -> Option<(usize, usize)> { - let flag = handles_at.checked_sub(1)?; - if !Bits::new(data, flag, handles_at).bit()? { - return Some((flag, flag)); - } - let size_at = flag.checked_sub(16)?; - let mut size = usize::from(Bits::new(data, size_at, flag).raw_short()?); - let mut start = size_at; - if size & 0x8000 != 0 { - let high_at = size_at.checked_sub(16)?; - let high = usize::from(Bits::new(data, high_at, size_at).raw_short()?); - size = (size & 0x7FFF) | (high << 15); - start = high_at; - } - Some((start.checked_sub(size)?, start)) -} - -struct Reader<'a> { - main: Bits<'a>, - strings: Bits<'a>, - handles: Bits<'a>, - own: u64, -} - -impl Reader<'_> { - fn properties(&mut self) -> Option { - let count = self.main.bit_long()?; - let mut properties = Vec::new(); - for _ in 0..count { - let name = self.text()?; - let kind = self.main.byte()?; - properties.push((name, self.value(kind, 0)?)); - } - Some(Properties(properties)) - } - - fn value(&mut self, kind: u8, depth: u8) -> Option { - // Lists and maps nest at most a level or two; a deeper one is not - // a property list. - if depth > 4 { - return None; - } - Some(match kind { - 2 => Value::Text(self.text()?), - 3 => Value::Integer(self.main.bit_long()?), - 4 => Value::Real(self.main.bit_double()?), - 5 => Value::Flag(self.main.bit()?), - 6 => Value::Byte(self.main.byte()?), - 7 => { - let length = self.main.byte()?; - Value::Raw( - (0..length) - .map(|_| self.main.byte()) - .collect::>()?, - ) - } - 8 => { - self.main.byte()?; // the kind of reference - Value::Object(Handle::from(self.handles.handle(self.own)?)) - } - 9 => { - let element = self.main.byte()?; - let count = self.count()?; - Value::List( - (0..count) - .map(|_| self.value(element, depth + 1)) - .collect::>()?, - ) - } - 10 => { - let key = self.main.byte()?; - let value = self.main.byte()?; - let count = self.count()?; - Value::Map( - (0..count) - .map(|_| Some((self.value(key, depth + 1)?, self.value(value, depth + 1)?))) - .collect::>()?, - ) - } - _ => return None, - }) - } - - /// An element count. Every element takes at least one bit of one of the - /// streams, so a count beyond the record's bits is not one. - fn count(&mut self) -> Option { - let count = usize::try_from(self.main.bit_long()?).ok()?; - (count <= self.main.data.len() * 8).then_some(count) - } - - /// A string from the string stream: a length, then UTF-16 code units. - fn text(&mut self) -> Option { - let length = usize::try_from(self.strings.bit_short()?).ok()?; - if length * 16 > self.strings.end - self.strings.pos { - return None; - } - let units: Vec = (0..length) - .map(|_| self.strings.raw_short()) - .collect::>()?; - Some(String::from_utf16_lossy(&units)) +/// The properties of the BricsCAD object `handle` whose record is a plain +/// property list (see [`record`]). +pub(crate) fn properties(document: &Document, handle: Handle) -> Option { + match record(document, handle)?.body { + record::Body::Properties(properties) => Some(properties), + _ => None, } } -/// A bit range of a record, read most significant bit first. -struct Bits<'a> { - data: &'a [u8], - pos: usize, - end: usize, -} - -impl<'a> Bits<'a> { - fn new(data: &'a [u8], pos: usize, end: usize) -> Self { - Self { - data, - pos, - end: end.min(data.len() * 8), - } - } - - fn bit(&mut self) -> Option { - if self.pos >= self.end { - return None; - } - let bit = self.data[self.pos / 8] >> (7 - self.pos % 8) & 1; - self.pos += 1; - Some(bit == 1) - } - - fn bits(&mut self, count: u32) -> Option { - (0..count).try_fold(0, |value, _| Some(value << 1 | u32::from(self.bit()?))) - } - - fn byte(&mut self) -> Option { - self.bits(8).map(|value| value as u8) - } - - fn raw_short(&mut self) -> Option { - Some(u16::from_le_bytes([self.byte()?, self.byte()?])) - } - - fn raw_long(&mut self) -> Option { - Some(u32::from_le_bytes([ - self.byte()?, - self.byte()?, - self.byte()?, - self.byte()?, - ])) - } - - fn bit_short(&mut self) -> Option { - Some(match self.bits(2)? { - 0 => self.raw_short()? as i16, - 1 => i16::from(self.byte()?), - 2 => 0, - _ => 256, - }) - } - - fn bit_long(&mut self) -> Option { - match self.bits(2)? { - 0 => Some(self.raw_long()? as i32), - 1 => Some(i32::from(self.byte()?)), - 2 => Some(0), - _ => None, - } - } - - fn bit_double(&mut self) -> Option { - match self.bits(2)? { - 0 => { - let mut bytes = [0; 8]; - for byte in &mut bytes { - *byte = self.byte()?; - } - Some(f64::from_le_bytes(bytes)) - } - 1 => Some(1.0), - 2 => Some(0.0), - _ => None, - } - } - - /// The object type of a DWG 2010 or later record. - fn object_type(&mut self) -> Option { - match self.bits(2)? { - 0 => self.byte().map(u16::from), - 1 => self.byte().map(|byte| 0x1F0 + u16::from(byte)), - _ => self.raw_short(), - } - } +#[cfg(test)] +mod tests; - /// A handle reference; the offset codes count from `reference`. - fn handle(&mut self, reference: u64) -> Option { - let form = self.byte()?; - let mut value = 0u64; - for _ in 0..form & 0x0F { - value = value << 8 | u64::from(self.byte()?); - } - Some(match form >> 4 { - 0x6 => reference.checked_add(1)?, - 0x8 => reference.checked_sub(1)?, - 0xA => reference.checked_add(value)?, - 0xC => reference.checked_sub(value)?, - _ => value, - }) - } -} +#[cfg(test)] +mod record_tests; #[cfg(test)] -mod tests; +mod switch_tests; diff --git a/src/scene/bricscad_parameters/record.rs b/src/scene/bricscad_parameters/record.rs new file mode 100644 index 0000000000..00f097a784 --- /dev/null +++ b/src/scene/bricscad_parameters/record.rs @@ -0,0 +1,925 @@ +//! BricsCAD's parameter objects as DWG records (2010 and later), decoded so +//! that encoding them again gives the same bits, and encoded after a change. +//! +//! A record holds the common object header (type, handle, extended data, +//! owner, reactors, extension dictionary) and a body. Most of BricsCAD's +//! classes hold a plain list of named properties; three hold a few values +//! around such a list: +//! +//! - `BDMDBCONSTRAINTMANAGER`: five counts, the objects and child managers it +//! owns, then its settings; +//! - `BDMOBJECT`: a byte and a count, the object it stands for, its +//! properties, a count; +//! - `BDMDBOBJECTDEPENDENCY`: its (empty) properties, a count, the object it +//! depends on. +//! +//! In the data stream a property list is a count and, per property, a type +//! byte and the value. Names and text sit in the string stream and references +//! in the handle stream, both in the order the data stream names them. + +use document::{DxfVersion, Handle}; + +/// A reference through the handle stream and the code it is written with: +/// a reference type (2 to 5) or one of the forms relative to the record's own +/// handle (6, 8, 10, 12). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Ref { + pub(crate) handle: Handle, + pub(crate) code: u8, +} + +impl Ref { + pub(crate) fn new(handle: Handle, code: u8) -> Self { + Self { handle, code } + } +} + +/// A property value. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Value { + Text(String), + Integer(i32), + Real(f64), + Flag(bool), + Byte(u8), + /// Bytes in the data stream; BricsCAD stores some handles this way. + Raw(Vec), + /// A reference: a byte in the data stream, the handle in the handle stream. + Object { + kind: u8, + target: Ref, + }, + List { + element: u8, + items: Vec, + }, + Map { + key: u8, + value: u8, + entries: Vec<(Value, Value)>, + }, +} + +impl Value { + fn kind(&self) -> u8 { + match self { + Value::Text(_) => 2, + Value::Integer(_) => 3, + Value::Real(_) => 4, + Value::Flag(_) => 5, + Value::Byte(_) => 6, + Value::Raw(_) => 7, + Value::Object { .. } => 8, + Value::List { .. } => 9, + Value::Map { .. } => 10, + } + } + + pub(crate) fn text(&self) -> Option<&str> { + match self { + Value::Text(text) => Some(text), + _ => None, + } + } + + pub(crate) fn object(&self) -> Option { + match self { + Value::Object { target, .. } => Some(target.handle), + _ => None, + } + } + + pub(crate) fn items(&self) -> Option<&[Value]> { + match self { + Value::List { items, .. } => Some(items), + _ => None, + } + } + + pub(crate) fn entries(&self) -> Option<&[(Value, Value)]> { + match self { + Value::Map { entries, .. } => Some(entries), + _ => None, + } + } + + /// Every reference in the value, in the order they are written. + fn refs_mut(&mut self, visit: &mut impl FnMut(&mut Ref)) { + match self { + Value::Object { target, .. } => visit(target), + Value::List { items, .. } => items.iter_mut().for_each(|item| item.refs_mut(visit)), + Value::Map { entries, .. } => entries.iter_mut().for_each(|(key, value)| { + key.refs_mut(visit); + value.refs_mut(visit); + }), + _ => {} + } + } +} + +/// The named properties of a record, in stored order. +#[derive(Debug, Clone, PartialEq, Default)] +pub(crate) struct Properties(pub(crate) Vec<(String, Value)>); + +impl Properties { + pub(crate) fn get(&self, name: &str) -> Option<&Value> { + self.0 + .iter() + .find(|(key, _)| key == name) + .map(|(_, value)| value) + } + + pub(crate) fn get_mut(&mut self, name: &str) -> Option<&mut Value> { + self.0 + .iter_mut() + .find(|(key, _)| key == name) + .map(|(_, value)| value) + } + + pub(crate) fn text(&self, name: &str) -> Option<&str> { + self.get(name)?.text() + } + + /// Replace the value of an existing property; `false` when there is none. + pub(crate) fn set(&mut self, name: &str, value: Value) -> bool { + match self.get_mut(name) { + Some(slot) => { + *slot = value; + true + } + None => false, + } + } + + fn refs_mut(&mut self, visit: &mut impl FnMut(&mut Ref)) { + for (_, value) in &mut self.0 { + value.refs_mut(visit); + } + } +} + +/// What a record holds after the common header. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Body { + Properties(Properties), + /// `BDMDBCONSTRAINTMANAGER`. `counts[1]` objects and `counts[3]` child + /// managers, in that order in `children`. + ConstraintManager { + counts: [i32; 5], + children: Vec, + settings: Properties, + }, + /// `BDMOBJECT`. + Object { + lead: u8, + lead_count: i32, + entity: Ref, + properties: Properties, + tail: i32, + }, + /// `BDMDBOBJECTDEPENDENCY`. + Dependency { + properties: Properties, + tail: i32, + entity: Ref, + }, +} + +impl Body { + pub(crate) fn properties(&self) -> &Properties { + match self { + Body::Properties(properties) + | Body::Object { properties, .. } + | Body::Dependency { properties, .. } => properties, + Body::ConstraintManager { settings, .. } => settings, + } + } + + pub(crate) fn properties_mut(&mut self) -> &mut Properties { + match self { + Body::Properties(properties) + | Body::Object { properties, .. } + | Body::Dependency { properties, .. } => properties, + Body::ConstraintManager { settings, .. } => settings, + } + } + + /// Every reference of the body, in the order they are written. + fn refs_mut(&mut self, visit: &mut impl FnMut(&mut Ref)) { + match self { + Body::Properties(properties) => properties.refs_mut(visit), + Body::ConstraintManager { + children, settings, .. + } => { + children.iter_mut().for_each(&mut *visit); + settings.refs_mut(visit); + } + Body::Object { + entity, properties, .. + } => { + visit(entity); + properties.refs_mut(visit); + } + Body::Dependency { + properties, entity, .. + } => { + properties.refs_mut(visit); + visit(entity); + } + } + } +} + +/// One record of a BricsCAD parameter object. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct Record { + object_type: u16, + pub(crate) handle: Handle, + handle_code: u8, + extended_data: Vec<(Ref, Vec)>, + pub(crate) owner: Ref, + pub(crate) reactors: Vec, + pub(crate) extension_dictionary: Option, + binary_data: bool, + pub(crate) body: Body, + pub(crate) version: DxfVersion, +} + +impl Record { + /// A new record of the class of `template`, which gives the type number + /// and the version; no extended data, reactors or extension dictionary. + pub(crate) fn like(template: &Record, handle: Handle, owner: Ref, body: Body) -> Self { + Self { + object_type: template.object_type, + handle, + handle_code: template.handle_code, + extended_data: Vec::new(), + owner, + reactors: Vec::new(), + extension_dictionary: None, + binary_data: false, + body, + version: template.version, + } + } + + /// Every reference of the record: owner, reactors, extension dictionary + /// and those of the body. Extended data names applications, which are + /// left alone. + pub(crate) fn refs_mut(&mut self, mut visit: impl FnMut(&mut Ref)) { + visit(&mut self.owner); + self.reactors.iter_mut().for_each(&mut visit); + if let Some(dictionary) = &mut self.extension_dictionary { + visit(dictionary); + } + self.body.refs_mut(&mut visit); + } +} + +/// Decode the record of a `class` object: the merged data, string and handle +/// streams as the DWG reader keeps them, without the size prefixes and the +/// CRC. `None` for a DWG before 2010 and a record that does not decode in +/// full: any data or string bit left over, or more than padding left in the +/// handle stream. +pub(crate) fn decode( + class: &str, + data: &[u8], + handle_bits: i64, + version: DxfVersion, +) -> Option { + if version < DxfVersion::AC1024 { + return None; + } + let total = data.len().checked_mul(8)?; + let handles_at = total.checked_sub(usize::try_from(handle_bits).ok()?)?; + let mut main = Bits::new(data, 0, handles_at); + let object_type = main.object_type()?; + let (handle_code, own) = main.handle(0)?; + let mut extended_data = Vec::new(); + loop { + let size = main.bit_short()?; + if size < 0 { + return None; + } + if size == 0 { + break; + } + let (code, application) = main.handle(0)?; + let bytes = (0..size).map(|_| main.byte()).collect::>>()?; + extended_data.push((Ref::new(Handle::from(application), code), bytes)); + } + let reactor_count = usize::try_from(main.bit_long()?).ok()?; + if reactor_count > total { + return None; + } + let has_extension_dictionary = !main.bit()?; + let binary_data = version >= DxfVersion::AC1027 && main.bit()?; + + let (strings_at, strings_end) = string_stream(data, handles_at)?; + if main.pos > strings_at { + return None; + } + main.end = strings_at; + let mut handles = Bits::new(data, handles_at, total); + let reference = |handles: &mut Bits| { + handles + .handle(own) + .map(|(code, handle)| Ref::new(Handle::from(handle), code)) + }; + let owner = reference(&mut handles)?; + let reactors = (0..reactor_count) + .map(|_| reference(&mut handles)) + .collect::>>()?; + let extension_dictionary = if has_extension_dictionary { + Some(reference(&mut handles)?) + } else { + None + }; + let mut reader = Reader { + main, + strings: Bits::new(data, strings_at, strings_end), + handles, + own, + }; + let body = reader.body(class)?; + let complete = reader.main.pos == reader.main.end + && reader.strings.pos == reader.strings.end + && reader.handles.end - reader.handles.pos < 8; + complete.then_some(Record { + object_type, + handle: Handle::from(own), + handle_code, + extended_data, + owner, + reactors, + extension_dictionary, + binary_data, + body, + version, + }) +} + +/// Encode `record`: the merged streams and the bit count of its handle +/// stream, as the DWG writer takes a raw record. +pub(crate) fn encode(record: &Record) -> (Vec, i64) { + let own = record.handle.value(); + let mut main = Writer::default(); + let strings = Writer::default(); + let mut handles = Writer::default(); + main.object_type(record.object_type); + main.handle(record.handle_code, own, 0); + for (application, bytes) in &record.extended_data { + main.bit_short(bytes.len() as i16); + main.handle(application.code, application.handle.value(), 0); + for byte in bytes { + main.byte(*byte); + } + } + main.bit_short(0); + main.bit_long(record.reactors.len() as i32); + main.bit(record.extension_dictionary.is_none()); + if record.version >= DxfVersion::AC1027 { + main.bit(record.binary_data); + } + handles.reference(record.owner, own); + for reactor in &record.reactors { + handles.reference(*reactor, own); + } + if let Some(dictionary) = record.extension_dictionary { + handles.reference(dictionary, own); + } + let mut encoder = Encoder { + main, + strings, + handles, + own, + }; + encoder.body(&record.body); + let Encoder { + mut main, + strings, + handles, + .. + } = encoder; + let string_bits = strings.len; + if string_bits > 0 { + main.append(&strings); + if string_bits < 0x8000 { + main.raw_short(string_bits as u16); + } else { + main.raw_short((string_bits >> 15) as u16); + main.raw_short((string_bits & 0x7FFF) as u16 | 0x8000); + } + main.bit(true); + } else { + main.bit(false); + } + let main_bits = main.len; + main.append(&handles); + let bytes = main.into_bytes(); + let handle_bits = (bytes.len() * 8 - main_bits) as i64; + (bytes, handle_bits) +} + +/// The bit range of the string stream, which ends where the data stream's +/// last bit says whether there is one. +fn string_stream(data: &[u8], handles_at: usize) -> Option<(usize, usize)> { + let flag = handles_at.checked_sub(1)?; + if !Bits::new(data, flag, handles_at).bit()? { + return Some((flag, flag)); + } + let size_at = flag.checked_sub(16)?; + let mut size = usize::from(Bits::new(data, size_at, flag).raw_short()?); + let mut start = size_at; + if size & 0x8000 != 0 { + let high_at = size_at.checked_sub(16)?; + let high = usize::from(Bits::new(data, high_at, size_at).raw_short()?); + size = (size & 0x7FFF) | (high << 15); + start = high_at; + } + Some((start.checked_sub(size)?, start)) +} + +struct Reader<'a> { + main: Bits<'a>, + strings: Bits<'a>, + handles: Bits<'a>, + own: u64, +} + +impl Reader<'_> { + fn body(&mut self, class: &str) -> Option { + Some(match class { + "BDMDBCONSTRAINTMANAGER" => { + let mut counts = [0; 5]; + for count in &mut counts { + *count = self.main.bit_long()?; + } + // Only the objects and child managers are understood. + if counts[2] != 0 || counts[4] != 0 { + return None; + } + let children = + usize::try_from(counts[1]).ok()? + usize::try_from(counts[3]).ok()?; + if children > self.handles.end { + return None; + } + let children = (0..children) + .map(|_| self.reference()) + .collect::>>()?; + Body::ConstraintManager { + counts, + children, + settings: self.properties()?, + } + } + "BDMOBJECT" => Body::Object { + lead: self.main.byte()?, + lead_count: self.main.bit_long()?, + entity: self.reference()?, + properties: self.properties()?, + tail: self.main.bit_long()?, + }, + "BDMDBOBJECTDEPENDENCY" => Body::Dependency { + properties: self.properties()?, + tail: self.main.bit_long()?, + entity: self.reference()?, + }, + _ => Body::Properties(self.properties()?), + }) + } + + fn reference(&mut self) -> Option { + let (code, handle) = self.handles.handle(self.own)?; + Some(Ref::new(Handle::from(handle), code)) + } + + fn properties(&mut self) -> Option { + let count = self.count()?; + let mut properties = Vec::with_capacity(count.min(64)); + for _ in 0..count { + let name = self.text()?; + let kind = self.main.byte()?; + properties.push((name, self.value(kind, 0)?)); + } + Some(Properties(properties)) + } + + fn value(&mut self, kind: u8, depth: u8) -> Option { + // Lists and maps nest a level or two; a deeper one is not a property + // list. + if depth > 4 { + return None; + } + Some(match kind { + 2 => Value::Text(self.text()?), + 3 => Value::Integer(self.main.bit_long()?), + 4 => Value::Real(self.main.bit_double()?), + 5 => Value::Flag(self.main.bit()?), + 6 => Value::Byte(self.main.byte()?), + 7 => { + let length = self.main.byte()?; + Value::Raw( + (0..length) + .map(|_| self.main.byte()) + .collect::>()?, + ) + } + 8 => Value::Object { + kind: self.main.byte()?, + target: self.reference()?, + }, + 9 => { + let element = self.main.byte()?; + let count = self.count()?; + Value::List { + element, + items: (0..count) + .map(|_| self.value(element, depth + 1)) + .collect::>()?, + } + } + 10 => { + let key = self.main.byte()?; + let value = self.main.byte()?; + let count = self.count()?; + Value::Map { + key, + value, + entries: (0..count) + .map(|_| Some((self.value(key, depth + 1)?, self.value(value, depth + 1)?))) + .collect::>()?, + } + } + _ => return None, + }) + } + + /// An element count. Every element takes at least one bit of one of the + /// streams, so a count beyond the record's bits is not one. + fn count(&mut self) -> Option { + let count = usize::try_from(self.main.bit_long()?).ok()?; + (count <= self.main.data.len() * 8).then_some(count) + } + + /// A string from the string stream: a length, then UTF-16 code units. + fn text(&mut self) -> Option { + let length = usize::try_from(self.strings.bit_short()?).ok()?; + if length * 16 > self.strings.end - self.strings.pos { + return None; + } + let units: Vec = (0..length) + .map(|_| self.strings.raw_short()) + .collect::>()?; + Some(String::from_utf16_lossy(&units)) + } +} + +struct Encoder { + main: Writer, + strings: Writer, + handles: Writer, + own: u64, +} + +impl Encoder { + fn body(&mut self, body: &Body) { + match body { + Body::Properties(properties) => self.properties(properties), + Body::ConstraintManager { + counts, + children, + settings, + } => { + for count in counts { + self.main.bit_long(*count); + } + for child in children { + self.handles.reference(*child, self.own); + } + self.properties(settings); + } + Body::Object { + lead, + lead_count, + entity, + properties, + tail, + } => { + self.main.byte(*lead); + self.main.bit_long(*lead_count); + self.handles.reference(*entity, self.own); + self.properties(properties); + self.main.bit_long(*tail); + } + Body::Dependency { + properties, + tail, + entity, + } => { + self.properties(properties); + self.main.bit_long(*tail); + self.handles.reference(*entity, self.own); + } + } + } + + fn properties(&mut self, properties: &Properties) { + self.main.bit_long(properties.0.len() as i32); + for (name, value) in &properties.0 { + self.text(name); + self.main.byte(value.kind()); + self.value(value); + } + } + + fn value(&mut self, value: &Value) { + match value { + Value::Text(text) => self.text(text), + Value::Integer(integer) => self.main.bit_long(*integer), + Value::Real(real) => self.main.bit_double(*real), + Value::Flag(flag) => self.main.bit(*flag), + Value::Byte(byte) => self.main.byte(*byte), + Value::Raw(bytes) => { + self.main.byte(bytes.len() as u8); + for byte in bytes { + self.main.byte(*byte); + } + } + Value::Object { kind, target } => { + self.main.byte(*kind); + self.handles.reference(*target, self.own); + } + Value::List { element, items } => { + self.main.byte(*element); + self.main.bit_long(items.len() as i32); + for item in items { + self.value(item); + } + } + Value::Map { + key, + value, + entries, + } => { + self.main.byte(*key); + self.main.byte(*value); + self.main.bit_long(entries.len() as i32); + for (key, value) in entries { + self.value(key); + self.value(value); + } + } + } + } + + fn text(&mut self, text: &str) { + let units: Vec = text.encode_utf16().collect(); + self.strings.bit_short(units.len() as i16); + for unit in units { + self.strings.raw_short(unit); + } + } +} + +/// A bit range of a record, read most significant bit first. +pub(super) struct Bits<'a> { + data: &'a [u8], + pos: usize, + end: usize, +} + +impl<'a> Bits<'a> { + fn new(data: &'a [u8], pos: usize, end: usize) -> Self { + Self { + data, + pos, + end: end.min(data.len() * 8), + } + } + + fn bit(&mut self) -> Option { + if self.pos >= self.end { + return None; + } + let bit = self.data[self.pos / 8] >> (7 - self.pos % 8) & 1; + self.pos += 1; + Some(bit == 1) + } + + fn bits(&mut self, count: u32) -> Option { + (0..count).try_fold(0, |value, _| Some(value << 1 | u32::from(self.bit()?))) + } + + fn byte(&mut self) -> Option { + self.bits(8).map(|value| value as u8) + } + + fn raw_short(&mut self) -> Option { + Some(u16::from_le_bytes([self.byte()?, self.byte()?])) + } + + fn raw_long(&mut self) -> Option { + Some(u32::from_le_bytes([ + self.byte()?, + self.byte()?, + self.byte()?, + self.byte()?, + ])) + } + + fn bit_short(&mut self) -> Option { + Some(match self.bits(2)? { + 0 => self.raw_short()? as i16, + 1 => i16::from(self.byte()?), + 2 => 0, + _ => 256, + }) + } + + fn bit_long(&mut self) -> Option { + match self.bits(2)? { + 0 => Some(self.raw_long()? as i32), + 1 => Some(i32::from(self.byte()?)), + 2 => Some(0), + _ => None, + } + } + + fn bit_double(&mut self) -> Option { + match self.bits(2)? { + 0 => { + let mut bytes = [0; 8]; + for byte in &mut bytes { + *byte = self.byte()?; + } + Some(f64::from_le_bytes(bytes)) + } + 1 => Some(1.0), + 2 => Some(0.0), + _ => None, + } + } + + /// The object type of a DWG 2010 or later record. + fn object_type(&mut self) -> Option { + match self.bits(2)? { + 0 => self.byte().map(u16::from), + 1 => self.byte().map(|byte| 0x1F0 + u16::from(byte)), + _ => self.raw_short(), + } + } + + /// A handle reference as its code and the handle; the offset forms count + /// from `reference`. + fn handle(&mut self, reference: u64) -> Option<(u8, u64)> { + let form = self.byte()?; + let mut value = 0u64; + for _ in 0..form & 0x0F { + value = value << 8 | u64::from(self.byte()?); + } + let code = form >> 4; + let handle = match code { + 0x6 => reference.checked_add(1)?, + 0x8 => reference.checked_sub(1)?, + 0xA => reference.checked_add(value)?, + 0xC => reference.checked_sub(value)?, + _ => value, + }; + Some((code, handle)) + } +} + +/// The bits of a record being written, most significant bit first. +#[derive(Default)] +struct Writer { + bytes: Vec, + len: usize, +} + +impl Writer { + fn bit(&mut self, bit: bool) { + if self.len.is_multiple_of(8) { + self.bytes.push(0); + } + if bit { + let last = self.bytes.len() - 1; + self.bytes[last] |= 0x80 >> (self.len % 8); + } + self.len += 1; + } + + fn bits(&mut self, value: u32, count: u32) { + for shift in (0..count).rev() { + self.bit(value >> shift & 1 == 1); + } + } + + fn byte(&mut self, byte: u8) { + self.bits(u32::from(byte), 8); + } + + fn raw_short(&mut self, value: u16) { + for byte in value.to_le_bytes() { + self.byte(byte); + } + } + + fn bit_short(&mut self, value: i16) { + match value { + 0 => self.bits(2, 2), + 256 => self.bits(3, 2), + 1..=255 => { + self.bits(1, 2); + self.byte(value as u8); + } + _ => { + self.bits(0, 2); + self.raw_short(value as u16); + } + } + } + + fn bit_long(&mut self, value: i32) { + match value { + 0 => self.bits(2, 2), + 1..=255 => { + self.bits(1, 2); + self.byte(value as u8); + } + _ => { + self.bits(0, 2); + for byte in value.to_le_bytes() { + self.byte(byte); + } + } + } + } + + fn bit_double(&mut self, value: f64) { + if value.to_bits() == 1.0f64.to_bits() { + self.bits(1, 2); + } else if value.to_bits() == 0.0f64.to_bits() { + self.bits(2, 2); + } else { + self.bits(0, 2); + for byte in value.to_le_bytes() { + self.byte(byte); + } + } + } + + fn object_type(&mut self, value: u16) { + if value <= 0xFF { + self.bits(0, 2); + self.byte(value as u8); + } else if (0x1F0..=0x2EF).contains(&value) { + self.bits(1, 2); + self.byte((value - 0x1F0) as u8); + } else { + self.bits(2, 2); + self.raw_short(value); + } + } + + /// A handle with `code`; an offset form is recomputed from `own`, and + /// falls back to the matching other offset form when the handle moved. + fn handle(&mut self, code: u8, handle: u64, own: u64) { + let (code, value) = match code { + 0x6 | 0x8 | 0xA | 0xC => { + let difference = i128::from(handle) - i128::from(own); + match (code, difference) { + (0x6, 1) => (0x6, 0), + (0x8, -1) => (0x8, 0), + (_, difference) if difference > 0 => (0xA, difference as u64), + (_, difference) if difference < 0 => (0xC, difference.unsigned_abs() as u64), + _ => (0x4, handle), + } + } + code => (code, handle), + }; + let bytes: Vec = value + .to_be_bytes() + .into_iter() + .skip_while(|byte| *byte == 0) + .collect(); + self.byte(code << 4 | bytes.len() as u8); + for byte in bytes { + self.byte(byte); + } + } + + fn reference(&mut self, reference: Ref, own: u64) { + self.handle(reference.code, reference.handle.value(), own); + } + + fn append(&mut self, other: &Writer) { + for index in 0..other.len { + self.bit(other.bytes[index / 8] >> (7 - index % 8) & 1 == 1); + } + } + + fn into_bytes(self) -> Vec { + self.bytes + } +} diff --git a/src/scene/bricscad_parameters/record_tests.rs b/src/scene/bricscad_parameters/record_tests.rs new file mode 100644 index 0000000000..edad3ca260 --- /dev/null +++ b/src/scene/bricscad_parameters/record_tests.rs @@ -0,0 +1,117 @@ +use super::record::{decode, encode, Body, Ref, Value}; +use super::*; + +/// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README). +fn fixture() -> Document { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/bricscad/visibility-states.dwg" + ); + let bytes = std::fs::read(path).expect("read the fixture"); + crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes) + .expect("open the fixture") +} + +/// Every BricsCAD object of `document` with its class, record bytes, handle +/// stream bits and version. +fn bricscad_records( + document: &Document, +) -> Vec<(Handle, String, Vec, i64, document::DxfVersion)> { + let mut records: Vec<_> = document + .objects + .iter() + .filter_map(|(handle, object)| match object { + ObjectType::Unknown { + type_name, + raw_dwg_data: Some(data), + raw_dwg_handle_bits, + raw_dwg_version: Some(version), + .. + } if type_name.to_ascii_uppercase().starts_with("BDM") => Some(( + *handle, + type_name.clone(), + data.clone(), + *raw_dwg_handle_bits, + *version, + )), + _ => None, + }) + .collect(); + records.sort_by_key(|record| record.0); + records +} + +#[test] +fn every_bricscad_record_encodes_to_the_bits_it_was_read_from() { + let document = fixture(); + let records = bricscad_records(&document); + assert_eq!(records.len(), 87, "the fixture's BricsCAD objects"); + for (handle, class, data, handle_bits, version) in records { + let record = decode(&class, &data, handle_bits, version) + .unwrap_or_else(|| panic!("{class} {handle:?} does not decode")); + assert_eq!(record.handle, handle, "{class}"); + assert_eq!( + encode(&record), + (data, handle_bits), + "{class} {handle:?} encodes to other bits" + ); + } +} + +#[test] +fn the_three_classes_around_a_property_list_decode_to_their_parts() { + let document = fixture(); + let manager = record(&document, Handle::from(0x1A5u64)).unwrap(); + let Body::ConstraintManager { + counts, children, .. + } = &manager.body + else { + panic!("{:?}", manager.body); + }; + assert_eq!(*counts, [2, 2, 0, 0, 0]); + assert_eq!( + children + .iter() + .map(|child| child.handle) + .collect::>(), + [Handle::from(0x1A6u64), Handle::from(0x1E1u64)] + ); + let object = record(&document, Handle::from(0x1A6u64)).unwrap(); + let Body::Object { + entity, properties, .. + } = &object.body + else { + panic!("{:?}", object.body); + }; + assert_eq!( + entity.handle, + Handle::from(0x146u64), + "the reference it stands for" + ); + assert_eq!(properties.text("NAME"), Some("Objekt_1")); + let dependency = record(&document, Handle::from(0x1A7u64)).unwrap(); + let Body::Dependency { entity, .. } = &dependency.body else { + panic!("{:?}", dependency.body); + }; + assert_eq!(entity.handle, Handle::from(0x146u64)); +} + +#[test] +fn a_changed_record_reads_back_as_changed() { + let document = fixture(); + let mut feature = record(&document, Handle::from(0x1C7u64)).unwrap(); + assert_eq!(feature.body.properties().text("LastKeyValue"), Some("Off")); + // Longer text, a new handle further away and every reference moved: the + // offset forms are recomputed from the new handle. + feature.body.properties_mut().set( + "LastKeyValue", + Value::Text("A much longer state name".into()), + ); + feature.handle = Handle::from(0x12_3456u64); + feature.refs_mut(|reference: &mut Ref| { + reference.handle = Handle::from(reference.handle.value() + 0x1000); + }); + let (data, handle_bits) = encode(&feature); + let read = decode("BDMDBFEATUREDATA", &data, handle_bits, feature.version).unwrap(); + assert_eq!(read, feature); +} diff --git a/src/scene/bricscad_parameters/switch.rs b/src/scene/bricscad_parameters/switch.rs new file mode 100644 index 0000000000..0c29d8937b --- /dev/null +++ b/src/scene/bricscad_parameters/switch.rs @@ -0,0 +1,1288 @@ +//! Switching the visibility state a BricsCAD parametric block reference +//! shows, the way BricsCAD does it, so that BricsCAD keeps the block's +//! parameters. +//! +//! A reference shows the block itself or an anonymous copy of it, and +//! BricsCAD reads the states a reference shows from the parameter objects of +//! that copy. When a state is changed in BricsCAD, it starts from the states +//! the reference's entry in model space lists: a `BmAssemblyParameters` +//! feature, linked to the reference through a `BDMOBJECT` and a dependency, +//! that lists every parameter the reference was ever set to with the state it +//! shows. BricsCAD shares a copy between references that show the same +//! states. +//! +//! Switching here: +//! 1. works out the states the reference is to show and the parameters its +//! entry lists; +//! 2. points the reference at the block when those are the block's own states, +//! at a copy of the block that shows them when there is one, or at a new +//! copy: the block's members and all its parameter objects cloned under new +//! handles, with the states set as BricsCAD sets them; +//! 3. moves the reference's attributes on or off `*SUPPRESS` with their +//! definitions in the block it now shows; +//! 4. writes the reference's entry in model space, creating it, and model +//! space's own parameter objects when there are none. + +use std::collections::{BTreeMap, BTreeSet}; + +use document::objects::{ + AssocAction, AssocDependency, AssocEvalValue, AssocEvalVariant, AssociativeData, + AssociativeObject, ObjectType, +}; +use document::{Document, EntityType, Handle}; +use rustc_hash::{FxHashMap, FxHashSet}; + +use super::record::{self, Body, Properties, Record, Ref, Value}; +use super::{ + database_entry, features, original_block, record as read_record, shown_block, + visibility_parameters, +}; +use crate::scene::Scene; + +/// The layer BricsCAD moves the members a state hides to. +const SUPPRESS_LAYER: &str = "*SUPPRESS"; + +const UNSUPPORTED: &str = "This BricsCAD parametric block cannot be switched here."; +const NOT_IN_MODEL_SPACE: &str = "Only a BricsCAD block reference in model space can be switched."; +const NO_SUCH_STATE: &str = "The block has no such visibility state."; + +type Result = std::result::Result; + +/// Whether [`Scene::set_bricscad_visibility`] can switch `insert`: a +/// reference in model space to a BricsCAD parametric block, or to a copy of +/// one, whose parameter objects read. +pub(crate) fn can_switch(document: &Document, insert: Handle) -> bool { + document.get_entity(insert).is_some_and(|entity| { + entity.common().owner_handle == document.header.model_space_block_handle + }) && super::master_block(document, insert).is_some() +} + +impl Scene { + /// Show `state` of the visibility parameter `parameter` on the reference + /// `insert`, as BricsCAD does. `Ok(false)` when the reference shows it + /// already. On an error the document is left as it was only when the + /// caller works on a copy of it; the property and automation paths do. + pub(crate) fn set_bricscad_visibility( + &mut self, + insert: Handle, + parameter: &str, + state: &str, + ) -> Result { + let document = &self.document; + if !can_switch(document, insert) { + return Err(NOT_IN_MODEL_SPACE); + } + let shown = shown_block(document, insert).ok_or(UNSUPPORTED)?; + let master = original_block(document, shown).unwrap_or(shown); + let master_parameters = visibility_parameters(document, master); + let shown_parameters = visibility_parameters(document, shown); + let names: Vec<&str> = master_parameters.iter().map(|p| p.name.as_str()).collect(); + if names.is_empty() + || shown_parameters + .iter() + .map(|p| p.name.as_str()) + .ne(names.iter().copied()) + { + return Err(UNSUPPORTED); + } + let index = names + .iter() + .position(|name| *name == parameter) + .ok_or(NO_SUCH_STATE)?; + if !master_parameters[index].states.iter().any(|s| s == state) { + return Err(NO_SUCH_STATE); + } + let shown_state = |parameters: &[super::VisibilityParameter]| -> Result> { + parameters + .iter() + .map(|p| { + p.current + .and_then(|current| p.states.get(current).cloned()) + .ok_or(UNSUPPORTED) + }) + .collect() + }; + let defaults = shown_state(&master_parameters)?; + let current = shown_state(&shown_parameters)?; + if current[index] == state { + return Ok(false); + } + let mut target = current.clone(); + target[index] = state.to_string(); + + // The entry lists what it listed, what differs from the block, and + // the parameter set now, each in the state it shows. + let entry = find_entry(document, insert); + let mut listed: BTreeSet = entry + .as_ref() + .and_then(|(_, record)| record.body.properties().get("expr.const")) + .and_then(Value::entries) + .map(|entries| { + entries + .iter() + .filter_map(|(key, _)| key.text().map(str::to_string)) + .filter(|key| names.contains(&key.as_str())) + .collect() + }) + .unwrap_or_default(); + for (k, name) in names.iter().enumerate() { + if current[k] != defaults[k] { + listed.insert(name.to_string()); + } + } + listed.insert(parameter.to_string()); + let overrides: Vec<(String, String)> = listed + .iter() + .map(|name| { + let k = names.iter().position(|n| n == name).unwrap_or(index); + (name.clone(), target[k].clone()) + }) + .collect(); + let names: Vec = names.iter().map(|name| name.to_string()).collect(); + + let block = if target == defaults { + master + } else if let Some(copy) = find_copy(&self.document, master, &target) { + copy + } else { + let states: BTreeMap = + names.iter().cloned().zip(target.iter().cloned()).collect(); + self.clone_parametric_copy(master, &states, &listed)? + }; + if block != shown { + let name = self + .document + .block_records + .iter() + .find(|record| record.handle == block) + .map(|record| record.name.clone()) + .ok_or(UNSUPPORTED)?; + self.repoint_representation(insert, shown, block, &name); + follow_attribute_definitions(&mut self.document, insert, block); + } + write_entry(&mut self.document, insert, master, overrides)?; + Ok(true) + } + + /// A new anonymous copy of the BricsCAD parametric block `master` showing + /// `states`, with the parameters in `listed` set on it: the members and + /// every object under the block's extension dictionary cloned under new + /// handles, then the states applied. + pub(super) fn clone_parametric_copy( + &mut self, + master: Handle, + states: &BTreeMap, + listed: &BTreeSet, + ) -> Result { + let document = &self.document; + let master_dictionary = document + .extension_dictionary_handle(master) + .ok_or(UNSUPPORTED)?; + let objects = owned_tree(document, master_dictionary)?; + let records: FxHashMap = objects + .iter() + .filter(|handle| { + matches!( + document.objects.get(handle), + Some(ObjectType::Unknown { .. }) + ) + }) + .map(|handle| Some((*handle, read_record(document, *handle)?))) + .collect::>() + .ok_or(UNSUPPORTED)?; + let tag = block_tag(document, master); + let master_record = document + .block_records + .iter() + .find(|record| record.handle == master) + .ok_or(UNSUPPORTED)?; + let master_name = master_record.name.clone(); + let master_members = crate::scene::block_authoring::members(document, master); + let entities: Vec = master_members + .iter() + .map(|handle| document.get_entity(*handle).cloned()) + .collect::>() + .ok_or(UNSUPPORTED)?; + let layers: Vec = entities + .iter() + .map(|entity| entity.common().layer.clone()) + .collect(); + let base = crate::scene::render_graph::block_base_point(document, &master_name); + let name = next_anonymous_name(document); + + self.define_block_raw_unbumped(&name, base, entities); + let record = self + .document + .block_records + .get_mut(&name) + .ok_or(UNSUPPORTED)?; + record.flags.anonymous = true; + let copy = record.handle; + let copy_members = crate::scene::block_authoring::members(&self.document, copy); + if copy_members.len() != master_members.len() { + return Err(UNSUPPORTED); + } + self.own_copied_xdicts(master_members.clone(), copy_members.clone()); + + let document = &mut self.document; + // A block BricsCAD never copied has no tag yet; BricsCAD gives it one + // when it makes the first copy. + let tag = match tag { + Some(tag) => tag, + None => give_block_tag(document, master), + }; + let copy_dictionary = document.ensure_extension_dictionary(copy); + let mut cloned: FxHashMap = FxHashMap::default(); + for &handle in &objects { + let new = if handle == master_dictionary { + copy_dictionary + } else { + document.allocate_handle() + }; + cloned.insert(handle, new); + } + let members: FxHashMap = master_members + .iter() + .copied() + .zip(copy_members.iter().copied()) + .collect(); + let remap = |handle: Handle| { + if handle == master { + copy + } else { + cloned + .get(&handle) + .or_else(|| members.get(&handle)) + .copied() + .unwrap_or(handle) + } + }; + let mut clones = Vec::with_capacity(objects.len()); + for &handle in &objects { + let new = remap(handle); + let clone = match document.objects.get(&handle).ok_or(UNSUPPORTED)? { + ObjectType::Dictionary(dictionary) => { + let mut dictionary = dictionary.clone(); + dictionary.handle = new; + dictionary.owner = remap(dictionary.owner); + for (_, entry) in &mut dictionary.entries { + *entry = remap(*entry); + } + for reactor in &mut dictionary.reactors { + *reactor = remap(*reactor); + } + dictionary.xdictionary_handle = dictionary.xdictionary_handle.map(remap); + ObjectType::Dictionary(dictionary) + } + ObjectType::Associative(object) => { + let mut object = object.clone(); + remap_associative(&mut object, &remap)?; + ObjectType::Associative(object) + } + // The block's draw order, member by member. + ObjectType::SortEntitiesTable(table) => { + let mut order = document::objects::SortEntitiesTable::for_block(copy); + order.handle = new; + order.owner_handle = remap(table.owner_handle); + for entry in table.entries() { + order.add_entry(remap(entry.entity_handle), remap(entry.sort_handle)); + } + ObjectType::SortEntitiesTable(order) + } + ObjectType::Unknown { type_name, .. } => { + let mut record = records[&handle].clone(); + record.handle = new; + record.refs_mut(|reference| reference.handle = remap(reference.handle)); + unknown(type_name, &record) + } + _ => return Err(UNSUPPORTED), + }; + clones.push((new, clone)); + } + for (handle, object) in clones { + document.objects.insert(handle, object); + } + // The copies' reactors name the clones of the master members' + // parameter objects; anything else they named stays with the master. + for (original, copy_member) in master_members.iter().zip(©_members) { + let reactors: Vec = document + .get_entity(*original) + .map(|entity| { + entity + .common() + .reactors + .iter() + .filter_map(|reactor| cloned.get(reactor).copied()) + .collect() + }) + .unwrap_or_default(); + if let Some(entity) = document.get_entity_mut(*copy_member) { + entity.common_mut().reactors = reactors; + } + } + + // The copy names the block it was made from, member by member. + let manager = database_entry(document, copy, "PERSIDMANAGER").ok_or(UNSUPPORTED)?; + let mut record = read_record(document, manager).ok_or(UNSUPPORTED)?; + let properties = record.body.properties_mut(); + properties + .0 + .retain(|(name, _)| !name.starts_with("original.")); + properties.0.push(( + "original.block".into(), + Value::Object { + kind: 1, + target: Ref::new(master, 5), + }, + )); + properties.0.push(( + "original.map".into(), + Value::Map { + key: 7, + value: 8, + entries: master_members + .iter() + .zip(©_members) + .map(|(original, member)| { + ( + Value::Raw(handle_bytes(*original)), + Value::Object { + kind: 0, + target: Ref::new(*member, 4), + }, + ) + }) + .collect(), + }, + )); + properties.0.push(("original.tag".into(), Value::Text(tag))); + store(document, &record); + + let layers: FxHashMap = copy_members.iter().copied().zip(layers).collect(); + apply_states(document, copy, ©_members, &layers, states, listed)?; + Ok(copy) + } +} + +/// Every object owned, directly or further down, by `root`, root first. +fn owned_tree(document: &Document, root: Handle) -> Result> { + let mut children: FxHashMap> = FxHashMap::default(); + for &handle in document.objects.keys() { + if let Some(owner) = document.object_owner(handle) { + children.entry(owner).or_default().push(handle); + } + } + let mut seen = FxHashSet::default(); + let mut order = Vec::new(); + let mut stack = vec![root]; + while let Some(handle) = stack.pop() { + if handle.is_null() || !seen.insert(handle) { + continue; + } + match document.objects.get(&handle) { + Some( + ObjectType::Dictionary(_) + | ObjectType::Unknown { .. } + | ObjectType::SortEntitiesTable(_), + ) => {} + Some(ObjectType::Associative(AssociativeObject { + data: + AssociativeData::Network(_) + | AssociativeData::Variable(_) + | AssociativeData::ValueDependency(_), + .. + })) => {} + _ => return Err(UNSUPPORTED), + } + order.push(handle); + if let Some(owned) = children.get(&handle) { + let mut owned = owned.clone(); + owned.sort_unstable_by_key(|handle| std::cmp::Reverse(*handle)); + stack.extend(owned); + } + } + Ok(order) +} + +/// Point every handle of an associative network, variable or value dependency +/// through `remap`. +fn remap_associative( + object: &mut AssociativeObject, + remap: &impl Fn(Handle) -> Handle, +) -> Result<()> { + object.handle = remap(object.handle); + object.owner = remap(object.owner); + for reactor in &mut object.reactors { + *reactor = remap(*reactor); + } + object.xdictionary_handle = object.xdictionary_handle.map(remap); + let action = |action: &mut AssocAction| { + action.owning_network = remap(action.owning_network); + action.action_body = remap(action.action_body); + for dependency in &mut action.dependencies { + dependency.dependency = remap(dependency.dependency); + } + for parameter in &mut action.owned_parameters { + *parameter = remap(*parameter); + } + for value in &mut action.values { + value.controlled_object_dependency = remap(value.controlled_object_dependency); + for variable in &mut value.variables { + variable.handle = remap(variable.handle); + if let AssocEvalValue::Handle(handle) = &mut variable.value.value { + *handle = remap(*handle); + } + } + } + }; + let dependency = |dependency: &mut AssocDependency| { + dependency.dependent_on = remap(dependency.dependent_on); + dependency.read_dependency = remap(dependency.read_dependency); + dependency.node = remap(dependency.node); + dependency.dependency_body = remap(dependency.dependency_body); + }; + match &mut object.data { + AssociativeData::Network(network) => { + action(&mut network.action); + for child in &mut network.actions { + child.dependency = remap(child.dependency); + } + for owned in &mut network.owned_actions { + *owned = remap(*owned); + } + } + AssociativeData::Variable(variable) => { + action(&mut variable.action); + for owned in &mut variable.dependencies { + owned.dependency = remap(owned.dependency); + } + if let AssocEvalValue::Handle(handle) = &mut variable.value.value { + *handle = remap(*handle); + } + } + AssociativeData::ValueDependency(value) => { + dependency(&mut value.dependency); + if let AssocEvalValue::Handle(handle) = &mut value.value.value { + *handle = remap(*handle); + } + } + _ => return Err(UNSUPPORTED), + } + Ok(()) +} + +/// Set the copy's parameter objects, associative variables and member layers +/// to `states`, as BricsCAD leaves a copy it made: for each visibility +/// parameter the state, the values of its table's columns and, for a +/// parameter in `listed`, the marks BricsCAD sets on an instance's own +/// parameter; for each suppression its value, status and the layers of the +/// members it moved to `*SUPPRESS`. +fn apply_states( + document: &mut Document, + copy: Handle, + members: &[Handle], + layers: &FxHashMap, + states: &BTreeMap, + listed: &BTreeSet, +) -> Result<()> { + let features = features(document, copy); + let mut columns: FxHashMap = FxHashMap::default(); + let mut suppressions = Vec::new(); + for &feature in &features { + let mut record = read_record(document, feature).ok_or(UNSUPPORTED)?; + let properties = record.body.properties(); + match properties.text("Feature_type") { + Some("BdmConfigurationFeature") + if properties.text("TableType") == Some("VisibilityStates") => {} + Some("BdmSuppressFeature") => { + suppressions.push(feature); + continue; + } + _ => continue, + } + let table = super::properties( + document, + properties + .get("ConfigTable") + .and_then(Value::object) + .ok_or(UNSUPPORTED)?, + ) + .ok_or(UNSUPPORTED)?; + let name = table + .text("KeyName") + .or_else(|| properties.text("Name")) + .ok_or(UNSUPPORTED)? + .to_string(); + let state = states.get(&name).ok_or(UNSUPPORTED)?; + let texts = |key: &str| -> Option> { + table.get(key)?.items()?.iter().map(Value::text).collect() + }; + let keys = texts("KeyValues").ok_or(UNSUPPORTED)?; + let column_names = texts("ColNames").ok_or(UNSUPPORTED)?; + let values: Vec = table + .get("DblValues") + .and_then(Value::items) + .and_then(|items| { + items + .iter() + .map(|item| match item { + Value::Real(value) => Some(*value), + _ => None, + }) + .collect() + }) + .ok_or(UNSUPPORTED)?; + let row = keys + .iter() + .position(|key| key == state) + .ok_or(NO_SUCH_STATE)?; + let own = listed.contains(&name); + let reactors: Vec = properties + .get("Reactors") + .and_then(Value::items) + .map(|items| items.iter().filter_map(Value::object).collect()) + .unwrap_or_default(); + record + .body + .properties_mut() + .set("LastKeyValue", Value::Text(state.clone())); + store(document, &record); + + for reactor in reactors { + let mut variable_reactor = read_record(document, reactor).ok_or(UNSUPPORTED)?; + let properties = variable_reactor.body.properties_mut(); + let variable = properties + .get("VarId") + .and_then(Value::object) + .ok_or(UNSUPPORTED)?; + if properties.get("IsKeyVar") == Some(&Value::Flag(true)) { + properties.set("String", Value::Text(state.clone())); + properties.set("IsEnabled", Value::Flag(!own)); + if own { + properties.set("Value", Value::Real(row as f64)); + set_variable( + document, + variable, + Some(row.to_string()), + AssocEvalVariant { + code: 90, + value: AssocEvalValue::Long(row as i32), + }, + )?; + } + } else { + let column_name = properties.text("VarName").ok_or(UNSUPPORTED)?.to_string(); + let column = column_names + .iter() + .position(|name| *name == column_name) + .ok_or(UNSUPPORTED)?; + let value = *values + .get(row * column_names.len() + column) + .ok_or(UNSUPPORTED)?; + properties.set("Value", Value::Real(value)); + set_variable( + document, + variable, + None, + AssocEvalVariant { + code: 40, + value: AssocEvalValue::Real(value), + }, + )?; + columns.insert(column_name, value); + } + store(document, &variable_reactor); + } + } + + let order: FxHashMap = + members.iter().enumerate().map(|(k, h)| (*h, k)).collect(); + let mut suppressed: FxHashSet = FxHashSet::default(); + let layer_handle = + |document: &Document, name: &str| document.layers.get(name).map(|layer| layer.handle); + for feature in suppressions { + let mut record = read_record(document, feature).ok_or(UNSUPPORTED)?; + let reactors: Vec = record + .body + .properties() + .get("Reactors") + .and_then(Value::items) + .map(|items| items.iter().filter_map(Value::object).collect()) + .unwrap_or_default(); + let mut entities = Vec::new(); + let mut value = None; + for reactor in reactors { + let mut reactor_record = read_record(document, reactor).ok_or(UNSUPPORTED)?; + let properties = reactor_record.body.properties(); + if let Some(dependencies) = properties.get("pers_ids").and_then(Value::items) { + for dependency in dependencies.iter().filter_map(Value::object) { + match read_record(document, dependency).map(|record| record.body) { + Some(Body::Dependency { entity, .. }) => entities.push(entity.handle), + _ => return Err(UNSUPPORTED), + } + } + } else if let Some(variable) = properties.get("var").and_then(Value::object) { + let expression = match document.objects.get(&variable) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + })) => variable.expression.clone(), + _ => return Err(UNSUPPORTED), + }; + let suppress = evaluate(&expression, &columns).ok_or(UNSUPPORTED)?; + reactor_record + .body + .properties_mut() + .set("value", Value::Real(suppress)); + store(document, &reactor_record); + set_variable( + document, + variable, + None, + AssocEvalVariant { + code: 90, + value: AssocEvalValue::Long(suppress as i32), + }, + )?; + value = Some(suppress); + } + } + let suppress = value.ok_or(UNSUPPORTED)? != 0.0; + entities.sort_by_key(|entity| order.get(entity).copied().unwrap_or(usize::MAX)); + let properties = record.body.properties_mut(); + properties.set("Status", Value::Integer(if suppress { 32 } else { 0 })); + let Some(Value::Map { entries, .. }) = properties.get_mut("aEntLayerKey") else { + return Err(UNSUPPORTED); + }; + entries.clear(); + if suppress { + for entity in &entities { + let layer = layers.get(entity).ok_or(UNSUPPORTED)?; + let layer = layer_handle(document, layer).ok_or(UNSUPPORTED)?; + entries.push(( + Value::Object { + kind: 0, + target: Ref::new(*entity, 4), + }, + Value::Object { + kind: 1, + target: Ref::new(layer, 5), + }, + )); + } + suppressed.extend(entities); + } + store(document, &record); + } + + if !suppressed.is_empty() { + ensure_suppress_layer(document); + } + for member in members { + let layer = if suppressed.contains(member) { + SUPPRESS_LAYER.to_string() + } else { + layers.get(member).cloned().ok_or(UNSUPPORTED)? + }; + if document + .get_entity(*member) + .is_some_and(|entity| entity.common().layer != layer) + { + if let Some(entity) = document.get_entity_mut(*member) { + entity.common_mut().layer = layer; + } + } + } + Ok(()) +} + +/// The value of a suppression's expression, such as `1 - look_3` or +/// `1 - look_13 * look_14`, over the table columns. +fn evaluate(expression: &str, columns: &FxHashMap) -> Option { + const RESULT: &str = "bricscad_suppression"; + let mut table = crate::scene::named_parameters::ParameterTable::new(); + for (name, value) in columns { + table.set(name, &value.to_string()).ok()?; + } + table.set(RESULT, expression).ok()?; + table.resolve(RESULT).ok().filter(|value| value.is_finite()) +} + +fn set_variable( + document: &mut Document, + variable: Handle, + expression: Option, + value: AssocEvalVariant, +) -> Result<()> { + let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + })) = document.objects.get_mut(&variable) + else { + return Err(UNSUPPORTED); + }; + if let Some(expression) = expression { + variable.expression = expression; + } + variable.value = value; + Ok(()) +} + +/// The layer BricsCAD keeps hidden members on: frozen and off. +fn ensure_suppress_layer(document: &mut Document) { + if document.layers.get(SUPPRESS_LAYER).is_some() { + return; + } + let mut layer = document::tables::Layer::new(SUPPRESS_LAYER); + layer.flags.frozen = true; + layer.flags.off = true; + layer.handle = document.allocate_handle(); + let _ = document.layers.add(layer); +} + +/// A copy of `master`, other than the block itself, that shows `states`. +fn find_copy(document: &Document, master: Handle, states: &[String]) -> Option { + document + .block_records + .iter() + .filter(|record| record.is_anonymous() && record.handle != master) + .filter(|record| original_block(document, record.handle) == Some(master)) + .find(|record| { + let parameters = visibility_parameters(document, record.handle); + parameters.len() == states.len() + && parameters.iter().zip(states).all(|(parameter, state)| { + parameter + .current + .and_then(|current| parameter.states.get(current)) + == Some(state) + }) + }) + .map(|record| record.handle) +} + +/// After the reference `insert` was pointed at `block`, an attribute whose +/// definition there is on `*SUPPRESS` goes there too, and one on `*SUPPRESS` +/// whose definition is not goes back to the definition's layer, as BricsCAD +/// keeps them. +fn follow_attribute_definitions(document: &mut Document, insert: Handle, block: Handle) { + let definitions: FxHashMap = + crate::scene::block_authoring::members(document, block) + .into_iter() + .filter_map(|member| match document.get_entity(member) { + Some(EntityType::AttributeDefinition(definition)) => Some(( + definition.tag.to_uppercase(), + definition.common.layer.clone(), + )), + _ => None, + }) + .collect(); + let needs = match document.get_entity(insert) { + Some(EntityType::Insert(reference)) => reference.attributes.iter().any(|attribute| { + target_layer(&definitions, &attribute.tag, &attribute.common.layer).is_some() + }), + _ => false, + }; + if !needs { + return; + } + if let Some(EntityType::Insert(reference)) = document.get_entity_mut(insert) { + for attribute in &mut reference.attributes { + if let Some(layer) = target_layer(&definitions, &attribute.tag, &attribute.common.layer) + { + attribute.common.layer = layer; + attribute.common.raw_record = None; + } + } + } +} + +fn target_layer(definitions: &FxHashMap, tag: &str, layer: &str) -> Option { + let definition = definitions.get(&tag.to_uppercase())?; + if definition == SUPPRESS_LAYER && layer != SUPPRESS_LAYER { + Some(SUPPRESS_LAYER.to_string()) + } else if definition != SUPPRESS_LAYER && layer == SUPPRESS_LAYER { + Some(definition.clone()) + } else { + None + } +} + +/// The reference's entry in model space: the `BmAssemblyParameters` feature +/// its `BDMOBJECT` leads to, with its record. +pub(super) fn find_entry(document: &Document, insert: Handle) -> Option<(Handle, Record)> { + let reactors = document.get_entity(insert)?.common().reactors.clone(); + reactors.into_iter().find_map(|reactor| { + let Body::Object { properties, .. } = read_record(document, reactor)?.body else { + return None; + }; + properties + .get("PersIdDependencies")? + .items()? + .iter() + .filter_map(Value::object) + .find_map(|dependency| { + read_record(document, dependency)? + .reactors + .iter() + .find_map(|reactor| { + let feature = read_record(document, reactor.handle)?.owner.handle; + let record = read_record(document, feature)?; + (record.body.properties().text("Feature_type") + == Some("BmAssemblyParameters")) + .then_some((feature, record)) + }) + }) + }) +} + +/// Write the reference's entry with `overrides`, creating it when there is +/// none. +fn write_entry( + document: &mut Document, + insert: Handle, + master: Handle, + overrides: Vec<(String, String)>, +) -> Result<()> { + let constants = |entries: Vec<(String, String)>| Value::Map { + key: 2, + value: 2, + entries: entries + .into_iter() + .map(|(name, state)| (Value::Text(name), Value::Text(state))) + .collect(), + }; + if let Some((_, mut record)) = find_entry(document, insert) { + if !record + .body + .properties_mut() + .set("expr.const", constants(overrides)) + { + return Err(UNSUPPORTED); + } + store(document, &record); + return Ok(()); + } + + let template = |class: &str| template_record(document, master, class).ok_or(UNSUPPORTED); + let feature_template = template("BDMDBFEATUREDATA")?; + let reactor_template = template("BDMDBPERSIDREACTOR")?; + let dependency_template = template("BDMDBOBJECTDEPENDENCY")?; + let object_template = template("BDMOBJECT")?; + let (feature_manager, dependency_manager, constraint_manager) = + model_database(document, master)?; + + let names: Vec = features(document, document.header.model_space_block_handle) + .into_iter() + .filter_map(|feature| { + super::properties(document, feature)? + .text("Name") + .map(str::to_string) + }) + .collect(); + let base = format!("*{:X}", insert.value()); + let name = std::iter::once(base.clone()) + .chain((1..).map(|n| format!("{base}_{n}"))) + .find(|name| !names.contains(name)) + .unwrap_or(base); + let mut constraint_record = read_record(document, constraint_manager).ok_or(UNSUPPORTED)?; + let object_number = match &constraint_record.body { + Body::ConstraintManager { + counts, children, .. + } => { + children + .iter() + .take(usize::try_from(counts[1]).unwrap_or(0)) + .filter_map(|child| match read_record(document, child.handle)?.body { + Body::Object { properties, .. } => properties + .text("NAME")? + .strip_prefix("Objekt_")? + .parse::() + .ok(), + _ => None, + }) + .max() + .unwrap_or(0) + + 1 + } + _ => return Err(UNSUPPORTED), + }; + + let [feature, reactor, dependency, object] = [(); 4].map(|_| document.allocate_handle()); + let object_lead = match &object_template.body { + Body::Object { + lead, + lead_count, + tail, + .. + } => (*lead, *lead_count, *tail), + _ => return Err(UNSUPPORTED), + }; + let new_records = [ + Record::like( + &feature_template, + feature, + Ref::new(feature_manager, 4), + Body::Properties(Properties(vec![ + ("_ver".into(), Value::Byte(1)), + ( + "Feature_type".into(), + Value::Text("BmAssemblyParameters".into()), + ), + ("Name".into(), Value::Text(name)), + ( + "Reactors".into(), + Value::List { + element: 8, + items: vec![Value::Object { + kind: 3, + target: Ref::new(reactor, 3), + }], + }, + ), + ("Status".into(), Value::Integer(0)), + ("expr.const".into(), constants(overrides)), + ("expr.orig".into(), constants(Vec::new())), + ( + "modifiedParams".into(), + Value::List { + element: 2, + items: Vec::new(), + }, + ), + ])), + ), + Record::like( + &reactor_template, + reactor, + Ref::new(feature, 4), + Body::Properties(Properties(vec![ + ("_ver".into(), Value::Byte(1)), + ("mask".into(), Value::Integer(1)), + ( + "pers_ids".into(), + Value::List { + element: 8, + items: vec![Value::Object { + kind: 0, + target: Ref::new(dependency, 4), + }], + }, + ), + ("tag".into(), Value::Integer(0)), + ])), + ), + { + let mut record = Record::like( + &dependency_template, + dependency, + Ref::new(dependency_manager, 4), + Body::Dependency { + properties: Properties::default(), + tail: 0, + entity: Ref::new(insert, 5), + }, + ); + record.reactors = vec![Ref::new(reactor, 4)]; + record + }, + Record::like( + &object_template, + object, + Ref::new(constraint_manager, 4), + Body::Object { + lead: object_lead.0, + lead_count: object_lead.1, + entity: Ref::new(insert, 4), + properties: Properties(vec![ + ( + "NAME".into(), + Value::Text(format!("Objekt_{object_number}")), + ), + ( + "PersIdDependencies".into(), + Value::List { + element: 8, + items: vec![Value::Object { + kind: 0, + target: Ref::new(dependency, 4), + }], + }, + ), + ]), + tail: object_lead.2, + }, + ), + ]; + let classes = [ + "BDMDBFEATUREDATA", + "BDMDBPERSIDREACTOR", + "BDMDBOBJECTDEPENDENCY", + "BDMOBJECT", + ]; + for (class, record) in classes.iter().zip(&new_records) { + document + .objects + .insert(record.handle, unknown(class, record)); + } + + append_object(document, feature_manager, "Features", feature)?; + append_object(document, dependency_manager, "deps", dependency)?; + let Body::ConstraintManager { + counts, children, .. + } = &mut constraint_record.body + else { + return Err(UNSUPPORTED); + }; + let at = usize::try_from(counts[1]).map_err(|_| UNSUPPORTED)?; + children.insert(at.min(children.len()), Ref::new(object, 3)); + counts[1] += 1; + store(document, &constraint_record); + if let Some(entity) = document.get_entity_mut(insert) { + entity.common_mut().reactors.push(object); + } + Ok(()) +} + +/// Append a reference to `target` to the list property `list` of `manager`. +fn append_object( + document: &mut Document, + manager: Handle, + list: &str, + target: Handle, +) -> Result<()> { + let mut record = read_record(document, manager).ok_or(UNSUPPORTED)?; + let Some(Value::List { items, .. }) = record.body.properties_mut().get_mut(list) else { + return Err(UNSUPPORTED); + }; + items.push(Value::Object { + kind: 3, + target: Ref::new(target, 3), + }); + store(document, &record); + Ok(()) +} + +/// Model space's feature manager, dependency manager and constraint manager, +/// created after those of `master` when model space has none yet. +fn model_database(document: &mut Document, master: Handle) -> Result<(Handle, Handle, Handle)> { + let model = document.header.model_space_block_handle; + let entries = |document: &Document, owner: Handle| { + Some(( + database_entry(document, owner, "FEATURE_MANAGER")?, + database_entry(document, owner, "PERSIDMANAGER")?, + database_entry(document, owner, "BDM_DATABASE")?, + )) + }; + if let Some(found) = entries(document, model) { + return Ok(found); + } + let model_dictionary = document.ensure_extension_dictionary(model); + let has_database = matches!( + document.objects.get(&model_dictionary), + Some(ObjectType::Dictionary(dictionary)) if dictionary.get("BDM_DATABASE").is_some() + ); + if has_database { + // A database without all three managers is not one this writes into. + return Err(UNSUPPORTED); + } + let master_dictionary = document + .extension_dictionary_handle(master) + .ok_or(UNSUPPORTED)?; + let (master_database, hard_owned) = match document.objects.get(&master_dictionary) { + Some(ObjectType::Dictionary(dictionary)) => ( + dictionary.get("BDM_DATABASE").ok_or(UNSUPPORTED)?, + dictionary + .hard_owner_entries + .iter() + .any(|key| key.eq_ignore_ascii_case("BDM_DATABASE")), + ), + _ => return Err(UNSUPPORTED), + }; + let Some(ObjectType::Dictionary(template)) = document.objects.get(&master_database).cloned() + else { + return Err(UNSUPPORTED); + }; + let (feature_template, dependency_template, constraint_template) = + entries(document, master).ok_or(UNSUPPORTED)?; + let database = document.allocate_handle(); + let mut created = Vec::new(); + let mut handles = FxHashMap::default(); + for (key, template_handle) in [ + ("FEATURE_MANAGER", feature_template), + ("PERSIDMANAGER", dependency_template), + ("BDM_DATABASE", constraint_template), + ] { + let mut record = read_record(document, template_handle).ok_or(UNSUPPORTED)?; + let handle = document.allocate_handle(); + record.handle = handle; + record.owner.handle = database; + for reactor in &mut record.reactors { + reactor.handle = database; + } + match &mut record.body { + Body::Properties(properties) => { + properties + .0 + .retain(|(name, _)| !name.starts_with("original.")); + for list in ["Features", "Contexts", "deps"] { + if let Some(Value::List { items, .. }) = properties.get_mut(list) { + items.clear(); + } + } + } + Body::ConstraintManager { + counts, children, .. + } => { + counts[1] = 0; + counts[3] = 0; + children.clear(); + } + _ => return Err(UNSUPPORTED), + } + let class = match key { + "FEATURE_MANAGER" => "BDMDBFEATUREMANAGER", + "PERSIDMANAGER" => "BdmDbPersIdManager", + _ => "BDMDBCONSTRAINTMANAGER", + }; + created.push((handle, unknown(class, &record))); + handles.insert(key, handle); + } + let mut dictionary = template; + dictionary.handle = database; + dictionary.owner = model_dictionary; + dictionary.reactors = vec![model_dictionary]; + dictionary.xdictionary_handle = None; + for (key, entry) in &mut dictionary.entries { + *entry = *handles.get(key.as_str()).ok_or(UNSUPPORTED)?; + } + document + .objects + .insert(database, ObjectType::Dictionary(dictionary)); + for (handle, object) in created { + document.objects.insert(handle, object); + } + if let Some(ObjectType::Dictionary(dictionary)) = document.objects.get_mut(&model_dictionary) { + dictionary.add_entry("BDM_DATABASE", database); + if hard_owned { + dictionary.hard_owner_entries.push("BDM_DATABASE".into()); + } + } + entries(document, model).ok_or(UNSUPPORTED) +} + +/// A record of `class` to make new ones like: one under `master`'s extension +/// dictionary, or any in the drawing. +fn template_record(document: &Document, master: Handle, class: &str) -> Option { + let tree: FxHashSet = document + .extension_dictionary_handle(master) + .and_then(|root| owned_tree(document, root).ok()) + .map(|tree| tree.into_iter().collect()) + .unwrap_or_default(); + let mut candidates: Vec = document + .objects + .iter() + .filter_map(|(handle, object)| match object { + ObjectType::Unknown { type_name, .. } if type_name == class => Some(*handle), + _ => None, + }) + .collect(); + candidates.sort_by_key(|handle| (!tree.contains(handle), *handle)); + candidates + .into_iter() + .find_map(|handle| read_record(document, handle)) +} + +/// The tag BricsCAD gives a parametric block, kept in its extended data and +/// named by every copy (`original.tag`). +fn block_tag(document: &Document, block: Handle) -> Option { + const NAME: &[u8] = b"ParametricBlockGUID"; + document + .object_xdata(block)? + .records() + .iter() + .filter(|record| record.application_name == "BDM_DB") + .flat_map(|record| &record.values) + .find_map(|value| { + let document::xdata::XDataValue::BinaryData(bytes) = value else { + return None; + }; + let at = bytes + .windows(NAME.len()) + .position(|window| window == NAME)? + + NAME.len(); + // A type byte (2: text), the length and the characters. + if *bytes.get(at)? != 2 { + return None; + } + let length = usize::from(u16::from_le_bytes([ + *bytes.get(at + 1)?, + *bytes.get(at + 2)?, + ])); + let text = bytes.get(at + 3..at + 3 + length)?; + String::from_utf8(text.to_vec()).ok() + }) +} + +/// Give `block` a new tag the way BricsCAD stores it, and return it. +fn give_block_tag(document: &mut Document, block: Handle) -> String { + const NAME: &[u8] = b"ParametricBlockGUID"; + let tag = crate::scene::block_authoring::new_guid().to_lowercase(); + let mut bytes = vec![1, 0, 0, 0]; + bytes.extend((NAME.len() as u16).to_le_bytes()); + bytes.extend(NAME); + bytes.push(2); + bytes.extend((tag.len() as u16).to_le_bytes()); + bytes.extend(tag.as_bytes()); + crate::scene::block_authoring::ensure_app_id(document, "BDM_DB"); + let mut record = document::xdata::ExtendedDataRecord::new("BDM_DB"); + record.add_value(document::xdata::XDataValue::BinaryData(bytes)); + document.set_object_xdata_record(block, record); + tag +} + +/// The handle as BricsCAD stores it in a raw value: its bytes, most +/// significant first, without leading zeros. +fn handle_bytes(handle: Handle) -> Vec { + handle + .value() + .to_be_bytes() + .into_iter() + .skip_while(|byte| *byte == 0) + .collect() +} + +/// The next free name of the form `*U`. +fn next_anonymous_name(document: &Document) -> String { + let next = document + .block_records + .iter() + .filter_map(|record| record.name.strip_prefix("*U")?.parse::().ok()) + .max() + .map_or(1, |n| n + 1); + format!("*U{next}") +} + +/// The raw object for `record`. +fn unknown(class: &str, record: &Record) -> ObjectType { + let (data, handle_bits) = record::encode(record); + ObjectType::Unknown { + type_name: class.to_string(), + handle: record.handle, + owner: record.owner.handle, + raw_dxf_codes: None, + raw_dwg_data: Some(data), + raw_dwg_handle_bits: handle_bits, + raw_dwg_version: Some(record.version), + } +} + +/// Store a changed record over the object it was read from. +fn store(document: &mut Document, record: &Record) { + let class = match document.objects.get(&record.handle) { + Some(ObjectType::Unknown { type_name, .. }) => type_name.clone(), + _ => return, + }; + document + .objects + .insert(record.handle, unknown(&class, record)); +} diff --git a/src/scene/bricscad_parameters/switch_tests.rs b/src/scene/bricscad_parameters/switch_tests.rs new file mode 100644 index 0000000000..8e8a46bdf8 --- /dev/null +++ b/src/scene/bricscad_parameters/switch_tests.rs @@ -0,0 +1,458 @@ +//! Switching on the BricsCAD drawing in `tests/fixtures/bricscad` (see its +//! README): EE shows the block in On/Shown, 146 the copy *U2 in Off/Shown and +//! 19E the copy *U3 in Off/Hidden; 146 and 19E have entries in model space. + +use super::record::{Body, Value}; +use super::*; +use crate::scene::Scene; +use std::collections::{BTreeMap, BTreeSet}; + +const MASTER: &str = "ocs-bricscad-visibility-block"; + +fn opened() -> Scene { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/bricscad/visibility-states.dwg" + ); + let bytes = std::fs::read(path).expect("read the fixture"); + let mut scene = Scene::new(); + scene.document = + crate::io::load_bytes_finalized(std::path::Path::new("visibility-states.dwg"), bytes) + .expect("open the fixture"); + scene.load_named_parameters_from_document(); + scene.load_parametric_constraints_from_document(); + scene +} + +fn reference(value: u64) -> Handle { + Handle::from(value) +} + +fn block_of(document: &Document, insert: u64) -> String { + match document.get_entity(reference(insert)) { + Some(EntityType::Insert(insert)) => insert.block_name.clone(), + other => panic!("{other:?}"), + } +} + +/// Each parameter and the state the reference shows. +fn shown(document: &Document, insert: u64) -> Vec<(String, String)> { + reference_parameters(document, reference(insert)) + .into_iter() + .map(|parameter| { + let state = parameter.states[parameter.current.unwrap()].clone(); + (parameter.name, state) + }) + .collect() +} + +fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter() + .map(|(a, b)| (a.to_string(), b.to_string())) + .collect() +} + +/// The parameters the reference's entry in model space lists. +fn entry(document: &Document, insert: u64) -> Option> { + let (_, record) = super::switch::find_entry(document, reference(insert))?; + Some( + record + .body + .properties() + .get("expr.const")? + .entries()? + .iter() + .map(|(key, value)| { + ( + key.text().unwrap().to_string(), + value.text().unwrap().to_string(), + ) + }) + .collect(), + ) +} + +/// The references in the BricsCAD objects of `document` that name an object +/// the drawing does not have, as (holder, target). +fn dangling_references(document: &Document) -> BTreeSet<(Handle, Handle)> { + let mut dangling = BTreeSet::new(); + for (handle, object) in &document.objects { + if !matches!(object, ObjectType::Unknown { type_name, .. } if type_name.to_ascii_uppercase().starts_with("BDM")) + { + continue; + } + let mut record = record(document, *handle).expect("a BricsCAD object decodes"); + record.refs_mut(|reference| { + let target = reference.handle; + let known = target.is_null() + || document.objects.contains_key(&target) + || document.get_entity(target).is_some() + || document.block_records.iter().any(|r| r.handle == target) + || document.layers.iter().any(|layer| layer.handle == target); + if !known { + dangling.insert((*handle, target)); + } + }); + } + dangling +} + +/// No reference in the BricsCAD objects names an object the drawing lacks, +/// apart from those BricsCAD itself left in the fixture: its global constraint +/// manager still lists child managers it purged. +fn assert_no_dangling_references(document: &Document) { + let left_by_bricscad = dangling_references(&opened().document); + let dangling = dangling_references(document); + let new: Vec<_> = dangling.difference(&left_by_bricscad).collect(); + assert!( + new.is_empty(), + "references to objects the drawing lacks: {new:?}" + ); +} + +#[test] +fn a_state_another_copy_shows_shares_that_copy_and_gives_the_reference_an_entry() { + let mut scene = opened(); + assert_eq!(entry(&scene.document, 0xEE), None); + assert!(scene + .set_bricscad_visibility(reference(0xEE), "LAMP", "Off") + .unwrap()); + let document = &scene.document; + assert_eq!( + block_of(document, 0xEE), + "*U2", + "BricsCAD shares copies too" + ); + assert_eq!( + shown(document, 0xEE), + pairs(&[("LAMP", "Off"), ("LABEL", "Shown")]) + ); + assert_eq!(entry(document, 0xEE), Some(pairs(&[("LAMP", "Off")]))); + assert_eq!( + shown(document, 0x146), + pairs(&[("LAMP", "Off"), ("LABEL", "Shown")]) + ); + assert_no_dangling_references(document); +} + +#[test] +fn the_block_s_own_states_show_the_block_and_the_entry_keeps_the_parameter() { + let mut scene = opened(); + assert!(scene + .set_bricscad_visibility(reference(0x146), "LAMP", "On") + .unwrap()); + let document = &scene.document; + assert_eq!(block_of(document, 0x146), MASTER); + assert_eq!( + shown(document, 0x146), + pairs(&[("LAMP", "On"), ("LABEL", "Shown")]) + ); + // BricsCAD keeps a parameter in the entry once set, also in the block's + // own state. + assert_eq!(entry(document, 0x146), Some(pairs(&[("LAMP", "On")]))); +} + +#[test] +fn a_state_no_block_shows_gets_a_new_copy() { + let mut scene = opened(); + let records = scene.document.block_records.iter().count(); + assert!(scene + .set_bricscad_visibility(reference(0xEE), "LABEL", "Hidden") + .unwrap()); + let document = &scene.document; + assert_eq!(document.block_records.iter().count(), records + 1); + let copy = block_of(document, 0xEE); + assert_eq!(copy, "*U4"); + let copy = document.block_records.get(©).unwrap().handle; + let master = document.block_records.get(MASTER).unwrap().handle; + assert_eq!(original_block(document, copy), Some(master)); + assert_eq!( + shown(document, 0xEE), + pairs(&[("LAMP", "On"), ("LABEL", "Hidden")]) + ); + assert_eq!(entry(document, 0xEE), Some(pairs(&[("LABEL", "Hidden")]))); + let layers: Vec = crate::scene::block_authoring::members(document, copy) + .into_iter() + .map(|member| document.get_entity(member).unwrap().common().layer.clone()) + .collect(); + assert_eq!( + layers, + ["0", "0", "0", "0", "*SUPPRESS"], + "only the text is hidden" + ); + // The block and the other references are left alone. + assert_eq!( + shown(document, 0x146), + pairs(&[("LAMP", "Off"), ("LABEL", "Shown")]) + ); + assert_eq!( + visibility_parameters(document, master) + .iter() + .map(|p| p.current) + .collect::>(), + [Some(0), Some(0)] + ); + assert_no_dangling_references(document); +} + +/// A property value with references written as the kind, code and class of +/// what they name, and members as their place in the block. +fn normalized(document: &Document, members: &[Handle], value: &Value) -> String { + match value { + Value::Object { kind, target } => { + let what = members + .iter() + .position(|member| *member == target.handle) + .map(|index| format!("member {index}")) + .or_else(|| { + document + .objects + .get(&target.handle) + .map(|object| match object { + ObjectType::Unknown { type_name, .. } => type_name.clone(), + ObjectType::Associative(object) => object.dxf_name.clone(), + other => format!("{:?}", std::mem::discriminant(other)), + }) + }) + .or_else(|| { + document + .layers + .iter() + .find(|layer| layer.handle == target.handle) + .map(|layer| format!("layer {}", layer.name)) + }) + .or_else(|| { + document + .block_records + .iter() + .find(|record| record.handle == target.handle) + .map(|record| format!("block {}", record.name)) + }) + .unwrap_or_else(|| format!("{:?}", target.handle)); + format!("ref({kind},{},{what})", target.code) + } + Value::List { element, items } => format!( + "list {element} [{}]", + items + .iter() + .map(|item| normalized(document, members, item)) + .collect::>() + .join(", ") + ), + Value::Map { + key, + value, + entries, + } => format!( + "map {key} {value} [{}]", + entries + .iter() + .map(|(k, v)| format!( + "{} => {}", + normalized(document, members, k), + normalized(document, members, v) + )) + .collect::>() + .join(", ") + ), + Value::Raw(bytes) => { + // A raw handle of a member of the block the copy was made from. + let handle = Handle::from(bytes.iter().fold(0u64, |v, b| v << 8 | u64::from(*b))); + let master = document.block_records.get(MASTER).unwrap().handle; + let index = crate::scene::block_authoring::members(document, master) + .iter() + .position(|member| *member == handle); + format!("raw member {index:?}") + } + other => format!("{other:?}"), + } +} + +/// Every BricsCAD object under `block`'s extension dictionary, in the order of +/// a walk through its feature and other managers, each as its class and +/// normalized properties. +fn parameter_objects(document: &Document, block: Handle) -> Vec { + let members = crate::scene::block_authoring::members(document, block); + let mut out = Vec::new(); + let mut seen = std::collections::HashSet::new(); + let mut stack: Vec = ["BDM_DATABASE", "FEATURE_MANAGER", "PERSIDMANAGER"] + .iter() + .filter_map(|key| database_entry(document, block, key)) + .collect(); + stack.reverse(); + while let Some(handle) = stack.pop() { + if !seen.insert(handle) { + continue; + } + let Some(record) = record(document, handle) else { + continue; + }; + let class = match document.objects.get(&handle) { + Some(ObjectType::Unknown { type_name, .. }) => type_name.clone(), + _ => continue, + }; + let mut children = Vec::new(); + let properties = match &record.body { + Body::Properties(properties) => properties.clone(), + Body::ConstraintManager { + counts, + children: owned, + settings, + } => { + children.extend(owned.iter().map(|r| r.handle)); + out.push(format!("{class} counts {counts:?}")); + settings.clone() + } + Body::Object { + entity, properties, .. + } => { + out.push(format!( + "{class} entity {}", + normalized( + document, + &members, + &Value::Object { + kind: 0, + target: *entity + } + ) + )); + properties.clone() + } + Body::Dependency { + entity, properties, .. + } => { + out.push(format!( + "{class} entity {}", + normalized( + document, + &members, + &Value::Object { + kind: 0, + target: *entity + } + ) + )); + properties.clone() + } + }; + for (name, value) in &properties.0 { + out.push(format!( + "{class}.{name} = {}", + normalized(document, &members, value) + )); + let mut value = value.clone(); + let mut collect = |value: &Value| { + if let Value::Object { target, .. } = value { + children.push(target.handle); + } + }; + walk(&mut value, &mut collect); + } + stack.extend(children.into_iter().rev()); + } + out +} + +fn walk(value: &mut Value, visit: &mut impl FnMut(&Value)) { + visit(value); + match value { + Value::List { items, .. } => items.iter_mut().for_each(|item| walk(item, visit)), + Value::Map { entries, .. } => entries.iter_mut().for_each(|(k, v)| { + walk(k, visit); + walk(v, visit); + }), + _ => {} + } +} + +#[test] +fn a_new_copy_holds_what_bricscad_s_own_copy_in_the_same_states_holds() { + let mut scene = opened(); + let master = scene.document.block_records.get(MASTER).unwrap().handle; + let bricscad = scene.document.block_records.get("*U3").unwrap().handle; + let states: BTreeMap = [("LAMP", "Off"), ("LABEL", "Hidden")] + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + let listed: BTreeSet = ["LAMP", "LABEL"].iter().map(|s| s.to_string()).collect(); + let copy = scene + .clone_parametric_copy(master, &states, &listed) + .unwrap(); + let ours = parameter_objects(&scene.document, copy); + let theirs = parameter_objects(&scene.document, bricscad); + assert!(ours.len() > 40, "{ours:#?}"); + // The key variables' numbers follow no rule BricsCAD keeps: the same + // state carries 0 in one of its copies and 1 in another. + let differences: Vec<(&String, &String)> = ours + .iter() + .zip(&theirs) + .filter(|(a, b)| a != b) + .filter(|(a, _)| !a.starts_with("BDMDBCONFIGVARREACTOR.Value")) + .collect(); + assert_eq!(ours.len(), theirs.len(), "{ours:#?}\n{theirs:#?}"); + assert!(differences.is_empty(), "{differences:#?}"); + // Member layers too. + let layers = |block: Handle| -> Vec { + crate::scene::block_authoring::members(&scene.document, block) + .into_iter() + .map(|m| scene.document.get_entity(m).unwrap().common().layer.clone()) + .collect() + }; + assert_eq!(layers(copy), layers(bricscad)); +} + +#[test] +fn the_switched_drawing_keeps_its_parameters_through_a_dwg_save() { + let mut scene = opened(); + scene + .set_bricscad_visibility(reference(0xEE), "LABEL", "Hidden") + .unwrap(); + scene + .set_bricscad_visibility(reference(0x19E), "LAMP", "On") + .unwrap(); + scene.sync_native_parametric_graph(); + let saved = crate::io::save_to_bytes(&scene.document, "dwg", scene.document.version) + .expect("save as DWG"); + let reopened = crate::io::load_bytes_finalized(std::path::Path::new("saved.dwg"), saved) + .expect("open the saved DWG"); + assert_eq!( + shown(&reopened, 0xEE), + pairs(&[("LAMP", "On"), ("LABEL", "Hidden")]) + ); + assert_eq!( + shown(&reopened, 0x146), + pairs(&[("LAMP", "Off"), ("LABEL", "Shown")]) + ); + assert_eq!( + shown(&reopened, 0x19E), + pairs(&[("LAMP", "On"), ("LABEL", "Hidden")]) + ); + assert_eq!( + block_of(&reopened, 0x19E), + block_of(&reopened, 0xEE), + "shared" + ); + assert_eq!( + entry(&reopened, 0x19E), + Some(pairs(&[("LABEL", "Hidden"), ("LAMP", "On")])) + ); + assert_no_dangling_references(&reopened); +} + +#[test] +fn an_unknown_parameter_or_state_is_refused_and_a_shown_state_changes_nothing() { + let mut scene = opened(); + let before = scene.document.clone(); + assert!(scene + .set_bricscad_visibility(reference(0xEE), "NOPE", "On") + .is_err()); + assert!(scene + .set_bricscad_visibility(reference(0xEE), "LAMP", "Dim") + .is_err()); + assert_eq!( + scene.set_bricscad_visibility(reference(0xEE), "LAMP", "On"), + Ok(false) + ); + assert!(scene.document == before); +} diff --git a/src/scene/bricscad_parameters/tests.rs b/src/scene/bricscad_parameters/tests.rs index 393ec3cc1b..d876386121 100644 --- a/src/scene/bricscad_parameters/tests.rs +++ b/src/scene/bricscad_parameters/tests.rs @@ -1,4 +1,5 @@ use super::*; +use document::DxfVersion; /// The BricsCAD drawing in `tests/fixtures/bricscad` (see its README). fn fixture() -> Document { @@ -47,11 +48,13 @@ fn the_definition_names_its_parameters_their_states_and_the_ones_it_shows() { name: "LAMP".into(), states: vec!["On".into(), "Off".into()], current: Some(0), + feature: Handle::from(0x16Fu64), }, VisibilityParameter { name: "LABEL".into(), states: vec!["Shown".into(), "Hidden".into()], current: Some(0), + feature: Handle::from(0x176u64), }, ] ); @@ -121,14 +124,18 @@ fn a_cut_record_decodes_to_nothing_rather_than_a_wrong_answer() { if type_name != "BDMDBCONFIGURATIONTABLE" { continue; } - let whole = decode(data, *raw_dwg_handle_bits, *version).expect("the whole record"); - assert!(whole.get("KeyValues").is_some()); + let whole = record::decode(type_name, data, *raw_dwg_handle_bits, *version) + .expect("the whole record"); + assert!(whole.body.properties().get("KeyValues").is_some()); records += 1; for length in 0..data.len() { // Shorter by whole bytes: the streams no longer line up. - let _ = decode(&data[..length], *raw_dwg_handle_bits, *version); + let _ = record::decode(type_name, &data[..length], *raw_dwg_handle_bits, *version); } - assert_eq!(decode(data, *raw_dwg_handle_bits, DxfVersion::AC1021), None); + assert_eq!( + record::decode(type_name, data, *raw_dwg_handle_bits, DxfVersion::AC1021), + None + ); } assert_eq!(records, 6, "two tables in each of the three blocks"); } diff --git a/src/scene/model/object.rs b/src/scene/model/object.rs index 849142ac86..98da238b9e 100644 --- a/src/scene/model/object.rs +++ b/src/scene/model/object.rs @@ -22,6 +22,9 @@ pub enum BlockParameterComponent { Angle, Flip, Visibility(u64), + // A BricsCAD parametric block's visibility parameter, with a hash of its + // name and states. + Bricscad(u64), TableRow(u64), LookupOutput { column: usize, revision: u64 }, } From f8fd5cc8888dfc0b836f48de2f98c9e31f2dc389 Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:03:48 +0100 Subject: [PATCH 4/7] A switched BricsCAD block keeps each read of a variable at its value BricsCAD keeps every value dependency (ACDBASSOCVALUEDEPENDENCY) at the value of the variable it reads: all 14,882 of them in 408 drawings made in BricsCAD do. It takes a variable whose new value its reads already hold for unchanged and does not evaluate what depends on it; in model space a stale read keeps it from hiding a member on the next change of state. A copy made for a reference kept the reads of the block it was cloned from. Setting a variable now sets its reads too. --- src/scene/bricscad_parameters/switch.rs | 22 +++++++-- src/scene/bricscad_parameters/switch_tests.rs | 49 +++++++++++++++++++ 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/src/scene/bricscad_parameters/switch.rs b/src/scene/bricscad_parameters/switch.rs index 0c29d8937b..c21cc54eb0 100644 --- a/src/scene/bricscad_parameters/switch.rs +++ b/src/scene/bricscad_parameters/switch.rs @@ -708,6 +708,10 @@ fn evaluate(expression: &str, columns: &FxHashMap) -> Option { table.resolve(RESULT).ok().filter(|value| value.is_finite()) } +/// Set an associative variable and every read of it: BricsCAD keeps each +/// value dependency at the value of the variable it reads, and takes a +/// variable whose new value its reads already hold for unchanged, leaving +/// what depends on it unevaluated. fn set_variable( document: &mut Document, variable: Handle, @@ -715,16 +719,28 @@ fn set_variable( value: AssocEvalVariant, ) -> Result<()> { let Some(ObjectType::Associative(AssociativeObject { - data: AssociativeData::Variable(variable), + data: AssociativeData::Variable(object), + reactors, .. })) = document.objects.get_mut(&variable) else { return Err(UNSUPPORTED); }; if let Some(expression) = expression { - variable.expression = expression; + object.expression = expression; + } + object.value = value.clone(); + for reactor in reactors.clone() { + if let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::ValueDependency(read), + .. + })) = document.objects.get_mut(&reactor) + { + if read.dependency.dependent_on == variable { + read.value = value.clone(); + } + } } - variable.value = value; Ok(()) } diff --git a/src/scene/bricscad_parameters/switch_tests.rs b/src/scene/bricscad_parameters/switch_tests.rs index 8e8a46bdf8..660ea5796d 100644 --- a/src/scene/bricscad_parameters/switch_tests.rs +++ b/src/scene/bricscad_parameters/switch_tests.rs @@ -456,3 +456,52 @@ fn an_unknown_parameter_or_state_is_refused_and_a_shown_state_changes_nothing() ); assert!(scene.document == before); } + +/// BricsCAD keeps each read of a variable at the variable's value, and takes a +/// variable whose reads already hold its new value for unchanged: a stale +/// read would keep it from evaluating what depends on the variable. +#[test] +fn each_read_of_a_variable_holds_the_variable_s_value_after_a_switch() { + use document::objects::{AssociativeData, AssociativeObject}; + let mut scene = opened(); + assert!(scene + .set_bricscad_visibility(reference(0xEE), "LABEL", "Hidden") + .unwrap()); + let document = &scene.document; + let copy = document + .block_records + .get(&block_of(document, 0xEE)) + .unwrap() + .handle; + // The copy's network sits in its extension dictionary, behind a + // dictionary of the same name. + let entry = |dictionary: Handle| match document.objects.get(&dictionary) { + Some(ObjectType::Dictionary(dictionary)) => dictionary.get("ACAD_ASSOCNETWORK"), + _ => None, + }; + let mut network = entry(document.extension_dictionary_handle(copy).unwrap()).unwrap(); + while let Some(inner) = entry(network) { + network = inner; + } + let mut reads = 0; + for object in document.objects.values() { + let ObjectType::Associative(AssociativeObject { + data: AssociativeData::ValueDependency(read), + .. + }) = object + else { + continue; + }; + let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + owner, + .. + })) = document.objects.get(&read.dependency.dependent_on) + else { + panic!("a read of something other than a variable"); + }; + assert_eq!(read.value, variable.value, "{}", variable.name); + reads += usize::from(*owner == network); + } + assert!(reads > 0, "the copy's variables are read"); +} From 0315b427840a2c1959715141c98dd28209bb7992 Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:06:16 +0100 Subject: [PATCH 5/7] VISIBILITYSTATES creates and edits the visibility states of a BricsCAD parametric block BricsCAD sets up a parametric block's visibility states with its own VISIBILITYSTATES command, on model space of the drawing that becomes the block. OCS now has the same command, with the same prompts: a parameter, a state (new names make new ones), then Add, Remove, make Visible, make Invisible or Select state, and the objects. What it leaves is what BricsCAD leaves for the same steps, stored where BricsCAD reads it, so BricsCAD lists and switches the states and goes on editing them: - per parameter a configuration feature with a table, a row per state and a column (`look_n`) per group of objects that show and hide together; - per group a suppression whose variable is `1 - ` the product of its columns, one per parameter that rules the group, in parameter order; - the variables in model space's associative network, a dependency and a `BDMOBJECT` per object; names of new objects follow the drawing's, else the interface language (BricsCAD's English or German names). A new group or column takes a name no variable of the network has: BricsCAD finds variables by name, and some of its drawings name a group's variable after another group. After each step the current states show again. Each key also gets the number of the state it shows: BricsCAD shows the state of that number when it next evaluates, and its own state selection leaves the number behind. The command works in model space only. In the Block Editor the copies the block's references show would keep the old states, and BricsCAD itself does not bring them up to date on a later switch. A step is one undo step. Undo of a step taken as a document snapshot now also puts back the drawing's parameter table, which these steps change; it used to stay, and the next command wrote the undone variables back. Tests: the BricsCAD drawings in tests/fixtures/bricscad/authoring-*.dwg (see the README there) were saved along one run of BricsCAD's command; the same run here, through the scene and typed at the command line, leaves the same tables, groups, expressions, values and layers. Reads hold their variables' values, keys the number of their state, a new group's name is free, undo and redo work, a refused step and the Block Editor change nothing. Wiki: VISIBILITYSTATES page, a paragraph on BricsCAD parametric blocks in Blocks and Attributes. --- docs/wiki/commands/VISIBILITYSTATES.md | 30 + docs/wiki/pages/Blocks-and-Attributes.md | 2 + docs/wiki/since.json | 1 + src/app/commands/bricscad_visibility.rs | 119 + src/app/commands/mod.rs | 4 + src/app/history.rs | 12 +- src/app/mod.rs | 2 + src/app/tab_document.rs | 3 + src/app/visibilitystates_tests.rs | 169 ++ src/modules/draw/modify/mod.rs | 1 + src/modules/draw/modify/visibilitystates.rs | 238 ++ src/scene/bricscad_parameters.rs | 14 + src/scene/bricscad_parameters/author.rs | 2156 +++++++++++++++++ src/scene/bricscad_parameters/author_tests.rs | 429 ++++ src/scene/bricscad_parameters/record.rs | 23 + src/scene/bricscad_parameters/switch.rs | 10 +- src/scene/dwg_native_constraints.rs | 2 +- tests/fixtures/bricscad/README.md | 49 + tests/fixtures/bricscad/authoring-edit.dwg | Bin 0 -> 18437 bytes tests/fixtures/bricscad/authoring-select.dwg | Bin 0 -> 18117 bytes tests/fixtures/bricscad/authoring-start.dwg | Bin 0 -> 13669 bytes 21 files changed, 3257 insertions(+), 7 deletions(-) create mode 100644 docs/wiki/commands/VISIBILITYSTATES.md create mode 100644 src/app/commands/bricscad_visibility.rs create mode 100644 src/app/visibilitystates_tests.rs create mode 100644 src/modules/draw/modify/visibilitystates.rs create mode 100644 src/scene/bricscad_parameters/author.rs create mode 100644 src/scene/bricscad_parameters/author_tests.rs create mode 100644 tests/fixtures/bricscad/authoring-edit.dwg create mode 100644 tests/fixtures/bricscad/authoring-select.dwg create mode 100644 tests/fixtures/bricscad/authoring-start.dwg diff --git a/docs/wiki/commands/VISIBILITYSTATES.md b/docs/wiki/commands/VISIBILITYSTATES.md new file mode 100644 index 0000000000..54e846eb26 --- /dev/null +++ b/docs/wiki/commands/VISIBILITYSTATES.md @@ -0,0 +1,30 @@ +--- +summary: Creates and edits the visibility states of a BricsCAD parametric block in model space of the block's own drawing, stored the way BricsCAD stores them. +related: BVSTATE, BVSHOW, BVHIDE +web: Not available in the web app. +--- + +## Usage +1. Open the drawing of a BricsCAD parametric block (the block is the drawing's model space), or any drawing to make its model space one, and work in model space. +2. Type `VISIBILITYSTATES`. +3. At "Enter a new parameter or [...]", type the name of a visibility parameter. A name not in the list makes a new parameter. +4. At "Enter a new state for ... or [...]", type the name of a state. A name not in the list makes a new state, in which every object the parameter rules starts hidden. +5. Pick an action (see below), or press Enter for **Add objects**. +6. For every action but **Select state**, select the objects and press Enter. Objects you selected before starting the command are used without asking. + +## Actions +| Action | What it does | +|---|---| +| **Add objects** (`A`) | The parameter rules the objects: they show in this state only. Objects it already rules do not change. | +| **Remove objects** (`R`) | The parameter no longer rules the objects, so its states no longer show or hide them. | +| **make objects Visible** (`V`) | The objects show in this state. Objects the parameter did not rule yet show in this state only. | +| **make objects Invisible** (`I`) | The objects are hidden in this state. Objects the parameter did not rule yet show in every other state. | +| **Select state** (`S`) | Makes the state current, showing and hiding the objects the parameters rule. | + +## Notes +- This is BricsCAD's own command for its parametric blocks. A drawing saved as DWG keeps the states where BricsCAD finds them: BricsCAD lists and switches them, and can go on editing them with its own `VISIBILITYSTATES`. Where BricsCAD inserted the block into another drawing, a reference to it lists the states in Properties, where you pick one. +- An object ruled by several parameters shows only when every one of them shows it. +- New suppression and object names follow the names the drawing already uses; in a drawing without any they follow the interface language (English or German names). +- The command works in model space only. In the Block Editor it does nothing, because the copies of the block that its references show would keep the old states; edit the block's own drawing instead. +- The drawing must be DWG 2010 or later. Dynamic blocks made in OCS or AutoCAD use [`BVSTATE`](BVSTATE-Command) instead. +- Each run of the command is one undo step. diff --git a/docs/wiki/pages/Blocks-and-Attributes.md b/docs/wiki/pages/Blocks-and-Attributes.md index e4b4305737..a0600ff6fa 100644 --- a/docs/wiki/pages/Blocks-and-Attributes.md +++ b/docs/wiki/pages/Blocks-and-Attributes.md @@ -83,6 +83,8 @@ Dynamic blocks change shape through grips on each reference: a door that sets it **Visibility states.** `BVSTATE` creates and switches visibility states; `BVSHOW` and `BVHIDE` choose which objects show in the current state. Each reference then has a list to pick its state. +**BricsCAD parametric blocks.** A reference to a block made parametric in BricsCAD lists the states of its visibility parameters in Properties; the state you pick shows the way BricsCAD shows it. [`VISIBILITYSTATES`](VISIBILITYSTATES-Command) creates and edits those states in model space of the block's own drawing, stored where BricsCAD reads them. + **Block properties table.** `BTABLE` defines combinations of parameter values in a table, so each reference picks a row. `BTESTBLOCK` opens a test window to try the block's grips before you save it. `BCONSTRUCTION` marks objects as construction geometry that does not show in the references. Geometric and dimensional constraints work inside blocks too; see [Parametric Constraints](Parametric-Constraints). diff --git a/docs/wiki/since.json b/docs/wiki/since.json index 69e578a0f5..e8f689be75 100644 --- a/docs/wiki/since.json +++ b/docs/wiki/since.json @@ -905,6 +905,7 @@ "VCONSTRAINT": "2026.37", "VERTICAL": "0.1.4", "VIEW": "0.1.3", +"VISIBILITYSTATES": "2026.47", "VISRETAIN": "0.7.0", "VISUALSTYLES": "0.7.0", "VPCLIP": "2026.39", diff --git a/src/app/commands/bricscad_visibility.rs b/src/app/commands/bricscad_visibility.rs new file mode 100644 index 0000000000..ed31f7001a --- /dev/null +++ b/src/app/commands/bricscad_visibility.rs @@ -0,0 +1,119 @@ +//! VISIBILITYSTATES: the visibility states of a BricsCAD parametric block, in +//! model space of the block's own drawing (see +//! `scene::bricscad_parameters::author`). + +use crate::app::{Message, OpenCADStudio}; +use crate::command::CadCommand; +use crate::modules::draw::modify::visibilitystates::{VisibilityStatesCommand, SEP}; +use crate::scene::bricscad_parameters::{self as bricscad, Action}; +use document::Handle; +use iced::Task; + +/// Marks the step that runs after the objects are picked. +const PICKED: &str = "PICKED"; + +impl OpenCADStudio { + /// Model space, the block of a BricsCAD block drawing. A block definition + /// is left alone: the anonymous copies its references show would keep the + /// states it had. + fn visibility_states_owner(&mut self, i: usize) -> Option { + if self.tabs[i].active_block_edit_session().is_none() + && self.tabs[i].scene.current_layout == "Model" + { + return Some(self.tabs[i].scene.document.header.model_space_block_handle); + } + self.command_line.push_error( + crate::t!( + "VISIBILITYSTATES works in model space: open the drawing of the BricsCAD block." + ) + .as_ref(), + ); + None + } + + pub(super) fn dispatch_bricscad_visibility( + &mut self, + cmd: &str, + i: usize, + ) -> Option> { + if cmd == "VISIBILITYSTATES" { + let Some(owner) = self.visibility_states_owner(i) else { + return Some(Task::none()); + }; + let parameters = bricscad::parameter_states(&self.tabs[i].scene.document, owner); + let command = VisibilityStatesCommand::new(parameters); + self.command_line.push_info(&command.prompt()); + self.command_line.set_step_options(command.options()); + self.tabs[i].active_cmd = Some(Box::new(command)); + return Some(Task::none()); + } + let fields = cmd.strip_prefix("_VISIBILITYSTATES")?; + let fields: Vec<&str> = fields.strip_prefix(SEP)?.split(SEP).collect(); + let (parameter, state, action, picked) = match fields.as_slice() { + [parameter, state, action] => (*parameter, *state, *action, false), + [parameter, state, action, PICKED] => (*parameter, *state, *action, true), + _ => return Some(Task::none()), + }; + let action = match action { + "ADD" => Action::Add, + "REMOVE" => Action::Remove, + "VISIBLE" => Action::Visible, + "INVISIBLE" => Action::Invisible, + "SELECT" => Action::Select, + _ => return Some(Task::none()), + }; + if action != Action::Select && !picked && self.tabs[i].scene.selected.is_empty() { + use crate::modules::draw::select::SelectObjectsCommand; + let pending = format!("{cmd}{SEP}{PICKED}"); + let command = + SelectObjectsCommand::with_prompt("VISIBILITYSTATES", &pending, "Select objects:"); + self.command_line.push_info(&command.prompt()); + self.tabs[i].active_cmd = Some(Box::new(command)); + return Some(Task::none()); + } + self.tabs[i].active_cmd = None; + let Some(owner) = self.visibility_states_owner(i) else { + return Some(Task::none()); + }; + let objects = if action == Action::Select { + Vec::new() + } else { + self.tabs[i].scene.selected_handles_in_order() + }; + // The edit runs on a copy, so a refusal leaves the drawing as it was; + // what the editor holds goes into the drawing first. + self.tabs[i].scene.sync_native_parametric_graph(); + let mut scene = crate::scene::Scene::new(); + scene.document = self.tabs[i].scene.document.clone(); + scene.load_named_parameters_from_document(); + scene.load_parametric_constraints_from_document(); + match scene.edit_bricscad_visibility(owner, parameter, state, action, &objects) { + Ok(()) => { + self.push_undo_snapshot(i, "VISIBILITYSTATES"); + self.apply_action_document_and_bump(i, scene.document); + self.tabs[i].scene.load_named_parameters_from_document(); + self.tabs[i] + .scene + .load_parametric_constraints_from_document(); + self.tabs[i].dirty = true; + self.finish_pending_history(i); + if action != Action::Select { + self.tabs[i].scene.deselect_all(); + } + let shown = bricscad::parameter_states(&self.tabs[i].scene.document, owner) + .into_iter() + .find(|(name, _)| name.eq_ignore_ascii_case(parameter)) + .and_then(|_| { + bricscad::current_state(&self.tabs[i].scene.document, owner, parameter) + }); + if let Some(shown) = shown { + self.command_line + .push_output(crate::tf!("Current visibility state: {}", shown).as_ref()); + } + self.refresh_properties(); + } + Err(error) => self.command_line.push_error(crate::t!(error).as_ref()), + } + Some(Task::none()) + } +} diff --git a/src/app/commands/mod.rs b/src/app/commands/mod.rs index 5196473e82..027f1ee26a 100644 --- a/src/app/commands/mod.rs +++ b/src/app/commands/mod.rs @@ -29,6 +29,7 @@ pub(crate) fn linetype_library_lock() -> std::sync::MutexGuard<'static, ()> { mod revcloud_vars; pub(crate) use purge::purge_pass; mod block_editor_vars; +mod bricscad_visibility; mod bvisibility; mod count; mod dash; @@ -816,6 +817,9 @@ impl OpenCADStudio { if let Some(t) = self.dispatch_model_import(cmd, i) { return Some(t); } + if let Some(t) = self.dispatch_bricscad_visibility(cmd, i) { + return Some(t); + } if let Some(t) = self.dispatch_bvisibility(cmd, i) { return Some(t); } diff --git a/src/app/history.rs b/src/app/history.rs index 7fd6b7a60a..e5b0471bca 100644 --- a/src/app/history.rs +++ b/src/app/history.rs @@ -388,8 +388,17 @@ impl OpenCADStudio { .graph_before .take() .map(|before| Box::new((before, self.tabs[i].graph.undo_state()))); + let named_parameters_after = self.tabs[i].scene.named_parameters(); + let named_parameters = + (&pending.named_parameters_before != named_parameters_after).then(|| { + ( + pending.named_parameters_before, + named_parameters_after.clone(), + ) + }); if !pending.keep_empty && graph.is_none() + && named_parameters.is_none() && visibility_states.is_none() && entities.is_empty() && reference_designations.is_empty() @@ -421,7 +430,7 @@ impl OpenCADStudio { reference_designations, reference_session, graph, - named_parameters: None, + named_parameters, label: pending.label, }; self.push_undo_entry(i, HistorySnapshot::Delta(Box::new(delta))); @@ -524,6 +533,7 @@ impl OpenCADStudio { reference_designations_before: Vec::new(), reference_session_before: self.reference_session_state(i), parametric_constraints_before: self.tabs[i].scene.parametric_constraints.clone(), + named_parameters_before: self.tabs[i].scene.named_parameters().clone(), plugin_owned: false, keep_empty: false, held: false, diff --git a/src/app/mod.rs b/src/app/mod.rs index 542bf13e07..f3c95588aa 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -38,6 +38,8 @@ mod block_test_tests; mod block_visibility; #[cfg(test)] mod bricscad_visibility_tests; +#[cfg(test)] +mod visibilitystates_tests; pub(crate) mod calc; mod command_driver; mod extraction_catalog; diff --git a/src/app/tab_document.rs b/src/app/tab_document.rs index a5c3245212..3e38ae73b0 100644 --- a/src/app/tab_document.rs +++ b/src/app/tab_document.rs @@ -1538,6 +1538,9 @@ pub(super) struct PendingHistorySnapshot { /// removes a constraint a plugin created inside its scope. pub(super) parametric_constraints_before: Vec, + /// The drawing-wide parameter table when the scope opened. A step that + /// changes it (BricsCAD's visibility columns are parameters) puts it back. + pub(super) named_parameters_before: crate::scene::named_parameters::ParameterTable, /// Opened by a plugin's `push_undo`: while a plugin request runs, the /// commands it drives join this scope instead of closing it. pub(super) plugin_owned: bool, diff --git a/src/app/visibilitystates_tests.rs b/src/app/visibilitystates_tests.rs new file mode 100644 index 0000000000..ff79c7f2fc --- /dev/null +++ b/src/app/visibilitystates_tests.rs @@ -0,0 +1,169 @@ +//! VISIBILITYSTATES typed at the command line on the BricsCAD drawing of five +//! lines in `tests/fixtures/bricscad` leaves what BricsCAD leaves, and each +//! step is one undo step. + +use super::*; +use document::Handle; + +fn opened(name: &str) -> OpenCADStudio { + let mut app = OpenCADStudio::new_for_test(); + let path = format!( + "{}/tests/fixtures/bricscad/{name}", + env!("CARGO_MANIFEST_DIR") + ); + app.automation_op(&serde_json::json!({"op": "open", "path": path}).to_string()); + app +} + +fn feed(app: &mut OpenCADStudio, text: &str) { + let _ = app.update(Message::CommandInput(text.to_string())); + let _ = app.update(Message::CommandSubmit); +} + +/// One run of the command: the lines by number are selected first, as an +/// operator picks them before or when the command asks. +fn visibility_states( + app: &mut OpenCADStudio, + parameter: &str, + state: &str, + action: &str, + lines: &[usize], +) { + let i = app.active_tab; + app.tabs[i].scene.deselect_all(); + for (k, n) in lines.iter().enumerate() { + let handle = Handle::from(crate::scene::bricscad_parameters::author_tests::LINES[n - 1]); + app.tabs[i].scene.select_entity(handle, k == 0); + } + let _ = app.dispatch_command("VISIBILITYSTATES"); + feed(app, parameter); + feed(app, state); + feed(app, action); + assert!( + app.tabs[i].active_cmd.is_none(), + "{parameter} {state} {action} left a step open" + ); +} + +#[test] +fn typed_at_the_command_line_the_run_leaves_what_bricscad_leaves() { + let mut app = opened("authoring-start.dwg"); + for (parameter, state, action, lines) in [ + ("P1", "S1", "A", &[1, 2][..]), + ("P1", "S2", "I", &[1]), + ("P1", "S3", "I", &[2]), + ("P1", "S2", "V", &[1]), + ("P1", "S1", "A", &[3]), + ("P1", "S1", "R", &[3]), + ("P2", "Sichtbar", "A", &[4]), + ("P2", "Unsichtbar", "I", &[4]), + ("P2", "Sichtbar", "A", &[2]), + ("P1", "S4", "V", &[1]), + ("P1", "S2", "S", &[]), + ("P1", "S3", "S", &[]), + ] { + visibility_states(&mut app, parameter, state, action, lines); + } + let ours = crate::scene::bricscad_parameters::author_tests::describe( + &app.tabs[app.active_tab].scene.document, + ); + let theirs = crate::scene::bricscad_parameters::author_tests::describe( + &opened("authoring-select.dwg").tabs[0].scene.document, + ); + // The test runs in English; BricsCAD named them in German. + let ours: Vec = ours + .into_iter() + .map(|line| { + line.replace("Suppress_", "Unterdrücken_") + .replace( + "controlling visibility of entities in ", + "Steuerung der Sichtbarkeit von Objekten in ", + ) + .replace("Entity_", "Objekt_") + }) + .collect(); + assert_eq!(ours, theirs); +} + +#[test] +fn each_run_is_one_undo_step_and_a_refusal_changes_nothing() { + let mut app = opened("authoring-start.dwg"); + let i = app.active_tab; + let start = app.tabs[i].scene.document.clone(); + visibility_states(&mut app, "P1", "S1", "A", &[1, 2]); + assert_ne!(app.tabs[i].scene.document, start); + let _ = app.update(Message::Undo); + assert!( + crate::scene::bricscad_parameters::parameter_states( + &app.tabs[i].scene.document, + app.tabs[i].scene.document.header.model_space_block_handle + ) + .is_empty(), + "undo takes the parameter away" + ); + let _ = app.update(Message::Redo); + assert_eq!( + crate::scene::bricscad_parameters::parameter_states( + &app.tabs[i].scene.document, + app.tabs[i].scene.document.header.model_space_block_handle + ), + [("P1".to_string(), vec!["S1".to_string()])], + "redo brings it back" + ); + let _ = app.update(Message::Undo); + // A state to select that does not exist is refused, the drawing unchanged. + let before = app.tabs[i].scene.document.clone(); + let undo = app.tabs[i].history.undo_stack.len(); + visibility_states(&mut app, "P9", "S1", "S", &[]); + assert_eq!(app.tabs[i].history.undo_stack.len(), undo); + assert!(app.tabs[i].scene.document == before); +} + +#[test] +fn in_the_block_editor_the_command_changes_nothing() { + let mut app = opened("visibility-states.dwg"); + let i = app.active_tab; + let _ = app.dispatch_command(&format!("BEDIT_BEGIN:{}", 0xEE)); + assert!(app.tabs[i].active_block_edit.is_some()); + let before = app.tabs[i].scene.document.clone(); + let _ = app.dispatch_command("VISIBILITYSTATES"); + assert!(app.tabs[i].active_cmd.is_none()); + assert!(app.tabs[i].scene.document == before); +} + +#[test] +fn objects_picked_when_the_command_asks_are_the_ones_it_takes() { + let mut app = opened("authoring-start.dwg"); + let i = app.active_tab; + app.tabs[i].scene.deselect_all(); + let _ = app.dispatch_command("VISIBILITYSTATES"); + feed(&mut app, "P1"); + feed(&mut app, "S1"); + feed(&mut app, "A"); + let lines = crate::scene::bricscad_parameters::author_tests::LINES; + for handle in [lines[0], lines[1]] { + let command = app.tabs[i] + .active_cmd + .as_mut() + .expect("the command asks for objects"); + let _ = command.on_entity_pick(Handle::from(handle), glam::DVec3::ZERO); + } + feed(&mut app, ""); + assert!(app.tabs[i].active_cmd.is_none()); + + let mut scene = crate::scene::bricscad_parameters::author_tests::fixture("authoring-start.dwg"); + let model = scene.document.header.model_space_block_handle; + scene + .edit_bricscad_visibility( + model, + "P1", + "S1", + crate::scene::bricscad_parameters::Action::Add, + &[Handle::from(lines[0]), Handle::from(lines[1])], + ) + .unwrap(); + assert_eq!( + crate::scene::bricscad_parameters::author_tests::describe(&app.tabs[i].scene.document), + crate::scene::bricscad_parameters::author_tests::describe(&scene.document) + ); +} diff --git a/src/modules/draw/modify/mod.rs b/src/modules/draw/modify/mod.rs index 88449a126d..0b249fd506 100644 --- a/src/modules/draw/modify/mod.rs +++ b/src/modules/draw/modify/mod.rs @@ -35,3 +35,4 @@ pub mod translate; pub mod trim; pub mod txtexp; pub mod vertex_edit; +pub mod visibilitystates; diff --git a/src/modules/draw/modify/visibilitystates.rs b/src/modules/draw/modify/visibilitystates.rs new file mode 100644 index 0000000000..0a48e90c9e --- /dev/null +++ b/src/modules/draw/modify/visibilitystates.rs @@ -0,0 +1,238 @@ +// VISIBILITYSTATES — the visibility states of a BricsCAD parametric block, in +// model space of the block's own drawing: name a parameter and a state (new +// ones are made), then add, remove, show or hide objects in it, or make it +// current. The prompts follow BricsCAD's. + +use crate::command::{CadCommand, CmdOption, CmdResult, InputKind}; +use document::Handle; +use glam::DVec3; + +/// Separates the fields of the steps the command hands over. +pub const SEP: char = '\u{1f}'; + +enum Step { + Parameter, + State(String), + Action(String, String), +} + +pub struct VisibilityStatesCommand { + /// Each parameter with its states. + parameters: Vec<(String, Vec)>, + step: Step, +} + +impl VisibilityStatesCommand { + pub fn new(parameters: Vec<(String, Vec)>) -> Self { + Self { + parameters, + step: Step::Parameter, + } + } + + fn known<'a>(names: impl IntoIterator, name: &str) -> Option { + names + .into_iter() + .find(|candidate| candidate.eq_ignore_ascii_case(name)) + .cloned() + } + + fn states(&self, parameter: &str) -> Vec { + self.parameters + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case(parameter)) + .map(|(_, states)| states.clone()) + .unwrap_or_default() + } + + fn list(names: &[String]) -> String { + if names.is_empty() { + String::new() + } else { + format!(" or [{}]", names.join("/")) + } + } + + fn done(parts: &[&str]) -> CmdResult { + let mut command = String::from("_VISIBILITYSTATES"); + for part in parts { + command.push(SEP); + command.push_str(part); + } + CmdResult::Dispatch(command) + } +} + +impl CadCommand for VisibilityStatesCommand { + fn name(&self) -> &'static str { + "VISIBILITYSTATES" + } + + fn prompt(&self) -> String { + match &self.step { + Step::Parameter => { + let names: Vec = self.parameters.iter().map(|(n, _)| n.clone()).collect(); + crate::tf!( + "VISIBILITYSTATES Enter a new parameter{}:", + Self::list(&names) + ) + .into_owned() + } + Step::State(parameter) => crate::tf!( + "VISIBILITYSTATES Enter a new state for {}{}:", + parameter, + Self::list(&self.states(parameter)) + ) + .into_owned(), + Step::Action(..) => crate::t!( + "VISIBILITYSTATES Select action [Add objects/Remove objects/make objects Visible/make objects Invisible/Select state] :" + ) + .into_owned(), + } + } + + fn options(&self) -> Vec { + match &self.step { + Step::Parameter => self + .parameters + .iter() + .map(|(name, _)| CmdOption::new(name, name)) + .collect(), + Step::State(parameter) => self + .states(parameter) + .iter() + .map(|state| CmdOption::new(state, state)) + .collect(), + Step::Action(..) => vec![ + CmdOption::new(crate::t!("Add objects").as_ref(), "A"), + CmdOption::new(crate::t!("Remove objects").as_ref(), "R"), + CmdOption::new(crate::t!("make objects Visible").as_ref(), "V"), + CmdOption::new(crate::t!("make objects Invisible").as_ref(), "I"), + CmdOption::new(crate::t!("Select state").as_ref(), "S"), + ], + } + } + + fn wants_text_input(&self) -> bool { + true + } + + fn input_kind(&self) -> InputKind { + match self.step { + Step::Action(..) => InputKind::SingleToken, + _ => InputKind::FreeText, + } + } + + fn on_text_input(&mut self, text: &str) -> Option { + let text = text.trim(); + match &self.step { + Step::Parameter if text.is_empty() => Some(CmdResult::Cancel), + Step::Parameter => { + let names: Vec = self.parameters.iter().map(|(n, _)| n.clone()).collect(); + let name = Self::known(&names, text).unwrap_or_else(|| text.to_string()); + self.step = Step::State(name); + Some(CmdResult::NeedPoint) + } + Step::State(_) if text.is_empty() => Some(CmdResult::NeedPoint), + Step::State(parameter) => { + let parameter = parameter.clone(); + let state = + Self::known(&self.states(¶meter), text).unwrap_or_else(|| text.to_string()); + self.step = Step::Action(parameter, state); + Some(CmdResult::NeedPoint) + } + Step::Action(parameter, state) => { + let keyword = text.trim_start_matches('_').to_ascii_uppercase(); + let action = match keyword.as_str() { + "" | "A" | "ADD" => "ADD", + "R" | "REMOVE" => "REMOVE", + "V" | "VISIBLE" => "VISIBLE", + "I" | "INVISIBLE" => "INVISIBLE", + "S" | "SELECT" | "ST" | "STATE" => "SELECT", + _ => { + return Some(CmdResult::ReportError( + crate::t!("Invalid option keyword.").into_owned(), + )) + } + }; + Some(Self::done(&[parameter, state, action])) + } + } + } + + fn on_point(&mut self, _pt: DVec3) -> CmdResult { + CmdResult::NeedPoint + } + + fn on_entity_pick(&mut self, _handle: Handle, _pt: DVec3) -> CmdResult { + CmdResult::NeedPoint + } + + fn on_enter(&mut self) -> CmdResult { + self.on_text_input("").unwrap_or(CmdResult::Cancel) + } +} + +inventory::submit!(crate::command::CommandRegistration { + names: &["VISIBILITYSTATES"] +}); + +#[cfg(test)] +mod tests { + use super::*; + + fn command() -> VisibilityStatesCommand { + VisibilityStatesCommand::new(vec![("LAMP".into(), vec!["On".into(), "Off".into()])]) + } + + fn dispatched(result: Option) -> Vec { + match result { + Some(CmdResult::Dispatch(command)) => command.split(SEP).map(str::to_string).collect(), + _ => panic!("the command hands nothing over"), + } + } + + #[test] + fn known_names_take_their_own_case_and_the_action_defaults_to_add() { + let mut command = command(); + assert!(command.prompt().contains("[LAMP]"), "{}", command.prompt()); + command.on_text_input("lamp"); + assert!( + command.prompt().contains("[On/Off]"), + "{}", + command.prompt() + ); + command.on_text_input("off"); + assert_eq!( + dispatched(command.on_text_input("")), + ["_VISIBILITYSTATES", "LAMP", "Off", "ADD"] + ); + } + + #[test] + fn new_names_and_each_action_keyword() { + for (keyword, action) in [ + ("_A", "ADD"), + ("R", "REMOVE"), + ("v", "VISIBLE"), + ("_Invisible", "INVISIBLE"), + ("S", "SELECT"), + ] { + let mut command = command(); + command.on_text_input("Label"); + command.on_text_input("Shown"); + assert_eq!( + dispatched(command.on_text_input(keyword)), + ["_VISIBILITYSTATES", "Label", "Shown", action] + ); + } + let mut command = command(); + command.on_text_input("LAMP"); + command.on_text_input("On"); + assert!(matches!( + command.on_text_input("X"), + Some(CmdResult::ReportError(_)) + )); + } +} diff --git a/src/scene/bricscad_parameters.rs b/src/scene/bricscad_parameters.rs index 434466ba26..8f58a6997f 100644 --- a/src/scene/bricscad_parameters.rs +++ b/src/scene/bricscad_parameters.rs @@ -24,9 +24,12 @@ use document::objects::ObjectType; use document::{Document, EntityType, Handle}; +mod author; pub(crate) mod record; mod switch; +pub(crate) use author::{parameter_states, Action}; + pub(crate) use switch::can_switch; use record::{Properties, Record}; @@ -60,6 +63,14 @@ pub fn reference_parameters(document: &Document, insert: Handle) -> Vec Option { + visibility_parameters(document, owner) + .into_iter() + .find(|parameter| parameter.name.eq_ignore_ascii_case(name)) + .and_then(|parameter| parameter.states.get(parameter.current?).cloned()) +} + /// The block an anonymous copy of a BricsCAD parametric block was made from. pub fn original_block(document: &Document, block: Handle) -> Option { let manager = database_entry(document, block, "PERSIDMANAGER")?; @@ -179,3 +190,6 @@ mod record_tests; #[cfg(test)] mod switch_tests; + +#[cfg(test)] +pub(crate) mod author_tests; diff --git a/src/scene/bricscad_parameters/author.rs b/src/scene/bricscad_parameters/author.rs new file mode 100644 index 0000000000..8ac55fc9eb --- /dev/null +++ b/src/scene/bricscad_parameters/author.rs @@ -0,0 +1,2156 @@ +//! VISIBILITYSTATES: authoring the visibility states of a BricsCAD +//! parametric block in model space of the block's own drawing, stored the way +//! BricsCAD stores them. (A block definition stores them the same way, but +//! the anonymous copies its references show would keep the states they had, +//! so the command offers model space only.) +//! +//! BricsCAD keeps, per owner (model space or block definition): +//! +//! - per visibility parameter a configuration feature with a table: one row +//! per state, one column (`look_n`) per group of objects the parameter +//! rules, 1 where the group shows in that state; +//! - per group of objects that show and hide together a suppression feature +//! whose variable is `1 - ` the product of the group's columns, one per +//! parameter that rules the group, in parameter order; +//! - the variables of all of them in the owner's associative network, and a +//! dependency and a `BDMOBJECT` per object. +//! +//! An action on objects changes, for each object, the pattern of states in +//! which the parameter shows it: +//! +//! - Add and Visible on an object the parameter does not rule: only in the +//! state; Invisible: in every state but that one; Add on one it rules +//! changes nothing; +//! - Visible and Invisible on one it rules: set or clear the state; +//! - Remove: the parameter no longer rules it. +//! +//! Objects whose patterns now agree with a group's join it. When all members +//! of a group change alike the group changes in place; otherwise the changed +//! ones leave it. A group left with no member, or ruled by no parameter, goes +//! with its columns. A new state starts with every group hidden. After every +//! action the owner shows its current states again. All of this is what +//! BricsCAD V26 does for the same commands. + +use std::collections::{BTreeMap, BTreeSet}; + +use document::objects::{ + AssocAction, AssocActionDependency, AssocDependency, AssocEvalValue, AssocEvalVariant, + AssocNetwork, AssocValueDependency, AssocVariable, AssocVariableDependency, AssociativeData, + AssociativeObject, Dictionary, ObjectType, +}; +use document::{Document, DxfVersion, EntityType, Handle}; +use rustc_hash::{FxHashMap, FxHashSet}; + +use super::record::{Body, Properties, Record, Ref, Value}; +use super::switch::{apply_states, set_variable, store, unknown, SUPPRESS_LAYER}; +use super::{database_entry, features, record as read_record}; +use crate::scene::Scene; + +/// What VISIBILITYSTATES does to the picked objects. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Action { + Add, + Remove, + Visible, + Invisible, + /// Make the state current. + Select, +} + +const UNSUPPORTED: &str = "The visibility states here cannot be edited."; +const OLD_FORMAT: &str = "Visibility states need a drawing in DWG 2010 format or later."; +const NO_PARAMETER: &str = "No visibility parameter of that name."; +const NO_STATE: &str = "No visibility state of that name."; +const BAD_NAME: &str = "Enter a name of letters, digits and underscores."; +const NAME_TAKEN: &str = "That name is used by another variable."; +const NO_OBJECTS: &str = "Select objects of the space being edited."; + +type Result = std::result::Result; + +/// The classes of BricsCAD's objects, as BricsCAD V26 registers them. +const CLASSES: &[(&str, &str, &str)] = &[ + ( + "BDMDBFEATUREMANAGER", + "BdmDbFeatureManager", + "BricsCAD|Description: features data", + ), + ( + "BDMDBFEATUREDATA", + "BdmDbFeatureData", + "BricsCAD|Description: features data", + ), + ( + "BDMDBCONFIGURATIONTABLE", + "BdmDbConfigurationTable", + "BricsCAD|Description: configurations data", + ), + ( + "BDMDBCONFIGVARREACTOR", + "BdmDbConfigVarReactor", + "BricsCAD|Description: features reactor", + ), + ( + "BDMDBPERSIDREACTOR", + "BdmDbPersIdReactor", + "BricsCAD|Description: features reactor", + ), + ( + "BdmDbPersIdManager", + "BdmDbPersIdManager", + "BricsCAD|Description: model data", + ), + ( + "BDMDBCONSTRAINTMANAGER", + "BdmDbConstraintManager", + "BricsCAD|Description: 3D constraints data", + ), + ( + "BDMOBJECT", + "BdmDbObject", + "BdmModule|Description: Driving Dimension", + ), + ( + "BDMDBOBJECTDEPENDENCY", + "BdmDbObjectDependency", + "BricsCAD|Description: 3D constraints data", + ), + ( + "BDMDBEXPRESSIONREACTOR", + "BdmDbExpressionReactor", + "BricsCAD|Description: features reactor", + ), +]; + +/// The names BricsCAD gives suppressions and objects, and the description of +/// a column, in the language of its interface. A drawing that has some keeps +/// its own. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Naming { + pub(crate) suppression: &'static str, + pub(crate) description: &'static str, + pub(crate) object: &'static str, +} + +impl Naming { + pub(crate) const ENGLISH: Self = Self { + suppression: "Suppress_", + description: "controlling visibility of entities in ", + object: "Entity_", + }; + pub(crate) const GERMAN: Self = Self { + suppression: "Unterdrücken_", + description: "Steuerung der Sichtbarkeit von Objekten in ", + object: "Objekt_", + }; + + /// The names for the interface language `tag` (`de-DE`, …). + pub(crate) fn for_language(tag: &str) -> Self { + if tag.to_ascii_lowercase().starts_with("de") { + Self::GERMAN + } else { + Self::ENGLISH + } + } +} + +/// The visibility parameters of an owner, with their states, for the prompts. +pub(crate) fn parameter_states(document: &Document, owner: Handle) -> Vec<(String, Vec)> { + Setup::read(document, owner) + .map(|setup| { + setup + .parameters + .into_iter() + .map(|parameter| (parameter.name, parameter.states)) + .collect() + }) + .unwrap_or_default() +} + +impl Scene { + /// VISIBILITYSTATES on `owner` (model space or a block definition): apply + /// `action` in `state` of `parameter` to `objects`, making the parameter + /// and the state when they are new. Names match regardless of case. On an + /// error the document may be part-way changed; callers work on a copy or + /// take an undo snapshot first. + pub(crate) fn edit_bricscad_visibility( + &mut self, + owner: Handle, + parameter: &str, + state: &str, + action: Action, + objects: &[Handle], + ) -> Result<()> { + let language = crate::i18n::loader() + .current_languages() + .into_iter() + .next() + .map(|language| language.to_string()) + .unwrap_or_default(); + let naming = Naming::for_language(&language); + self.edit_bricscad_visibility_named(owner, parameter, state, action, objects, naming) + } + + /// [`Self::edit_bricscad_visibility`] with the names for a drawing that has + /// none yet. + pub(crate) fn edit_bricscad_visibility_named( + &mut self, + owner: Handle, + parameter: &str, + state: &str, + action: Action, + objects: &[Handle], + naming: Naming, + ) -> Result<()> { + if self.document.version < DxfVersion::AC1024 { + return Err(OLD_FORMAT); + } + // What the editor holds goes into the drawing first, so the reload at + // the end loses nothing. + self.sync_native_parametric_graph(); + let document = &self.document; + let layers = original_layers(document, owner); + let mut setup = Setup::read(document, owner)?; + setup.learn_names(document, naming); + let parameter = parameter.trim(); + let state = state.trim(); + if state.is_empty() { + return Err(NO_STATE); + } + let p = match setup + .parameters + .iter() + .position(|p| p.name.eq_ignore_ascii_case(parameter)) + { + Some(p) => p, + None if matches!(action, Action::Select | Action::Remove) => return Err(NO_PARAMETER), + None => { + if !valid_name(parameter) { + return Err(BAD_NAME); + } + if setup + .variable_names(document) + .contains(¶meter.to_lowercase()) + { + return Err(NAME_TAKEN); + } + setup.parameters.push(Parameter::new(parameter)); + setup.parameters.len() - 1 + } + }; + let s = match setup.parameters[p] + .states + .iter() + .position(|s| s.eq_ignore_ascii_case(state)) + { + Some(s) => s, + None if matches!(action, Action::Select | Action::Remove) => return Err(NO_STATE), + None => setup.parameters[p].add_state(state), + }; + if action == Action::Select { + setup.parameters[p].current = s; + } else { + // BricsCAD works through a selection from its last object. + let mut seen = FxHashSet::default(); + let objects: Vec = objects + .iter() + .rev() + .copied() + .filter(|handle| { + seen.insert(*handle) + && document + .get_entity(*handle) + .is_some_and(|entity| entity.common().owner_handle == owner) + }) + .collect(); + if objects.is_empty() { + return Err(NO_OBJECTS); + } + setup.act(p, s, action, &objects); + } + if setup.parameters[p].states.is_empty() + || setup.parameters[p].columns.is_empty() && setup.parameters[p].feature.is_none() + { + // A new parameter that came to rule nothing is not made. + return Err(NO_OBJECTS); + } + let states: BTreeMap = setup + .parameters + .iter() + .map(|parameter| { + ( + parameter.name.clone(), + parameter.states[parameter.current.min(parameter.states.len() - 1)].clone(), + ) + }) + .collect(); + setup.write(&mut self.document)?; + let members = owner_members(&self.document, owner); + apply_states( + &mut self.document, + owner, + &members, + &layers, + &states, + &BTreeSet::new(), + )?; + number_keys(&mut self.document, owner)?; + self.load_named_parameters_from_document(); + self.load_parametric_constraints_from_document(); + Ok(()) + } +} + +/// Give each parameter's key the number of the state it shows. BricsCAD +/// shows the state of that number again when it next evaluates the owner; +/// its own state selection leaves the number behind, so the next edit there +/// jumps back to an earlier state. +fn number_keys(document: &mut Document, owner: Handle) -> Result<()> { + for feature in features(document, owner) { + let Some(properties) = super::properties(document, feature) else { + continue; + }; + if properties.text("Feature_type") != Some("BdmConfigurationFeature") + || properties.text("TableType") != Some("VisibilityStates") + { + continue; + } + let states: Vec = properties + .get("ConfigTable") + .and_then(Value::object) + .and_then(|table| super::properties(document, table)) + .and_then(|table| { + table + .get("KeyValues")? + .items()? + .iter() + .map(|state| state.text().map(str::to_string)) + .collect() + }) + .ok_or(UNSUPPORTED)?; + let reactors: Vec = properties + .get("Reactors") + .and_then(Value::items) + .map(|items| items.iter().filter_map(Value::object).collect()) + .unwrap_or_default(); + for reactor in reactors { + let mut record = read_record(document, reactor).ok_or(UNSUPPORTED)?; + let properties = record.body.properties_mut(); + if properties.get("IsKeyVar") != Some(&Value::Flag(true)) { + continue; + } + let Some(row) = properties + .text("String") + .and_then(|state| states.iter().position(|name| name == state)) + else { + continue; + }; + let variable = properties + .get("VarId") + .and_then(Value::object) + .ok_or(UNSUPPORTED)?; + properties.set("Value", Value::Real(row as f64)); + store(document, &record); + let value = match variable_value(document, variable).value { + AssocEvalValue::Long(_) => AssocEvalVariant { + code: 90, + value: AssocEvalValue::Long(row as i32), + }, + _ => AssocEvalVariant { + code: 40, + value: AssocEvalValue::Real(row as f64), + }, + }; + set_variable(document, variable, None, value)?; + } + } + Ok(()) +} + +/// Every member of `owner`, in drawing order. +fn owner_members(document: &Document, owner: Handle) -> Vec { + document + .entities() + .filter(|entity| { + entity.common().owner_handle == owner + && !matches!(entity, EntityType::Block(_) | EntityType::BlockEnd(_)) + }) + .map(|entity| entity.common().handle) + .collect() +} + +/// Each member's layer as it is when no state hides it: a member on +/// `*SUPPRESS` takes the layer its suppression keeps for it. +fn original_layers(document: &Document, owner: Handle) -> FxHashMap { + let mut kept: FxHashMap = FxHashMap::default(); + for feature in features(document, owner) { + let Some(properties) = super::properties(document, feature) else { + continue; + }; + if let Some(entries) = properties.get("aEntLayerKey").and_then(Value::entries) { + for (entity, layer) in entries { + if let (Some(entity), Some(layer)) = (entity.object(), layer.object()) { + kept.insert(entity, layer); + } + } + } + } + let layer_name = |handle: Handle| { + document + .layers + .iter() + .find(|layer| layer.handle == handle) + .map(|layer| layer.name.clone()) + }; + owner_members(document, owner) + .into_iter() + .filter_map(|member| { + let layer = &document.get_entity(member)?.common().layer; + let layer = if layer == SUPPRESS_LAYER { + kept.get(&member) + .and_then(|handle| layer_name(*handle)) + .unwrap_or_else(|| "0".to_string()) + } else { + layer.clone() + }; + Some((member, layer)) + }) + .collect() +} + +/// Letters (any script), digits and underscores, not starting with a digit. +fn valid_name(name: &str) -> bool { + let mut chars = name.chars(); + chars + .next() + .is_some_and(|first| first.is_alphabetic() || first == '_') + && chars.all(|c| c.is_alphanumeric() || c == '_') +} + +/// One column of a parameter's table: a group's pattern under it. +#[derive(Debug, Clone)] +struct Column { + name: String, + values: Vec, + reactor: Option, + variable: Option, +} + +#[derive(Debug, Clone)] +struct Parameter { + name: String, + states: Vec, + current: usize, + columns: Vec, + feature: Option, + table: Option, + key_reactor: Option, + key_variable: Option, +} + +impl Parameter { + fn new(name: &str) -> Self { + Self { + name: name.to_string(), + states: Vec::new(), + current: 0, + columns: Vec::new(), + feature: None, + table: None, + key_reactor: None, + key_variable: None, + } + } + + /// A new state, in which every group is hidden. + fn add_state(&mut self, name: &str) -> usize { + self.states.push(name.to_string()); + for column in &mut self.columns { + column.values.push(false); + } + self.states.len() - 1 + } +} + +#[derive(Debug, Clone)] +struct Member { + entity: Handle, + dependency: Option, +} + +#[derive(Debug, Clone)] +struct Group { + name: String, + /// The columns the suppression multiplies: parameter index and column + /// name, in parameter order. + columns: Vec<(usize, String)>, + members: Vec, + feature: Option, + persid: Option, + expression: Option, + variable: Option, + /// The name of the group's variable; BricsCAD's own drawings have groups + /// whose variable is named after another group (`Unterdrücken_1` with + /// the variable `Unterdrücken_7`). + variable_name: String, + columns_changed: bool, +} + +/// Per parameter, the states a group shows in. +type Signature = BTreeMap>; + +/// One owner's visibility parameters and groups, read from its objects and +/// written back. +struct Setup { + owner: Handle, + parameters: Vec, + groups: Vec, + /// Columns, groups and dependencies that go, by their objects. + erased_columns: Vec, + erased_groups: Vec, + released: Vec, + suppress_prefix: Option, + description_prefix: Option, + object_prefix: Option, + /// The lowercased names of the network's variables that are no + /// parameter's, column's or group's. + foreign: FxHashSet, +} + +impl Setup { + fn read(document: &Document, owner: Handle) -> Result { + let mut setup = Self { + owner, + parameters: Vec::new(), + groups: Vec::new(), + erased_columns: Vec::new(), + erased_groups: Vec::new(), + released: Vec::new(), + suppress_prefix: None, + description_prefix: None, + object_prefix: None, + foreign: FxHashSet::default(), + }; + let variable = |handle: Handle| match document.objects.get(&handle) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + })) => Some(variable), + _ => None, + }; + let handles = |properties: &Properties, name: &str| -> Vec { + properties + .get(name) + .and_then(Value::items) + .map(|items| items.iter().filter_map(Value::object).collect()) + .unwrap_or_default() + }; + let mut suppressions = Vec::new(); + for feature in features(document, owner) { + let properties = super::properties(document, feature).ok_or(UNSUPPORTED)?; + match properties.text("Feature_type") { + Some("BdmConfigurationFeature") => { + if properties.text("TableType") != Some("VisibilityStates") { + return Err(UNSUPPORTED); + } + let table_handle = properties + .get("ConfigTable") + .and_then(Value::object) + .ok_or(UNSUPPORTED)?; + let table = super::properties(document, table_handle).ok_or(UNSUPPORTED)?; + let texts = |key: &str| -> Option> { + table + .get(key)? + .items()? + .iter() + .map(|item| item.text().map(str::to_string)) + .collect() + }; + let states = texts("KeyValues").ok_or(UNSUPPORTED)?; + let names = texts("ColNames").ok_or(UNSUPPORTED)?; + let values: Vec = table + .get("DblValues") + .and_then(Value::items) + .and_then(|items| { + items + .iter() + .map(|item| match item { + Value::Real(value) => Some(*value), + _ => None, + }) + .collect() + }) + .ok_or(UNSUPPORTED)?; + if values.len() != states.len() * names.len() { + return Err(UNSUPPORTED); + } + let mut reactors: FxHashMap = FxHashMap::default(); + let mut key = None; + for reactor in handles(&properties, "Reactors") { + let reactor_properties = + super::properties(document, reactor).ok_or(UNSUPPORTED)?; + let variable = reactor_properties + .get("VarId") + .and_then(Value::object) + .ok_or(UNSUPPORTED)?; + if reactor_properties.get("IsKeyVar") == Some(&Value::Flag(true)) { + key = Some((reactor, variable)); + } else { + let name = reactor_properties + .text("VarName") + .ok_or(UNSUPPORTED)? + .to_string(); + reactors.insert(name, (reactor, variable)); + } + } + let (key_reactor, key_variable) = key.ok_or(UNSUPPORTED)?; + let columns = names + .iter() + .enumerate() + .map(|(c, name)| { + let (reactor, variable) = reactors.get(name).ok_or(UNSUPPORTED)?; + if setup.description_prefix.is_none() { + setup.description_prefix = description_prefix(document, *variable); + } + Ok(Column { + name: name.clone(), + values: (0..states.len()) + .map(|row| values[row * names.len() + c] != 0.0) + .collect(), + reactor: Some(*reactor), + variable: Some(*variable), + }) + }) + .collect::>>()?; + let name = table + .text("KeyName") + .or_else(|| properties.text("Name")) + .ok_or(UNSUPPORTED)? + .to_string(); + let current = properties + .text("LastKeyValue") + .and_then(|shown| states.iter().position(|state| state == shown)) + .unwrap_or(0); + setup.parameters.push(Parameter { + name, + states, + current, + columns, + feature: Some(feature), + table: Some(table_handle), + key_reactor: Some(key_reactor), + key_variable: Some(key_variable), + }); + } + Some("BdmSuppressFeature") => suppressions.push((feature, properties)), + // Model space of a drawing also holds the entries of block + // references; they are not this owner's parameters. + _ => {} + } + } + for (feature, properties) in suppressions { + let name = properties.text("Name").ok_or(UNSUPPORTED)?.to_string(); + let mut persid = None; + let mut expression = None; + let mut members = Vec::new(); + let mut suppress_variable = None; + for reactor in handles(&properties, "Reactors") { + let reactor_properties = super::properties(document, reactor).ok_or(UNSUPPORTED)?; + if reactor_properties.get("pers_ids").is_some() { + persid = Some(reactor); + for dependency in handles(&reactor_properties, "pers_ids") { + match read_record(document, dependency).map(|record| record.body) { + Some(Body::Dependency { entity, .. }) => members.push(Member { + entity: entity.handle, + dependency: Some(dependency), + }), + _ => return Err(UNSUPPORTED), + } + } + } else if let Some(variable) = reactor_properties.get("var").and_then(Value::object) + { + expression = Some(reactor); + suppress_variable = Some(variable); + } + } + let variable_handle = suppress_variable.ok_or(UNSUPPORTED)?; + let expression_text = &variable(variable_handle).ok_or(UNSUPPORTED)?.expression; + let factors: Vec = expression_text + .split_once('-') + .filter(|(one, _)| one.trim() == "1") + .map(|(_, product)| product.split('*').map(|f| f.trim().to_string()).collect()) + .ok_or(UNSUPPORTED)?; + let mut columns = Vec::new(); + for factor in factors { + let p = setup + .parameters + .iter() + .position(|p| p.columns.iter().any(|c| c.name == factor)) + .ok_or(UNSUPPORTED)?; + columns.push((p, factor)); + } + if setup.suppress_prefix.is_none() { + setup.suppress_prefix = name + .rsplit_once('_') + .filter(|(_, n)| n.parse::().is_ok()) + .map(|(prefix, _)| format!("{prefix}_")); + } + setup.groups.push(Group { + name, + columns, + members, + feature: Some(feature), + persid: Some(persid.ok_or(UNSUPPORTED)?), + expression: Some(expression.ok_or(UNSUPPORTED)?), + variable: Some(variable_handle), + variable_name: variable(variable_handle).ok_or(UNSUPPORTED)?.name.clone(), + columns_changed: false, + }); + } + // Each column belongs to one group. + let mut used = FxHashSet::default(); + for group in &setup.groups { + for (_, column) in &group.columns { + if !used.insert(column.clone()) { + return Err(UNSUPPORTED); + } + } + } + if let Some(network) = owner_network(document, owner) { + let managed = setup.taken(); + setup.foreign = document + .objects + .values() + .filter_map(|object| match object { + ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + }) if variable.action.owning_network == network => { + Some(variable.name.to_lowercase()) + } + _ => None, + }) + .filter(|name| !managed.contains(name)) + .collect(); + } + Ok(setup) + } + + /// Fill in the names the owner does not show: from the rest of the + /// drawing, else `naming`. + fn learn_names(&mut self, document: &Document, naming: Naming) { + if self.object_prefix.is_none() { + self.object_prefix = document.objects.iter().find_map(|(handle, object)| { + matches!(object, ObjectType::Unknown { type_name, .. } if type_name == "BDMOBJECT") + .then(|| read_record(document, *handle)) + .flatten() + .and_then(|record| { + let name = record.body.properties().text("NAME")?.to_string(); + let (prefix, number) = name.rsplit_once('_')?; + number.parse::().ok()?; + Some(format!("{prefix}_")) + }) + }); + } + if self.suppress_prefix.is_none() || self.description_prefix.is_none() { + for (handle, object) in &document.objects { + if !matches!(object, ObjectType::Unknown { type_name, .. } if type_name == "BDMDBFEATUREDATA") + { + continue; + } + let Some(properties) = super::properties(document, *handle) else { + continue; + }; + if properties.text("Feature_type") != Some("BdmSuppressFeature") { + continue; + } + let Some(name) = properties.text("Name") else { + continue; + }; + if self.suppress_prefix.is_none() { + self.suppress_prefix = name + .rsplit_once('_') + .filter(|(_, n)| n.parse::().is_ok()) + .map(|(prefix, _)| format!("{prefix}_")); + } + if self.description_prefix.is_none() { + self.description_prefix = + document.objects.values().find_map(|object| match object { + ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + }) => variable + .description + .strip_suffix(name) + .filter(|prefix| !prefix.is_empty()) + .map(str::to_string), + _ => None, + }); + } + if self.suppress_prefix.is_some() && self.description_prefix.is_some() { + break; + } + } + } + self.suppress_prefix + .get_or_insert_with(|| naming.suppression.to_string()); + self.description_prefix + .get_or_insert_with(|| naming.description.to_string()); + self.object_prefix + .get_or_insert_with(|| naming.object.to_string()); + } + + /// The lowercased names of the owner's variables. + /// The lowercased names a new column or group may not take: every + /// variable of the network but those this edit erases. + fn taken(&self) -> FxHashSet { + self.parameters + .iter() + .flat_map(|p| { + std::iter::once(p.name.to_lowercase()) + .chain(p.columns.iter().map(|c| c.name.to_lowercase())) + }) + .chain( + self.groups + .iter() + .flat_map(|g| [g.name.to_lowercase(), g.variable_name.to_lowercase()]), + ) + .chain(self.foreign.iter().cloned()) + .collect() + } + + fn variable_names(&self, document: &Document) -> FxHashSet { + let mut names: FxHashSet = self + .parameters + .iter() + .flat_map(|p| { + std::iter::once(p.name.to_lowercase()) + .chain(p.columns.iter().map(|c| c.name.to_lowercase())) + }) + .chain(self.groups.iter().map(|g| g.name.to_lowercase())) + .collect(); + if let Some(network) = owner_network(document, self.owner) { + for object in document.objects.values() { + if let ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + }) = object + { + if variable.action.owning_network == network { + names.insert(variable.name.to_lowercase()); + } + } + } + } + names + } + + fn signature(&self, group: usize) -> Signature { + self.groups[group] + .columns + .iter() + .map(|(p, name)| { + let values = self.parameters[*p] + .columns + .iter() + .find(|column| &column.name == name) + .map(|column| column.values.clone()) + .unwrap_or_default(); + (*p, values) + }) + .collect() + } + + fn group_of(&self, entity: Handle) -> Option { + self.groups + .iter() + .position(|group| group.members.iter().any(|member| member.entity == entity)) + } + + /// Apply `action` in state `s` of parameter `p` to `objects`. + fn act(&mut self, p: usize, s: usize, action: Action, objects: &[Handle]) { + let states = self.parameters[p].states.len(); + let mut changes: Vec<(Option, Signature, Handle)> = Vec::new(); + for &entity in objects { + let group = self.group_of(entity); + let old = group.map(|g| self.signature(g)).unwrap_or_default(); + let mut new = old.clone(); + match (old.get(&p), action) { + (Some(_), Action::Add) | (None, Action::Remove) | (_, Action::Select) => {} + (Some(_), Action::Remove) => { + new.remove(&p); + } + (Some(pattern), Action::Visible | Action::Invisible) => { + let mut pattern = pattern.clone(); + pattern[s] = action == Action::Visible; + new.insert(p, pattern); + } + (None, Action::Add | Action::Visible) => { + new.insert(p, (0..states).map(|k| k == s).collect()); + } + (None, Action::Invisible) => { + new.insert(p, (0..states).map(|k| k != s).collect()); + } + } + if new != old { + changes.push((group, new, entity)); + } + } + // Objects of one group that change alike change together. + let mut batches: Vec<(Option, Signature, Vec)> = Vec::new(); + for (group, signature, entity) in changes { + match batches + .iter_mut() + .find(|(g, sig, _)| *g == group && *sig == signature) + { + Some((_, _, entities)) => entities.push(entity), + None => batches.push((group, signature, vec![entity])), + } + } + for (group, signature, entities) in batches { + let whole = group.is_some_and(|g| { + let members: BTreeSet = + self.groups[g].members.iter().map(|m| m.entity).collect(); + members == entities.iter().copied().collect::>() + }); + match group { + Some(g) if whole => self.reshape(g, &signature), + _ => { + let mut moved: Vec = Vec::new(); + if let Some(g) = group { + let members = std::mem::take(&mut self.groups[g].members); + let (leaving, staying): (Vec<_>, Vec<_>) = members + .into_iter() + .partition(|member| entities.contains(&member.entity)); + self.groups[g].members = staying; + moved = leaving; + } + for entity in &entities { + if !moved.iter().any(|member| member.entity == *entity) { + moved.push(Member { + entity: *entity, + dependency: None, + }); + } + } + if signature.is_empty() { + self.released + .extend(moved.iter().filter_map(|member| member.dependency)); + continue; + } + let target = (0..self.groups.len()).find(|&h| { + !self.groups[h].members.is_empty() && self.signature(h) == signature + }); + match target { + Some(h) => self.groups[h].members.extend(moved), + None => self.add_group(&signature, moved), + } + } + } + } + // Groups left with no member go. + let mut g = 0; + while g < self.groups.len() { + if self.groups[g].members.is_empty() { + self.erase_group(g); + } else { + g += 1; + } + } + } + + /// Change group `g` to `signature` in place. + fn reshape(&mut self, g: usize, signature: &Signature) { + if signature.is_empty() { + let members = std::mem::take(&mut self.groups[g].members); + self.released + .extend(members.into_iter().filter_map(|member| member.dependency)); + return; + } + for (&p, pattern) in signature { + let existing = self.groups[g] + .columns + .iter() + .find(|(q, _)| *q == p) + .map(|(_, name)| name.clone()); + match existing { + Some(name) => { + if let Some(column) = self.parameters[p] + .columns + .iter_mut() + .find(|c| c.name == name) + { + column.values = pattern.clone(); + } + } + None => { + let name = self.add_column(p, pattern.clone()); + let group = &mut self.groups[g]; + group.columns.push((p, name)); + group.columns.sort_by_key(|(q, _)| *q); + group.columns_changed = true; + } + } + } + let dropped: Vec<(usize, String)> = self.groups[g] + .columns + .iter() + .filter(|(p, _)| !signature.contains_key(p)) + .cloned() + .collect(); + for (p, name) in dropped { + self.erase_column(p, &name); + self.groups[g].columns.retain(|(_, column)| *column != name); + self.groups[g].columns_changed = true; + } + } + + fn add_group(&mut self, signature: &Signature, members: Vec) { + let prefix = self.suppress_prefix.clone().unwrap_or_default(); + let taken = self.taken(); + let mut number = self + .groups + .iter() + .filter_map(|group| group.name.strip_prefix(&prefix)?.parse::().ok()) + .max() + .unwrap_or(0) + + 1; + // BricsCAD finds variables by name: a second variable of the same + // name gets the two mixed up. + while taken.contains(&format!("{prefix}{number}").to_lowercase()) { + number += 1; + } + let name = format!("{prefix}{number}"); + let columns = signature + .iter() + .map(|(&p, pattern)| (p, self.add_column(p, pattern.clone()))) + .collect(); + self.groups.push(Group { + variable_name: name.clone(), + name, + columns, + members, + feature: None, + persid: None, + expression: None, + variable: None, + columns_changed: true, + }); + } + + /// A new column of parameter `p`, named with the lowest free number. + fn add_column(&mut self, p: usize, values: Vec) -> String { + let taken = self.taken(); + let number = (1..) + .find(|n| !taken.contains(&format!("look_{n}"))) + .unwrap_or(1); + let name = format!("look_{number}"); + self.parameters[p].columns.push(Column { + name: name.clone(), + values, + reactor: None, + variable: None, + }); + name + } + + fn erase_column(&mut self, p: usize, name: &str) { + if let Some(index) = self.parameters[p] + .columns + .iter() + .position(|c| c.name == name) + { + let column = self.parameters[p].columns.remove(index); + self.erased_columns.push(column); + } + } + + fn erase_group(&mut self, g: usize) { + let group = self.groups.remove(g); + for (p, name) in &group.columns { + self.erase_column(*p, name); + } + self.released + .extend(group.members.iter().filter_map(|member| member.dependency)); + self.erased_groups.push(group); + } + + /// Write the setup back into the owner's objects. + fn write(mut self, document: &mut Document) -> Result<()> { + let version = document.version; + let types = Types::ensure(document); + let database = ensure_database(document, self.owner, &types, version)?; + let network = ensure_network(document, self.owner)?; + let description_prefix = self.description_prefix.clone().unwrap_or_default(); + let object_prefix = self.object_prefix.clone().unwrap_or_default(); + let mut new_features = Vec::new(); + + // Columns and groups that go: their variables leave the network + // after the suppressions that read them are rewritten below. + let mut erased_variables: Vec = Vec::new(); + let mut erased_objects: Vec = Vec::new(); + for column in &self.erased_columns { + erased_variables.extend(column.variable); + erased_objects.extend(column.reactor); + } + for group in &self.erased_groups { + erased_variables.extend(group.variable); + erased_objects.extend(group.feature); + erased_objects.extend(group.persid); + erased_objects.extend(group.expression); + } + + // Group names, for the columns' descriptions. + let mut column_group: FxHashMap = FxHashMap::default(); + for group in &self.groups { + for (_, column) in &group.columns { + column_group.insert(column.clone(), group.name.clone()); + } + } + + for parameter in &mut self.parameters { + let current = parameter + .current + .min(parameter.states.len().saturating_sub(1)); + let key_variable = match parameter.key_variable { + Some(variable) => variable, + None => new_variable( + document, + network, + ¶meter.name, + "", + "", + AssocEvalVariant { + code: 40, + value: AssocEvalValue::Real(0.0), + }, + ), + }; + parameter.key_variable = Some(key_variable); + let feature = parameter + .feature + .unwrap_or_else(|| document.allocate_handle()); + let table = parameter + .table + .unwrap_or_else(|| document.allocate_handle()); + if parameter.key_reactor.is_none() { + let handle = document.allocate_handle(); + let record = Record::new( + types.config_reactor, + handle, + Ref::new(feature, 4), + Body::Properties(variable_reactor( + true, + ¶meter.states[current], + 0.0, + key_variable, + ¶meter.name, + )), + version, + ); + document + .objects + .insert(handle, unknown("BDMDBCONFIGVARREACTOR", &record)); + add_reactor(document, key_variable, handle); + parameter.key_reactor = Some(handle); + } + for column in &mut parameter.columns { + let value = column.values.get(current).copied().unwrap_or(false); + let variable = match column.variable { + Some(variable) => variable, + None => { + let group = column_group.get(&column.name).cloned().unwrap_or_default(); + new_variable( + document, + network, + &column.name, + "", + &format!("{description_prefix}{group}"), + AssocEvalVariant { + code: 40, + value: AssocEvalValue::Real(f64::from(u8::from(value))), + }, + ) + } + }; + column.variable = Some(variable); + if column.reactor.is_none() { + let handle = document.allocate_handle(); + let record = Record::new( + types.config_reactor, + handle, + Ref::new(feature, 4), + Body::Properties(variable_reactor( + false, + "", + f64::from(u8::from(value)), + variable, + &column.name, + )), + version, + ); + document + .objects + .insert(handle, unknown("BDMDBCONFIGVARREACTOR", &record)); + add_reactor(document, variable, handle); + column.reactor = Some(handle); + } + } + let table_record = Record::new( + types.table, + table, + Ref::new(feature, 4), + Body::Properties(table_properties(parameter)), + version, + ); + document + .objects + .insert(table, unknown("BDMDBCONFIGURATIONTABLE", &table_record)); + let mut reactors = vec![parameter.key_reactor.unwrap_or_default()]; + reactors.extend(parameter.columns.iter().filter_map(|column| column.reactor)); + let reactors = Value::List { + element: 8, + items: reactors + .into_iter() + .map(|reactor| Value::Object { + kind: 3, + target: Ref::new(reactor, 3), + }) + .collect(), + }; + match parameter.feature { + Some(existing) => { + let mut record = read_record(document, existing).ok_or(UNSUPPORTED)?; + let properties = record.body.properties_mut(); + properties.set("Reactors", reactors); + properties.set( + "LastKeyValue", + Value::Text(parameter.states[current].clone()), + ); + store(document, &record); + } + None => { + let record = Record::new( + types.feature, + feature, + Ref::new(database.features, 4), + Body::Properties(Properties(vec![ + ("_ver".into(), Value::Byte(1)), + ("CloningType".into(), Value::Flag(true)), + ( + "ConfigTable".into(), + Value::Object { + kind: 3, + target: Ref::new(table, 3), + }, + ), + ( + "Feature_type".into(), + Value::Text("BdmConfigurationFeature".into()), + ), + ("FreeConfig".into(), Value::Text("Custom".into())), + ( + "LastKeyValue".into(), + Value::Text(parameter.states[current].clone()), + ), + ("Name".into(), Value::Text(parameter.name.clone())), + ("Reactors".into(), reactors), + ("Status".into(), Value::Integer(1)), + ("TableType".into(), Value::Text("VisibilityStates".into())), + ])), + version, + ); + document + .objects + .insert(feature, unknown("BDMDBFEATUREDATA", &record)); + new_features.push(feature); + parameter.feature = Some(feature); + parameter.table = Some(table); + } + } + } + + // The objects every member needs. + let entity_objects = entity_objects(document, self.owner, database.constraints); + let mut new_objects: Vec = Vec::new(); + let mut new_dependencies: Vec = Vec::new(); + let mut next_object_number = entity_objects + .values() + .filter_map(|object| { + read_record(document, *object)? + .body + .properties() + .text("NAME")? + .strip_prefix(object_prefix.as_str())? + .parse::() + .ok() + }) + .max() + .unwrap_or(0) + + 1; + let mut entity_objects = entity_objects; + + let variables_by_name: FxHashMap = self + .parameters + .iter() + .flat_map(|p| p.columns.iter()) + .filter_map(|column| Some((column.name.clone(), column.variable?))) + .collect(); + for group in &mut self.groups { + let expression = format!( + "1 - {}", + group + .columns + .iter() + .map(|(_, name)| name.as_str()) + .collect::>() + .join(" * ") + ); + let reads: Vec = group + .columns + .iter() + .filter_map(|(_, name)| variables_by_name.get(name).copied()) + .collect(); + let variable = match group.variable { + Some(variable) => { + if group.columns_changed { + set_expression(document, variable, &expression, &reads); + } + variable + } + None => { + let variable = new_variable( + document, + network, + &group.name, + &expression, + "", + AssocEvalVariant { + code: 90, + value: AssocEvalValue::Long(0), + }, + ); + set_expression(document, variable, &expression, &reads); + variable + } + }; + group.variable = Some(variable); + let feature = group.feature.unwrap_or_else(|| document.allocate_handle()); + let persid = group.persid.unwrap_or_else(|| document.allocate_handle()); + let expression_reactor = group + .expression + .unwrap_or_else(|| document.allocate_handle()); + if group.feature.is_none() { + let record = Record::new( + types.feature, + feature, + Ref::new(database.features, 4), + Body::Properties(Properties(vec![ + ("_ver".into(), Value::Byte(1)), + ( + "Feature_type".into(), + Value::Text("BdmSuppressFeature".into()), + ), + ("Name".into(), Value::Text(group.name.clone())), + ( + "Reactors".into(), + Value::List { + element: 8, + items: [persid, expression_reactor] + .into_iter() + .map(|reactor| Value::Object { + kind: 3, + target: Ref::new(reactor, 3), + }) + .collect(), + }, + ), + ("Status".into(), Value::Integer(0)), + ( + "aEntLayerKey".into(), + Value::Map { + key: 8, + value: 8, + entries: Vec::new(), + }, + ), + ])), + version, + ); + document + .objects + .insert(feature, unknown("BDMDBFEATUREDATA", &record)); + new_features.push(feature); + let record = Record::new( + types.expression_reactor, + expression_reactor, + Ref::new(feature, 4), + Body::Properties(Properties(vec![ + ("_ver".into(), Value::Byte(1)), + ("deleteOnErase".into(), Value::Flag(true)), + ("expr".into(), Value::Text("1".into())), + ("prop".into(), Value::Text("suppress".into())), + ("react".into(), Value::Flag(false)), + ("strType".into(), Value::Flag(false)), + ("value".into(), Value::Real(0.0)), + ( + "var".into(), + Value::Object { + kind: 0, + target: Ref::new(variable, 4), + }, + ), + ])), + version, + ); + document.objects.insert( + expression_reactor, + unknown("BDMDBEXPRESSIONREACTOR", &record), + ); + add_reactor(document, variable, expression_reactor); + group.feature = Some(feature); + group.expression = Some(expression_reactor); + } + // Members: a dependency each, on this group's reactor. + let mut dependencies = Vec::with_capacity(group.members.len()); + for member in &mut group.members { + let dependency = match member.dependency { + Some(dependency) => { + let mut record = read_record(document, dependency).ok_or(UNSUPPORTED)?; + if record.reactors.iter().map(|r| r.handle).ne([persid]) { + record.reactors = vec![Ref::new(persid, 4)]; + store(document, &record); + } + dependency + } + None => { + let handle = document.allocate_handle(); + let mut record = Record::new( + types.dependency, + handle, + Ref::new(database.dependencies, 4), + Body::Dependency { + properties: Properties::default(), + tail: 0, + entity: Ref::new(member.entity, 5), + }, + version, + ); + record.reactors = vec![Ref::new(persid, 4)]; + document + .objects + .insert(handle, unknown("BDMDBOBJECTDEPENDENCY", &record)); + new_dependencies.push(handle); + // The member's object lists the dependency. + match entity_objects.get(&member.entity) { + Some(&object) => { + let mut object_record = + read_record(document, object).ok_or(UNSUPPORTED)?; + let Some(Value::List { items, .. }) = object_record + .body + .properties_mut() + .get_mut("PersIdDependencies") + else { + return Err(UNSUPPORTED); + }; + items.push(Value::Object { + kind: 0, + target: Ref::new(handle, 4), + }); + store(document, &object_record); + } + None => { + let object = document.allocate_handle(); + let record = Record::new( + types.object, + object, + Ref::new(database.constraints, 4), + Body::Object { + lead: 5, + lead_count: 0, + entity: Ref::new(member.entity, 4), + properties: Properties(vec![ + ( + "NAME".into(), + Value::Text(format!( + "{object_prefix}{next_object_number}" + )), + ), + ( + "PersIdDependencies".into(), + Value::List { + element: 8, + items: vec![Value::Object { + kind: 0, + target: Ref::new(handle, 4), + }], + }, + ), + ]), + tail: 0, + }, + version, + ); + next_object_number += 1; + document + .objects + .insert(object, unknown("BDMOBJECT", &record)); + new_objects.push(object); + entity_objects.insert(member.entity, object); + if let Some(entity) = document.get_entity_mut(member.entity) { + entity.common_mut().reactors.push(object); + } + } + } + handle + } + }; + member.dependency = Some(dependency); + dependencies.push(dependency); + } + let persid_record = Record::new( + types.persid_reactor, + persid, + Ref::new(feature, 4), + Body::Properties(Properties(vec![ + ("_ver".into(), Value::Byte(1)), + ("mask".into(), Value::Integer(1)), + ( + "pers_ids".into(), + Value::List { + element: 8, + items: dependencies + .iter() + .map(|dependency| Value::Object { + kind: 0, + target: Ref::new(*dependency, 4), + }) + .collect(), + }, + ), + ("tag".into(), Value::Integer(0)), + ])), + version, + ); + match group.persid { + Some(existing) => { + let mut record = read_record(document, existing).ok_or(UNSUPPORTED)?; + record.body = persid_record.body; + store(document, &record); + } + None => { + document + .objects + .insert(persid, unknown("BDMDBPERSIDREACTOR", &persid_record)); + group.persid = Some(persid); + } + } + } + + // Dependencies of objects no group rules any more go; their objects + // stay, as BricsCAD keeps them, with the dependency struck off. + for &dependency in &self.released { + for &object in entity_objects.values() { + let Some(mut record) = read_record(document, object) else { + continue; + }; + if let Some(Value::List { items, .. }) = + record.body.properties_mut().get_mut("PersIdDependencies") + { + let before = items.len(); + items.retain(|item| item.object() != Some(dependency)); + if items.len() != before { + store(document, &record); + } + } + } + erased_objects.push(dependency); + } + + for variable in &erased_variables { + erase_variable(document, network, *variable); + } + for object in &erased_objects { + document.objects.remove(object); + } + let erased: FxHashSet = erased_objects.iter().copied().collect(); + + // The managers list what was added and drop what went. + let mut record = read_record(document, database.features).ok_or(UNSUPPORTED)?; + if let Some(Value::List { items, .. }) = record.body.properties_mut().get_mut("Features") { + items.retain(|item| item.object().is_none_or(|h| !erased.contains(&h))); + items.extend(new_features.iter().map(|feature| Value::Object { + kind: 3, + target: Ref::new(*feature, 3), + })); + } + store(document, &record); + let mut record = read_record(document, database.dependencies).ok_or(UNSUPPORTED)?; + if let Some(Value::List { items, .. }) = record.body.properties_mut().get_mut("deps") { + items.retain(|item| item.object().is_none_or(|h| !erased.contains(&h))); + items.extend(new_dependencies.iter().map(|dependency| Value::Object { + kind: 3, + target: Ref::new(*dependency, 3), + })); + } + store(document, &record); + if !new_objects.is_empty() { + let mut record = read_record(document, database.constraints).ok_or(UNSUPPORTED)?; + let Body::ConstraintManager { + counts, children, .. + } = &mut record.body + else { + return Err(UNSUPPORTED); + }; + let at = usize::try_from(counts[1]).map_err(|_| UNSUPPORTED)?; + for (k, object) in new_objects.iter().enumerate() { + children.insert((at + k).min(children.len()), Ref::new(*object, 3)); + } + counts[1] += new_objects.len() as i32; + store(document, &record); + } + Ok(()) + } +} + +/// The prefix of a column variable's description, the text before the name +/// of the suppression it controls. +fn description_prefix(document: &Document, variable: Handle) -> Option { + let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + })) = document.objects.get(&variable) + else { + return None; + }; + let (prefix, _) = variable.description.rsplit_once(' ')?; + Some(format!("{prefix} ")) +} + +fn table_properties(parameter: &Parameter) -> Properties { + let rows = parameter.states.len(); + let mut values = Vec::with_capacity(rows * parameter.columns.len()); + for row in 0..rows { + for column in ¶meter.columns { + values.push(column.values.get(row).copied().unwrap_or(false)); + } + } + let texts = |items: Vec| Value::List { + element: 2, + items: items.into_iter().map(Value::Text).collect(), + }; + Properties(vec![ + ( + "ColNames".into(), + texts(parameter.columns.iter().map(|c| c.name.clone()).collect()), + ), + ( + "ColNum".into(), + Value::Integer(parameter.columns.len() as i32), + ), + ( + "ColTypes".into(), + Value::List { + element: 3, + items: parameter + .columns + .iter() + .map(|_| Value::Integer(0)) + .collect(), + }, + ), + ( + "DblValues".into(), + Value::List { + element: 4, + items: values + .iter() + .map(|v| Value::Real(f64::from(u8::from(*v)))) + .collect(), + }, + ), + ("KeyName".into(), Value::Text(parameter.name.clone())), + ("KeyType".into(), Value::Integer(1)), + ("KeyValues".into(), texts(parameter.states.clone())), + ("RowNum".into(), Value::Integer(rows as i32)), + ( + "Values".into(), + texts( + values + .iter() + .map(|v| if *v { "1".into() } else { "0".into() }) + .collect(), + ), + ), + ]) +} + +fn variable_reactor( + key: bool, + string: &str, + value: f64, + variable: Handle, + name: &str, +) -> Properties { + Properties(vec![ + ("_ver".into(), Value::Byte(1)), + ("DeleteVarOnErase".into(), Value::Flag(true)), + ("IsEnabled".into(), Value::Flag(true)), + ("IsKeyVar".into(), Value::Flag(key)), + ("IsString".into(), Value::Flag(key)), + ("String".into(), Value::Text(string.to_string())), + ("Value".into(), Value::Real(value)), + ( + "VarId".into(), + Value::Object { + kind: 0, + target: Ref::new(variable, 4), + }, + ), + ("VarName".into(), Value::Text(name.to_string())), + ]) +} + +/// The type numbers of BricsCAD's classes in this drawing. +struct Types { + feature_manager: u16, + feature: u16, + table: u16, + config_reactor: u16, + persid_reactor: u16, + persid_manager: u16, + constraint_manager: u16, + object: u16, + dependency: u16, + expression_reactor: u16, +} + +impl Types { + fn ensure(document: &mut Document) -> Self { + crate::scene::dwg_native_constraints::ensure_associative_classes_registered(document); + let mut number = |dxf: &str| -> u16 { + let (dxf, cpp, application) = CLASSES + .iter() + .find(|(name, ..)| *name == dxf) + .copied() + .unwrap_or((dxf, dxf, "")); + if document.classes.get_by_name(dxf).is_none() { + document.classes.add_or_update(document::classes::DxfClass { + dxf_name: dxf.to_string(), + cpp_class_name: cpp.to_string(), + application_name: application.to_string(), + proxy_flags: document::classes::ProxyFlags(1025), + instance_count: 0, + was_zombie: false, + is_an_entity: false, + class_number: 0, + item_class_id: 0x1F3, + dwg_version: 33, + maintenance_version: 55, + unknown1: 0, + unknown2: 0, + }); + } + document + .classes + .get_by_name(dxf) + .map_or(0, |class| class.class_number as u16) + }; + Self { + feature_manager: number("BDMDBFEATUREMANAGER"), + feature: number("BDMDBFEATUREDATA"), + table: number("BDMDBCONFIGURATIONTABLE"), + config_reactor: number("BDMDBCONFIGVARREACTOR"), + persid_reactor: number("BDMDBPERSIDREACTOR"), + persid_manager: number("BdmDbPersIdManager"), + constraint_manager: number("BDMDBCONSTRAINTMANAGER"), + object: number("BDMOBJECT"), + dependency: number("BDMDBOBJECTDEPENDENCY"), + expression_reactor: number("BDMDBEXPRESSIONREACTOR"), + } + } +} + +struct Database { + features: Handle, + dependencies: Handle, + constraints: Handle, +} + +/// The owner's `BDM_DATABASE` with its three managers, made when missing. +fn ensure_database( + document: &mut Document, + owner: Handle, + types: &Types, + version: DxfVersion, +) -> Result { + if let (Some(features), Some(dependencies), Some(constraints)) = ( + database_entry(document, owner, "FEATURE_MANAGER"), + database_entry(document, owner, "PERSIDMANAGER"), + database_entry(document, owner, "BDM_DATABASE"), + ) { + return Ok(Database { + features, + dependencies, + constraints, + }); + } + let extension = document.ensure_extension_dictionary(owner); + if matches!( + document.objects.get(&extension), + Some(ObjectType::Dictionary(dictionary)) if dictionary.get("BDM_DATABASE").is_some() + ) { + // A database without its three managers is not one this writes into. + return Err(UNSUPPORTED); + } + let [dictionary, features, dependencies, constraints] = + [(); 4].map(|_| document.allocate_handle()); + let mut database = Dictionary::new(); + database.handle = dictionary; + database.owner = extension; + database.reactors = vec![extension]; + database.entries = vec![ + ("FEATURE_MANAGER".into(), features), + ("PERSIDMANAGER".into(), dependencies), + ("BDM_DATABASE".into(), constraints), + ]; + document + .objects + .insert(dictionary, ObjectType::Dictionary(database)); + let managers = [ + ( + "BDMDBFEATUREMANAGER", + types.feature_manager, + features, + Body::Properties(Properties(vec![ + ("_ver".into(), Value::Byte(1)), + ( + "ColorPolicy".into(), + Value::Object { + kind: 3, + target: Ref::new(Handle::NULL, 3), + }, + ), + ( + "Contexts".into(), + Value::List { + element: 8, + items: Vec::new(), + }, + ), + ( + "Features".into(), + Value::List { + element: 8, + items: Vec::new(), + }, + ), + ])), + ), + ( + "BdmDbPersIdManager", + types.persid_manager, + dependencies, + Body::Properties(Properties(vec![ + ("_ver".into(), Value::Byte(1)), + ( + "deps".into(), + Value::List { + element: 8, + items: Vec::new(), + }, + ), + ])), + ), + ( + "BDMDBCONSTRAINTMANAGER", + types.constraint_manager, + constraints, + Body::ConstraintManager { + counts: [2, 0, 0, 0, 0], + children: Vec::new(), + settings: Properties(vec![( + "DesignIntentSettings".into(), + Value::Text("DISABLE_HEURISTIC_BODY_FIX".into()), + )]), + }, + ), + ]; + for (class, object_type, handle, body) in managers { + let mut record = Record::new(object_type, handle, Ref::new(dictionary, 4), body, version); + record.reactors = vec![Ref::new(dictionary, 4)]; + document.objects.insert(handle, unknown(class, &record)); + } + if let Some(ObjectType::Dictionary(extension)) = document.objects.get_mut(&extension) { + extension.add_entry("BDM_DATABASE", dictionary); + } + Ok(Database { + features, + dependencies, + constraints, + }) +} + +/// The owner's associative network. +fn owner_network(document: &Document, owner: Handle) -> Option { + let dictionary = |handle: Handle| match document.objects.get(&handle)? { + ObjectType::Dictionary(dictionary) => Some(dictionary), + _ => None, + }; + let extension = dictionary(document.extension_dictionary_handle(owner)?)?; + let mut network = extension.get("ACAD_ASSOCNETWORK")?; + while let Some(inner) = dictionary(network) { + network = inner.get("ACAD_ASSOCNETWORK")?; + } + matches!( + document.objects.get(&network), + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Network(_), + .. + })) + ) + .then_some(network) +} + +/// The owner's associative network, made and attached to the drawing's root +/// network when missing. +fn ensure_network(document: &mut Document, owner: Handle) -> Result { + if let Some(network) = owner_network(document, owner) { + return Ok(network); + } + let extension = document.ensure_extension_dictionary(owner); + if matches!( + document.objects.get(&extension), + Some(ObjectType::Dictionary(dictionary)) if dictionary.get("ACAD_ASSOCNETWORK").is_some() + ) { + return Err(UNSUPPORTED); + } + let [dictionary, network] = [(); 2].map(|_| document.allocate_handle()); + let mut holder = Dictionary::new(); + holder.handle = dictionary; + holder.owner = extension; + holder.reactors = vec![extension]; + holder.entries = vec![("ACAD_ASSOCNETWORK".into(), network)]; + document + .objects + .insert(dictionary, ObjectType::Dictionary(holder)); + document.objects.insert( + network, + ObjectType::Associative(AssociativeObject { + handle: network, + owner: dictionary, + reactors: vec![dictionary], + dxf_name: "ACDBASSOCNETWORK".into(), + cpp_class_name: "AcDbAssocNetwork".into(), + data: AssociativeData::Network(AssocNetwork { + action: AssocAction { + class_version: 2, + ..Default::default() + }, + ..Default::default() + }), + ..Default::default() + }), + ); + if let Some(ObjectType::Dictionary(extension)) = document.objects.get_mut(&extension) { + extension.add_entry("ACAD_ASSOCNETWORK", dictionary); + } + let mut networks = FxHashMap::default(); + networks.insert(network, network); + Scene::register_copied_constraint_networks(document, &networks).map_err(|_| UNSUPPORTED)?; + Ok(network) +} + +/// A new variable in `network`, its last action. +fn new_variable( + document: &mut Document, + network: Handle, + name: &str, + expression: &str, + description: &str, + value: AssocEvalVariant, +) -> Handle { + let handle = document.allocate_handle(); + let index = match document.objects.get_mut(&network) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Network(network), + .. + })) => { + network.network_action_index += 1; + network.actions.push(AssocActionDependency { + is_owned: true, + dependency: handle, + }); + network.network_action_index + } + _ => 0, + }; + document.objects.insert( + handle, + ObjectType::Associative(AssociativeObject { + handle, + owner: network, + dxf_name: "ACDBASSOCVARIABLE".into(), + cpp_class_name: "AcDbAssocVariable".into(), + data: AssociativeData::Variable(AssocVariable { + action: AssocAction { + class_version: 2, + owning_network: network, + action_index: index, + ..Default::default() + }, + class_version: 2, + name: name.to_string(), + expression: expression.to_string(), + evaluator: "AcDbCalc:1.0".into(), + description: description.to_string(), + value, + ..Default::default() + }), + ..Default::default() + }), + ); + handle +} + +fn add_reactor(document: &mut Document, object: Handle, reactor: Handle) { + if let Some(ObjectType::Associative(object)) = document.objects.get_mut(&object) { + if !object.reactors.contains(&reactor) { + object.reactors.push(reactor); + } + } +} + +fn variable_value(document: &Document, variable: Handle) -> AssocEvalVariant { + match document.objects.get(&variable) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + })) => variable.value.clone(), + _ => AssocEvalVariant::default(), + } +} + +/// Set a variable's expression and give it a value dependency on each +/// variable it reads, numbered on from the ones it had. +fn set_expression(document: &mut Document, variable: Handle, expression: &str, reads: &[Handle]) { + let old: Vec = match document.objects.get(&variable) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(value), + .. + })) => value.dependencies.iter().map(|d| d.dependency).collect(), + _ => return, + }; + for dependency in old { + let read = match document.objects.get(&dependency) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::ValueDependency(value), + .. + })) => Some(value.dependency.dependent_on), + _ => None, + }; + if let Some(read) = read { + if let Some(ObjectType::Associative(object)) = document.objects.get_mut(&read) { + object.reactors.retain(|reactor| *reactor != dependency); + } + } + document.objects.remove(&dependency); + } + let mut next = match document.objects.get(&variable) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(value), + .. + })) => value.action.max_dependency_index, + _ => 0, + }; + let mut dependencies = Vec::new(); + for (position, &read) in reads.iter().enumerate() { + next += 1; + let handle = document.allocate_handle(); + let value = variable_value(document, read); + document.objects.insert( + handle, + ObjectType::Associative(AssociativeObject { + handle, + owner: variable, + dxf_name: "ACDBASSOCVALUEDEPENDENCY".into(), + cpp_class_name: "AcDbAssocValueDependency".into(), + data: AssociativeData::ValueDependency(AssocValueDependency { + dependency: AssocDependency { + class_version: 2, + is_read_dependency: true, + is_attached_to_object: true, + is_delegating_to_owning_action: true, + dependent_on: read, + dependency_body_id: next, + ..Default::default() + }, + value, + ..Default::default() + }), + ..Default::default() + }), + ); + add_reactor(document, read, handle); + // BricsCAD numbers the reads of a variable in its flags. + dependencies.push(AssocVariableDependency { + dependency: handle, + flags: position as _, + }); + } + if let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(value), + .. + })) = document.objects.get_mut(&variable) + { + value.expression = expression.to_string(); + value.dependencies = dependencies; + value.action.max_dependency_index = next; + } +} + +/// Take a variable out of its network with the value dependencies it owns. +fn erase_variable(document: &mut Document, network: Handle, variable: Handle) { + set_expression(document, variable, "", &[]); + if let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Network(network), + .. + })) = document.objects.get_mut(&network) + { + network + .actions + .retain(|action| action.dependency != variable); + } + document.objects.remove(&variable); +} + +/// For each entity of `owner`, its `BDMOBJECT` in the owner's constraint +/// manager. +fn entity_objects( + document: &Document, + owner: Handle, + constraints: Handle, +) -> FxHashMap { + let mut objects = FxHashMap::default(); + let Some(Body::ConstraintManager { + counts, children, .. + }) = read_record(document, constraints).map(|record| record.body) + else { + return objects; + }; + for child in children + .iter() + .take(usize::try_from(counts[1]).unwrap_or(0)) + { + if let Some(Body::Object { entity, .. }) = + read_record(document, child.handle).map(|record| record.body) + { + if document + .get_entity(entity.handle) + .is_some_and(|e| e.common().owner_handle == owner) + { + objects.insert(entity.handle, child.handle); + } + } + } + objects +} diff --git a/src/scene/bricscad_parameters/author_tests.rs b/src/scene/bricscad_parameters/author_tests.rs new file mode 100644 index 0000000000..1ce8c46d79 --- /dev/null +++ b/src/scene/bricscad_parameters/author_tests.rs @@ -0,0 +1,429 @@ +//! VISIBILITYSTATES against BricsCAD: the drawings in +//! `tests/fixtures/bricscad/authoring-*.dwg` are what BricsCAD V26 saved +//! along one run of the command on five lines (see the README there). The +//! same run here leaves the same visibility setup. + +use super::author::Action; +use super::record::Value; +use super::*; +use crate::scene::Scene; +use document::objects::{AssociativeData, AssociativeObject}; + +pub(crate) fn fixture(name: &str) -> Scene { + let path = format!( + "{}/tests/fixtures/bricscad/{name}", + env!("CARGO_MANIFEST_DIR") + ); + let bytes = std::fs::read(&path).unwrap_or_else(|_| panic!("read {path}")); + let mut scene = Scene::new(); + scene.document = crate::io::load_bytes_finalized(std::path::Path::new(name), bytes) + .unwrap_or_else(|error| panic!("open {name}: {error}")); + scene.load_named_parameters_from_document(); + scene.load_parametric_constraints_from_document(); + scene +} + +/// The five lines, L1 to L5, by their handles in the fixtures. +pub(crate) const LINES: [u64; 5] = [0x92, 0x93, 0x94, 0x95, 0x96]; + +fn line(n: usize) -> Handle { + Handle::from(LINES[n - 1]) +} + +/// One step of the run: parameter, state, action, lines by number. +pub(super) type Step = (&'static str, &'static str, Action, &'static [usize]); + +/// The run up to the drawing BricsCAD saved as `authoring-select.dwg`. +pub(super) const TO_SELECT: &[Step] = &[ + ("P1", "S1", Action::Add, &[1, 2]), + ("P1", "S2", Action::Invisible, &[1]), + ("P1", "S3", Action::Invisible, &[2]), + ("P1", "S2", Action::Visible, &[1]), + ("P1", "S1", Action::Add, &[3]), + ("P1", "S1", Action::Remove, &[3]), + ("P2", "Sichtbar", Action::Add, &[4]), + ("P2", "Unsichtbar", Action::Invisible, &[4]), + ("P2", "Sichtbar", Action::Add, &[2]), + ("P1", "S4", Action::Visible, &[1]), + ("P1", "S2", Action::Select, &[]), + ("P1", "S3", Action::Select, &[]), +]; + +/// From the drawing after `S4` (before the two selections) on to the one +/// BricsCAD saved as `authoring-edit.dwg`. +pub(super) const TO_EDIT: &[Step] = &[ + ("P1", "S1", Action::Invisible, &[5]), + ("P1", "S2", Action::Visible, &[4]), + ("P1", "S1", Action::Remove, &[1]), + ("P1", "S3", Action::Add, &[2]), + ("P1", "S2", Action::Add, &[3]), +]; + +pub(super) fn run(scene: &mut Scene, steps: &[Step]) { + let model = scene.document.header.model_space_block_handle; + for (parameter, state, action, lines) in steps { + let objects: Vec = lines.iter().map(|n| line(*n)).collect(); + scene + .edit_bricscad_visibility_named( + model, + parameter, + state, + *action, + &objects, + super::author::Naming::GERMAN, + ) + .unwrap_or_else(|error| panic!("{parameter} {state} {action:?} {lines:?}: {error}")); + } +} + +/// The visibility setup of model space as text, without handles: parameters +/// with their tables and current states, suppressions with their members, +/// state and kept layers, the variables with their values, and each line's +/// layer and object. +pub(crate) fn describe(document: &Document) -> Vec { + let model = document.header.model_space_block_handle; + let mut out = Vec::new(); + let variable = |handle: Handle| match document.objects.get(&handle) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + })) => Some(variable), + _ => None, + }; + let number = |value: &document::objects::AssocEvalVariant| match &value.value { + document::objects::AssocEvalValue::Real(v) => format!("{v}"), + document::objects::AssocEvalValue::Long(v) => format!("{v}"), + other => format!("{other:?}"), + }; + let layer = |handle: Handle| { + document + .layers + .iter() + .find(|layer| layer.handle == handle) + .map_or_else(|| format!("{handle:?}"), |layer| layer.name.clone()) + }; + let objects = |properties: &record::Properties, name: &str| -> Vec { + properties + .get(name) + .and_then(Value::items) + .map(|items| items.iter().filter_map(Value::object).collect()) + .unwrap_or_default() + }; + let mut groups_of: std::collections::BTreeMap = Default::default(); + for feature in features(document, model) { + let properties = super::properties(document, feature).expect("a feature decodes"); + match properties.text("Feature_type") { + Some("BdmConfigurationFeature") => { + let table = super::properties( + document, + properties.get("ConfigTable").unwrap().object().unwrap(), + ) + .unwrap(); + out.push(format!( + "parameter {} shows {} table {:?}", + properties.text("Name").unwrap(), + properties.text("LastKeyValue").unwrap(), + table.0 + )); + for reactor in objects(&properties, "Reactors") { + let reactor = super::properties(document, reactor).unwrap(); + let key = reactor.get("IsKeyVar") == Some(&Value::Flag(true)); + let var = variable(reactor.get("VarId").unwrap().object().unwrap()).unwrap(); + out.push(format!( + " reactor {} key {key} enabled {:?} string {:?} value {} -> {} {:?} {}", + reactor.text("VarName").unwrap(), + reactor.get("IsEnabled").unwrap(), + reactor.text("String").unwrap(), + // The key variable's number follows no rule BricsCAD + // keeps; it reads the state from the string. + if key { + "-".into() + } else { + format!("{:?}", reactor.get("Value").unwrap()) + }, + var.name, + var.description, + if key { "-".into() } else { number(&var.value) }, + )); + } + } + Some("BdmSuppressFeature") => { + let name = properties.text("Name").unwrap().to_string(); + let mut line = format!( + "suppression {name} status {:?} kept {:?}", + properties.get("Status").unwrap(), + properties + .get("aEntLayerKey") + .and_then(Value::entries) + .unwrap() + .iter() + .map(|(entity, kept)| format!( + "{:X}->{}", + entity.object().unwrap().value(), + layer(kept.object().unwrap()) + )) + .collect::>() + ); + for reactor in objects(&properties, "Reactors") { + let reactor_properties = super::properties(document, reactor).unwrap(); + if reactor_properties.get("pers_ids").is_some() { + let mut members: Vec = objects(&reactor_properties, "pers_ids") + .into_iter() + .map( + |dependency| match record(document, dependency).unwrap().body { + record::Body::Dependency { entity, .. } => { + groups_of.insert(entity.handle.value(), name.clone()); + format!("{:X}", entity.handle.value()) + } + other => panic!("{other:?}"), + }, + ) + .collect(); + members.sort(); + line.push_str(&format!(" members {members:?}")); + } else { + let var = + variable(reactor_properties.get("var").unwrap().object().unwrap()) + .unwrap(); + let mut reads: Vec = var + .dependencies + .iter() + .map( + |dependency| match document.objects.get(&dependency.dependency) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::ValueDependency(value), + .. + })) => variable(value.dependency.dependent_on) + .unwrap() + .name + .clone(), + other => panic!("{other:?}"), + }, + ) + .collect(); + reads.sort(); + line.push_str(&format!( + " value {:?} variable {} = {} [{}] reads {reads:?}", + reactor_properties.get("value").unwrap(), + var.name, + var.expression, + number(&var.value) + )); + } + } + out.push(line); + } + _ => {} + } + } + for &handle in &LINES { + let entity = document.get_entity(Handle::from(handle)).unwrap(); + let objects: Vec = entity + .common() + .reactors + .iter() + .filter_map(|reactor| match record(document, *reactor)?.body { + record::Body::Object { properties, .. } => Some(format!( + "{} with {} dependencies", + properties.text("NAME").unwrap(), + properties + .get("PersIdDependencies") + .unwrap() + .items() + .unwrap() + .len() + )), + _ => None, + }) + .collect(); + out.push(format!( + "line {handle:X} layer {} in {:?} objects {objects:?}", + entity.common().layer, + groups_of.get(&handle) + )); + } + out +} + +fn assert_same(ours: &Document, theirs: &Document) { + let ours = describe(ours); + let theirs = describe(theirs); + let differences: Vec = ours + .iter() + .zip(&theirs) + .filter(|(a, b)| a != b) + .map(|(a, b)| format!("ours: {a}\ntheirs: {b}")) + .collect(); + assert!( + differences.is_empty() && ours.len() == theirs.len(), + "{}\n\nours:\n{}\n\ntheirs:\n{}", + differences.join("\n"), + ours.join("\n"), + theirs.join("\n") + ); +} + +#[test] +fn the_run_leaves_what_bricscad_leaves_up_to_two_selections() { + let mut scene = fixture("authoring-start.dwg"); + run(&mut scene, TO_SELECT); + assert_same(&scene.document, &fixture("authoring-select.dwg").document); +} + +#[test] +fn the_run_leaves_what_bricscad_leaves_through_remove_and_re_add() { + let mut scene = fixture("authoring-start.dwg"); + run(&mut scene, &TO_SELECT[..10]); + run(&mut scene, TO_EDIT); + assert_same(&scene.document, &fixture("authoring-edit.dwg").document); +} + +/// What BricsCAD keeps that the run's tables do not show: every read of a +/// variable holds the variable's value (BricsCAD does not evaluate past a +/// read that already holds a new value), a variable's reads are numbered, +/// and each key has the number of the state it shows. +#[test] +fn reads_hold_their_values_and_keys_the_number_of_their_state() { + let mut scene = fixture("authoring-start.dwg"); + run(&mut scene, TO_SELECT); + run( + &mut scene, + &[ + ("P3", "S1", Action::Add, &[2]), + ("P1", "S1", Action::Select, &[]), + ], + ); + let document = &scene.document; + let variable = |handle: Handle| match document.objects.get(&handle) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + })) => variable, + other => panic!("{other:?}"), + }; + let mut reads = 0; + let mut most = 0; + for object in document.objects.values() { + match object { + ObjectType::Associative(AssociativeObject { + data: AssociativeData::ValueDependency(read), + .. + }) => { + let read_variable = variable(read.dependency.dependent_on); + assert_eq!(read.value, read_variable.value, "{}", read_variable.name); + reads += 1; + } + ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + }) => { + let flags: Vec = variable + .dependencies + .iter() + .map(|dependency| dependency.flags as usize) + .collect(); + assert_eq!( + flags, + (0..flags.len()).collect::>(), + "{}", + variable.name + ); + most = most.max(flags.len()); + } + _ => {} + } + } + assert!(reads > 0); + assert_eq!(most, 3, "L2 is ruled by three parameters"); + let model = document.header.model_space_block_handle; + let mut keys = 0; + for feature in features(document, model) { + let properties = super::properties(document, feature).unwrap(); + if properties.text("Feature_type") != Some("BdmConfigurationFeature") { + continue; + } + let parameter = visibility_parameter(document, feature).unwrap(); + for reactor in properties.get("Reactors").unwrap().items().unwrap() { + let reactor = super::properties(document, reactor.object().unwrap()).unwrap(); + if reactor.get("IsKeyVar") != Some(&Value::Flag(true)) { + continue; + } + let row = parameter.current.unwrap() as f64; + assert_eq!( + reactor.get("Value"), + Some(&Value::Real(row)), + "{}", + parameter.name + ); + let key = variable(reactor.get("VarId").unwrap().object().unwrap()); + assert_eq!( + key.value.value, + document::objects::AssocEvalValue::Real(row), + "{}", + parameter.name + ); + keys += 1; + } + } + assert_eq!(keys, 3); +} + +/// BricsCAD finds variables by name, and a second variable of a name gets +/// the two mixed up. Some of its drawings have a group whose variable is +/// named after another group (`Unterdrücken_1` with the variable +/// `Unterdrücken_7`): a new group takes a name no variable has. +#[test] +fn a_new_group_takes_a_name_no_variable_has() { + let mut scene = fixture("authoring-select.dwg"); + let model = scene.document.header.model_space_block_handle; + let group_variable = features(&scene.document, model) + .into_iter() + .filter_map(|feature| super::properties(&scene.document, feature)) + .filter(|properties| properties.text("Name") == Some("Unterdrücken_2")) + .flat_map(|properties| { + properties + .get("Reactors") + .unwrap() + .items() + .unwrap() + .to_vec() + }) + .filter_map(|reactor| super::properties(&scene.document, reactor.object()?)) + .find_map(|reactor| reactor.get("var")?.object()) + .unwrap(); + match scene.document.objects.get_mut(&group_variable) { + Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + })) => variable.name = "Unterdrücken_4".into(), + other => panic!("{other:?}"), + } + // As if the drawing had been opened so. + scene.load_named_parameters_from_document(); + scene.load_parametric_constraints_from_document(); + run(&mut scene, &[("P1", "S1", Action::Add, &[5])]); + let document = &scene.document; + let mut names: Vec = document + .objects + .values() + .filter_map(|object| match object { + ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + }) => Some(variable.name.to_lowercase()), + _ => None, + }) + .collect(); + let all = names.len(); + names.sort(); + names.dedup(); + assert_eq!(names.len(), all, "{names:?}"); + let described = describe(document); + assert!( + described + .iter() + .any(|line| line.starts_with("suppression Unterdrücken_5 ") + && line.contains("members [\"96\"]")), + "{described:#?}" + ); +} diff --git a/src/scene/bricscad_parameters/record.rs b/src/scene/bricscad_parameters/record.rs index 00f097a784..ebbe5e56af 100644 --- a/src/scene/bricscad_parameters/record.rs +++ b/src/scene/bricscad_parameters/record.rs @@ -246,6 +246,29 @@ pub(crate) struct Record { } impl Record { + /// A new record of the class with DWG type number `object_type`; no + /// extended data, reactors or extension dictionary. + pub(crate) fn new( + object_type: u16, + handle: Handle, + owner: Ref, + body: Body, + version: DxfVersion, + ) -> Self { + Self { + object_type, + handle, + handle_code: 0, + extended_data: Vec::new(), + owner, + reactors: Vec::new(), + extension_dictionary: None, + binary_data: false, + body, + version, + } + } + /// A new record of the class of `template`, which gives the type number /// and the version; no extended data, reactors or extension dictionary. pub(crate) fn like(template: &Record, handle: Handle, owner: Ref, body: Body) -> Self { diff --git a/src/scene/bricscad_parameters/switch.rs b/src/scene/bricscad_parameters/switch.rs index c21cc54eb0..2e5190ab57 100644 --- a/src/scene/bricscad_parameters/switch.rs +++ b/src/scene/bricscad_parameters/switch.rs @@ -40,7 +40,7 @@ use super::{ use crate::scene::Scene; /// The layer BricsCAD moves the members a state hides to. -const SUPPRESS_LAYER: &str = "*SUPPRESS"; +pub(super) const SUPPRESS_LAYER: &str = "*SUPPRESS"; const UNSUPPORTED: &str = "This BricsCAD parametric block cannot be switched here."; const NOT_IN_MODEL_SPACE: &str = "Only a BricsCAD block reference in model space can be switched."; @@ -477,7 +477,7 @@ fn remap_associative( /// parameter in `listed`, the marks BricsCAD sets on an instance's own /// parameter; for each suppression its value, status and the layers of the /// members it moved to `*SUPPRESS`. -fn apply_states( +pub(super) fn apply_states( document: &mut Document, copy: Handle, members: &[Handle], @@ -712,7 +712,7 @@ fn evaluate(expression: &str, columns: &FxHashMap) -> Option { /// value dependency at the value of the variable it reads, and takes a /// variable whose new value its reads already hold for unchanged, leaving /// what depends on it unevaluated. -fn set_variable( +pub(super) fn set_variable( document: &mut Document, variable: Handle, expression: Option, @@ -1279,7 +1279,7 @@ fn next_anonymous_name(document: &Document) -> String { } /// The raw object for `record`. -fn unknown(class: &str, record: &Record) -> ObjectType { +pub(super) fn unknown(class: &str, record: &Record) -> ObjectType { let (data, handle_bits) = record::encode(record); ObjectType::Unknown { type_name: class.to_string(), @@ -1293,7 +1293,7 @@ fn unknown(class: &str, record: &Record) -> ObjectType { } /// Store a changed record over the object it was read from. -fn store(document: &mut Document, record: &Record) { +pub(super) fn store(document: &mut Document, record: &Record) { let class = match document.objects.get(&record.handle) { Some(ObjectType::Unknown { type_name, .. }) => type_name.clone(), _ => return, diff --git a/src/scene/dwg_native_constraints.rs b/src/scene/dwg_native_constraints.rs index 8db93cd4cc..010a74a961 100644 --- a/src/scene/dwg_native_constraints.rs +++ b/src/scene/dwg_native_constraints.rs @@ -1466,7 +1466,7 @@ const ASSOC_CLASSES: &[(&str, &str, i32)] = &[ ), ]; -fn ensure_associative_classes_registered(document: &mut Document) { +pub(super) fn ensure_associative_classes_registered(document: &mut Document) { for (dxf_name, cpp_class_name, maintenance_version) in ASSOC_CLASSES { if document.classes.get_by_name(dxf_name).is_some() { continue; diff --git a/tests/fixtures/bricscad/README.md b/tests/fixtures/bricscad/README.md index 35d41144bd..9d3a40c001 100644 --- a/tests/fixtures/bricscad/README.md +++ b/tests/fixtures/bricscad/README.md @@ -30,3 +30,52 @@ What the file shows about how BricsCAD stores such a block: those objects read and drive. The variables list them as reactors and the objects reach the variables by handle, so the variables must keep their handles when the drawing is saved. + +## Authoring: `authoring-*.dwg` + +Saved by BricsCAD V26 (same setup) along one run of `VISIBILITYSTATES` on a +drawing of five lines on layer `0`, ten long and five apart along the x axis: +L1 to L5, handles `92` to `96`. + +`authoring-start.dwg` is the drawing before the run. `authoring-select.dwg` is +the drawing after these steps (parameter, state, action, lines): + +| # | Parameter | State | Action | Lines | +|---|---|---|---|---| +| 1 | `P1` | `S1` | Add | L1, L2 | +| 2 | `P1` | `S2` | Invisible | L1 | +| 3 | `P1` | `S3` | Invisible | L2 | +| 4 | `P1` | `S2` | Visible | L1 | +| 5 | `P1` | `S1` | Add | L3 | +| 6 | `P1` | `S1` | Remove | L3 | +| 7 | `P2` | `Sichtbar` | Add | L4 | +| 8 | `P2` | `Unsichtbar` | Invisible | L4 | +| 9 | `P2` | `Sichtbar` | Add | L2 | +| 10 | `P1` | `S4` | Visible | L1 | +| 11 | `P1` | `S2` | Select state | | +| 12 | `P1` | `S3` | Select state | | + +`authoring-edit.dwg` is the drawing after steps 1 to 10 and then: + +| # | Parameter | State | Action | Lines | +|---|---|---|---|---| +| 11 | `P1` | `S1` | Invisible | L5 | +| 12 | `P1` | `S2` | Visible | L4 | +| 13 | `P1` | `S1` | Remove | L1 | +| 14 | `P1` | `S3` | Add | L2 | +| 15 | `P1` | `S2` | Add | L3 | + +What the run shows about how BricsCAD keeps the states it authors: + +- A parameter is a configuration feature with a table: a row per state, a + column (`look_n`, the lowest free number) per group of lines that show and + hide together, 1 where the group shows. A new state starts with every group + hidden. +- Each group is a suppression feature (`Unterdrücken_n` in the German + interface) whose variable is `1 - ` the product of the group's columns, one + per parameter that rules the group, in parameter order (step 9 makes + `1 - look_1 * look_4`). +- Remove keeps the line's `BDMOBJECT` but empties its dependencies; adding the + line again reuses it (step 15). +- Every read of a variable (an `ACDBASSOCVALUEDEPENDENCY`) holds the + variable's value, and a variable's reads carry their position as flags. diff --git a/tests/fixtures/bricscad/authoring-edit.dwg b/tests/fixtures/bricscad/authoring-edit.dwg new file mode 100644 index 0000000000000000000000000000000000000000..e84b68ff94bd205885d93c1624f81b2e51b748d3 GIT binary patch literal 18437 zcmc(H3tUv?+VAtO+pHO8U=0j7+;p*KzyU=@L`A%<83r71l;NgmsDliMh>D7eO0^VB zG^$al&~!H%x|MELT2@w5nUYbFQJLHNs7+>e*;wwftLGW3?{@at-}!y}JNpd3XIb>#Qo`!^t9dXuRM+8e%_In{_Tf1=Uq5aVEEd>RrfAAX?<$)#C_7I()PU{ z-9GHR?k3uCEw`4rXI1F?QE7{6`o7E0@10$<#yv{~3yZwA&yik3TJjq;lhhe9BCHfI3Bw0ZZ&k)7;YnTZoU;lbBqB%zcJDD_u8VmNTS?>jFW<500r;1#$6tQo zlLYV9mRp|5i-Lt9x{EllQUVZPq zg@?ul7C!rzzTmU}@;6wdf(i&)!Y zsKZi3Sc_$>!gJk?a|2$j!mBm-%!}6xVI3YTuzeyFU`wlRTsiQ(>P8EK={9_~4)21w zDsPl&!MqMk54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pF-4(s3DET+P8>nZ%d8=oTEhD6ldO*MHG(4bGZ%Z7E8)NW}u< zTrgwtOdMG4Y`+s*=hZ95w42SFhdB#)@GEphEuFTh3^v%xa*^V?T&j zHL=a5u0&?evf9e!jqBQ3kvG5+U6|=9&4PAn%n4GST*j5fsi$Cu{I!*pr41F!D_yLp z*23a~gJ(76kCxG)Tt~`74RTl3H`G-$io*_(@?nd&Y;jSy!WW*n=I1Yz?oFzTryUim zymghLFq$nhEPiT%tIb7+#yCFNr>jm(Yu2^D+`O8~t*cnKPK-W57Jn(BbHm6@YNcmP_{=jj}}FQiuC`Q01Wz}W)qRFpL2}3miuc0=EhY+J8PRB6JDPjg}A8 literal 0 HcmV?d00001 diff --git a/tests/fixtures/bricscad/authoring-start.dwg b/tests/fixtures/bricscad/authoring-start.dwg new file mode 100644 index 0000000000000000000000000000000000000000..759ab8036a08eceaee2ff749886ec580484ed999 GIT binary patch literal 13669 zcmc(G4_s8$*67;joH=tiGr$0Y4*&FUX21bO5kXNv&I|(%IO+hSqJj=O5F#o9Dk|v# z$?#7#DmT%rrXo_Zw6Zd@n#_#MZfJD#cD1Mv&8%*E^Olz7TgU3Y+xOk~z4vbS-FN1< z&i-@O-h1t}_g-u5wf9(ZMkkL+0p%G-`w2koxFNSvKfeUbQXUz>uToq5TG;%fZh%l9lH0NiWI zhhBT-e5_|<>)ONltUPfTkqNi~5R-*}Ci>5m`MaimV{xqMw-Eo^izEI2H0yq1!*48( z-T&tX?r+6@V{yYjHEsUZ`oEyK9eO__Gp49D3;4#@a2Y^;?o`{8R(DJP2ivX+ zrx|f=n6J=PeyfMd_XQYlz;NlUI+jA+-_@*OD>NurN*nd~R@(o^rAPkP&cR;DM9Eo) zwR>PW*3$4duGYcgU$wjhQ;ToWnFS(Pv5eAcJ>(z_Hp~$)wiGdH5pN0hf9l`i3;6y2 zln+Wx^N|*X(;k?2i>GzB_@;0`Y5S*|1=8!xc(aKqcS4OEXc=xEA)&;ipJnigi$c@AMp5JndP0Q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2_dUjp1nAMc~Nc9Tp16IJ`zU4$qsDa6Y8qPG}4y z)zH*9L>OnIsQHLI&V!e1Qs8#DlT?d5`h>d8-R1%#Uk74h6M;#r5HI8jl|q+rT(}U+ z#>U4M#CD4pVmBEJjES))%$s=ACf-4;^lUnXHZSTI}KQi#g)<6HDZBS!j`qqeb=~*i> zmz9bcjp^!H$?cI_AG>+{$dH`4B>}5SXICyyUM;!!qB$v=8B2$iXIRI!pMSUO;<*D6 z^_gqO6co>_F;^u{O7reNpsQS$lU+Ae#PCpneCCW zxd}*O;BuYY*l-nhG!fQDks z4s0X`34_;=F%C7{L6s042M@Of&(+J&G`P&5-4da-EU?X=khid=!d6l1SXkd0kH#<+ z0gQty4Y!kpph8oHE`V+I@PcMm8#VF>DUB;(OCtFRh>%xTQBho5zMujx z>+xDB%inuaQ@X!|RYgyiCuPFCa)VUZTPz&O@(AVD7vhoJRsG%L$fH3#~9v5Q|l>z-0NBNfrH)_hj z|B_S&UU~k(EzOLe1(rtqvW=Oc|l5*zMnI2YXJ0ABG3ydC{w8%bQxhCg!1EO zHHK~j0Eb~erUM+LOvNh+tU%+ydl^_(F}oBR1C>)B0f!?P(*ibyG~Q}Np%sZx(3IyF KTK}DYJo+Cnv^m%S literal 0 HcmV?d00001 From 4d3fc254803df29448ed76aab16ed7f38c232c18 Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:13:29 +0100 Subject: [PATCH 6/7] VISIBILITYSTATES leaves the keys of parameters it was not asked about as BricsCAD left them A visibility parameter's key (a BdmDbConfigVarReactor with IsKeyVar) can be disabled, its variable holding an expression of its own: openCirt's templates, made in BricsCAD, have keys showing the second state over a variable `0`. BricsCAD reads such a state by name and leaves the key alone until the parameter's state is picked; then it enables the key, drops the expression and gives the variable the state's number. VISIBILITYSTATES enabled every key of the drawing and renumbered it under its expression, so BricsCAD's next evaluation could show another state of a parameter nobody touched. Now only enabled keys are renumbered, and the key of the parameter whose state is picked is set the way BricsCAD sets it. Switching references is unchanged: a copy's keys are still set as in BricsCAD's own copies. --- src/scene/bricscad_parameters/author.rs | 55 ++++++--- src/scene/bricscad_parameters/author_tests.rs | 108 ++++++++++++++++++ src/scene/bricscad_parameters/switch.rs | 20 +++- 3 files changed, 164 insertions(+), 19 deletions(-) diff --git a/src/scene/bricscad_parameters/author.rs b/src/scene/bricscad_parameters/author.rs index 8ac55fc9eb..4d6edf648b 100644 --- a/src/scene/bricscad_parameters/author.rs +++ b/src/scene/bricscad_parameters/author.rs @@ -283,6 +283,7 @@ impl Scene { ) }) .collect(); + let parameter_name = setup.parameters[p].name.clone(); setup.write(&mut self.document)?; let members = owner_members(&self.document, owner); apply_states( @@ -292,19 +293,25 @@ impl Scene { &layers, &states, &BTreeSet::new(), + true, )?; - number_keys(&mut self.document, owner)?; + let chosen = (action == Action::Select).then_some(parameter_name); + number_keys(&mut self.document, owner, chosen.as_deref())?; self.load_named_parameters_from_document(); self.load_parametric_constraints_from_document(); Ok(()) } } -/// Give each parameter's key the number of the state it shows. BricsCAD -/// shows the state of that number again when it next evaluates the owner; -/// its own state selection leaves the number behind, so the next edit there -/// jumps back to an earlier state. -fn number_keys(document: &mut Document, owner: Handle) -> Result<()> { +/// Give each enabled key the number of the state it shows: BricsCAD shows the +/// state of that number again when it next evaluates the owner. A disabled +/// key is left alone; BricsCAD reads its state by name, and its variable may +/// hold an expression of its own (openCirt's templates have keys showing the +/// second state over a variable `0`). The key of `chosen`, the parameter a +/// state was picked for, is set the way BricsCAD sets it when it shows a +/// state: enabled, holding the state's number, its variable that number with +/// no expression. +fn number_keys(document: &mut Document, owner: Handle, chosen: Option<&str>) -> Result<()> { for feature in features(document, owner) { let Some(properties) = super::properties(document, feature) else { continue; @@ -327,6 +334,11 @@ fn number_keys(document: &mut Document, owner: Handle) -> Result<()> { .collect() }) .ok_or(UNSUPPORTED)?; + let is_chosen = chosen.is_some_and(|name| { + properties + .text("Name") + .is_some_and(|own| own.eq_ignore_ascii_case(name)) + }); let reactors: Vec = properties .get("Reactors") .and_then(Value::items) @@ -338,6 +350,9 @@ fn number_keys(document: &mut Document, owner: Handle) -> Result<()> { if properties.get("IsKeyVar") != Some(&Value::Flag(true)) { continue; } + if !is_chosen && properties.get("IsEnabled") == Some(&Value::Flag(false)) { + continue; + } let Some(row) = properties .text("String") .and_then(|state| states.iter().position(|name| name == state)) @@ -349,18 +364,26 @@ fn number_keys(document: &mut Document, owner: Handle) -> Result<()> { .and_then(Value::object) .ok_or(UNSUPPORTED)?; properties.set("Value", Value::Real(row as f64)); + if is_chosen { + properties.set("IsEnabled", Value::Flag(true)); + } store(document, &record); - let value = match variable_value(document, variable).value { - AssocEvalValue::Long(_) => AssocEvalVariant { - code: 90, - value: AssocEvalValue::Long(row as i32), - }, - _ => AssocEvalVariant { - code: 40, - value: AssocEvalValue::Real(row as f64), - }, + let real = AssocEvalVariant { + code: 40, + value: AssocEvalValue::Real(row as f64), }; - set_variable(document, variable, None, value)?; + if is_chosen { + set_variable(document, variable, Some(String::new()), real)?; + } else { + let value = match variable_value(document, variable).value { + AssocEvalValue::Long(_) => AssocEvalVariant { + code: 90, + value: AssocEvalValue::Long(row as i32), + }, + _ => real, + }; + set_variable(document, variable, None, value)?; + } } } Ok(()) diff --git a/src/scene/bricscad_parameters/author_tests.rs b/src/scene/bricscad_parameters/author_tests.rs index 1ce8c46d79..d6e1d62cab 100644 --- a/src/scene/bricscad_parameters/author_tests.rs +++ b/src/scene/bricscad_parameters/author_tests.rs @@ -427,3 +427,111 @@ fn a_new_group_takes_a_name_no_variable_has() { "{described:#?}" ); } + +/// The key of `parameter`: whether enabled, its number, its variable's +/// expression and value. +fn key_of( + document: &Document, + parameter: &str, +) -> (Value, Value, String, document::objects::AssocEvalValue) { + let model = document.header.model_space_block_handle; + for feature in features(document, model) { + let properties = super::properties(document, feature).unwrap(); + if properties.text("Name") != Some(parameter) { + continue; + } + for reactor in properties.get("Reactors").unwrap().items().unwrap() { + let reactor = super::properties(document, reactor.object().unwrap()).unwrap(); + if reactor.get("IsKeyVar") != Some(&Value::Flag(true)) { + continue; + } + let handle = reactor.get("VarId").unwrap().object().unwrap(); + let Some(ObjectType::Associative(AssociativeObject { + data: AssociativeData::Variable(variable), + .. + })) = document.objects.get(&handle) + else { + panic!() + }; + return ( + reactor.get("IsEnabled").unwrap().clone(), + reactor.get("Value").unwrap().clone(), + variable.expression.clone(), + variable.value.value.clone(), + ); + } + } + panic!("no key of {parameter}"); +} + +/// openCirt's templates have keys BricsCAD left disabled over a variable +/// with an expression of its own (a key showing the second state over `0`). +/// BricsCAD reads such a state by name and leaves the key alone until the +/// parameter's state is picked; then it enables the key and drops the +/// expression. A key re-enabled under its expression would make BricsCAD +/// show the first state on its next evaluation. +#[test] +fn a_disabled_key_is_left_alone_until_its_state_is_picked() { + use document::objects::{AssocEvalValue, AssocEvalVariant}; + let mut scene = fixture("authoring-select.dwg"); + let model = scene.document.header.model_space_block_handle; + // P2 shows Sichtbar (row 0); make its key like the templates' ones. + for feature in features(&scene.document, model) { + let properties = super::properties(&scene.document, feature).unwrap(); + if properties.text("Name") != Some("P2") { + continue; + } + for reactor in properties.get("Reactors").unwrap().items().unwrap() { + let handle = reactor.object().unwrap(); + let mut record = record(&scene.document, handle).unwrap(); + let reactor = record.body.properties_mut(); + if reactor.get("IsKeyVar") != Some(&Value::Flag(true)) { + continue; + } + reactor.set("IsEnabled", Value::Flag(false)); + reactor.set("Value", Value::Real(1.0)); + let variable = reactor.get("VarId").unwrap().object().unwrap(); + super::switch::store(&mut scene.document, &record); + super::switch::set_variable( + &mut scene.document, + variable, + Some("1".into()), + AssocEvalVariant { + code: 90, + value: AssocEvalValue::Long(1), + }, + ) + .unwrap(); + } + } + scene.load_named_parameters_from_document(); + let before = key_of(&scene.document, "P2"); + run( + &mut scene, + &[ + ("P1", "S1", Action::Select, &[]), + ("P1", "S4", Action::Invisible, &[4]), + ("P1", "S2", Action::Visible, &[5]), + ], + ); + assert_eq!( + key_of(&scene.document, "P2"), + before, + "P2 was not asked about" + ); + assert_eq!( + current_state(&scene.document, model, "P2").as_deref(), + Some("Sichtbar"), + "still shows Sichtbar" + ); + run(&mut scene, &[("P2", "Unsichtbar", Action::Select, &[])]); + assert_eq!( + key_of(&scene.document, "P2"), + ( + Value::Flag(true), + Value::Real(1.0), + String::new(), + AssocEvalValue::Real(1.0) + ) + ); +} diff --git a/src/scene/bricscad_parameters/switch.rs b/src/scene/bricscad_parameters/switch.rs index 2e5190ab57..194a96125c 100644 --- a/src/scene/bricscad_parameters/switch.rs +++ b/src/scene/bricscad_parameters/switch.rs @@ -359,7 +359,15 @@ impl Scene { store(document, &record); let layers: FxHashMap = copy_members.iter().copied().zip(layers).collect(); - apply_states(document, copy, ©_members, &layers, states, listed)?; + apply_states( + document, + copy, + ©_members, + &layers, + states, + listed, + false, + )?; Ok(copy) } } @@ -476,7 +484,10 @@ fn remap_associative( /// parameter the state, the values of its table's columns and, for a /// parameter in `listed`, the marks BricsCAD sets on an instance's own /// parameter; for each suppression its value, status and the layers of the -/// members it moved to `*SUPPRESS`. +/// members it moved to `*SUPPRESS`. With `keep_keys` the key reactors keep +/// whether they are enabled and the number they hold (model space of a block +/// drawing, where BricsCAD leaves the keys of parameters it was not asked +/// about as they are). pub(super) fn apply_states( document: &mut Document, copy: Handle, @@ -484,6 +495,7 @@ pub(super) fn apply_states( layers: &FxHashMap, states: &BTreeMap, listed: &BTreeSet, + keep_keys: bool, ) -> Result<()> { let features = features(document, copy); let mut columns: FxHashMap = FxHashMap::default(); @@ -557,7 +569,9 @@ pub(super) fn apply_states( .ok_or(UNSUPPORTED)?; if properties.get("IsKeyVar") == Some(&Value::Flag(true)) { properties.set("String", Value::Text(state.clone())); - properties.set("IsEnabled", Value::Flag(!own)); + if !keep_keys { + properties.set("IsEnabled", Value::Flag(!own)); + } if own { properties.set("Value", Value::Real(row as f64)); set_variable( From e58a200e587f81124b9e854f6114ae166f5651c6 Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:17:05 +0100 Subject: [PATCH 7/7] The Visibility States palette edits a BricsCAD parametric block's states with the mouse MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit VISIBILITYSTATESPANELOPEN (Parametric tab › Manage › Visibility States) opens a palette on model space of a BricsCAD block drawing, after BricsCAD's own Visibility States panel: - each visibility parameter with the number of objects it rules and its states; a click shows a state, ▲/▼ move it up or down, the arrow opens its page; Add state and + (a parameter, named with its first state and started with the objects then picked); - a state's page lists the parameter's objects (type, layer when shown, handle) with an eye to show or hide each in the state, ✕ to take it out of the parameter and a button to add objects; a row selects its object; an object that shows the same in every state is marked, as BricsCAD marks it. Moving states is something BricsCAD cannot do: the order is the order of the table's rows, which is the order Properties lists a reference's states in. A moved state takes its row along; the state shown stays shown and its key gets its new number. BricsCAD V26 lists the moved states in the new order and shows each as before. Every change runs through VISIBILITYSTATES' edit and is one undo step; the two new actions are MoveUp/MoveDown and NewState (a state with every object of the parameter hidden, shown at once). The command takes the whole source option a translated prompt hands back, and its prompts no longer build "or [...]" from English fragments. The texts of the command and the palette are in every locale's catalog. The palette is in the kit audit with no generic colours or literal sizes. Tests: moving keeps every state's objects and the shown state, past either end nothing moves; a new state hides every object of its parameter; the palette switches, moves, adds a state and objects, removes one, starts a parameter, and each step undoes; outside model space it has nothing to edit. Wiki: VISIBILITYSTATESPANELOPEN/CLOSE pages. --- docs/ui/audit_counts.sh | 1 + docs/ui/audit_counts.txt | 1 + docs/wiki/commands/VISIBILITYSTATES.md | 3 +- .../commands/VISIBILITYSTATESPANELCLOSE.md | 8 + .../commands/VISIBILITYSTATESPANELOPEN.md | 40 ++ docs/wiki/pages/Blocks-and-Attributes.md | 2 +- docs/wiki/since.json | 2 + locales/ar-SA/opencadstudio.ftl | 36 ++ locales/bg-BG/opencadstudio.ftl | 36 ++ locales/cs-CZ/opencadstudio.ftl | 36 ++ locales/de-DE/opencadstudio.ftl | 36 ++ locales/el-GR/opencadstudio.ftl | 36 ++ locales/en-US/opencadstudio.ftl | 36 ++ locales/es-ES/opencadstudio.ftl | 36 ++ locales/fi-FI/opencadstudio.ftl | 36 ++ locales/fr-FR/opencadstudio.ftl | 36 ++ locales/hi-IN/opencadstudio.ftl | 36 ++ locales/hu-HU/opencadstudio.ftl | 36 ++ locales/it-IT/opencadstudio.ftl | 36 ++ locales/ja-JP/opencadstudio.ftl | 36 ++ locales/ko-KR/opencadstudio.ftl | 36 ++ locales/lo-LA/opencadstudio.ftl | 36 ++ locales/nl-NL/opencadstudio.ftl | 36 ++ locales/pl-PL/opencadstudio.ftl | 36 ++ locales/pt-BR/opencadstudio.ftl | 36 ++ locales/ru-RU/opencadstudio.ftl | 36 ++ locales/tr-TR/opencadstudio.ftl | 36 ++ locales/vi-VN/opencadstudio.ftl | 36 ++ locales/zh-CN/opencadstudio.ftl | 36 ++ locales/zh-TW/opencadstudio.ftl | 36 ++ src/app/commands/bricscad_visibility.rs | 237 +++++++++- src/app/dock/update.rs | 3 + src/app/dock/view.rs | 6 + src/app/message.rs | 2 + src/app/mod.rs | 2 + src/app/update/dispatch.rs | 1 + src/app/visibilitystates_tests.rs | 138 ++++++ src/locale_catalog.rs | 36 ++ src/modules/draw/modify/visibilitystates.rs | 61 ++- src/modules/parametric/mod.rs | 8 +- src/scene/bricscad_parameters.rs | 2 +- src/scene/bricscad_parameters/author.rs | 120 ++++- src/scene/bricscad_parameters/author_tests.rs | 145 +++++- src/ui/dock.rs | 8 +- src/ui/ribbon/keytips.rs | 1 + src/ui/window/bricscad_visibility.rs | 430 ++++++++++++++++++ src/ui/window/mod.rs | 1 + 47 files changed, 2026 insertions(+), 60 deletions(-) create mode 100644 docs/wiki/commands/VISIBILITYSTATESPANELCLOSE.md create mode 100644 docs/wiki/commands/VISIBILITYSTATESPANELOPEN.md create mode 100644 src/ui/window/bricscad_visibility.rs diff --git a/docs/ui/audit_counts.sh b/docs/ui/audit_counts.sh index 11738fdf73..6f793f0162 100755 --- a/docs/ui/audit_counts.sh +++ b/docs/ui/audit_counts.sh @@ -27,6 +27,7 @@ src/ui/window/authoring_palettes.rs src/ui/window/tool_palettes.rs src/ui/window/parameters_manager.rs src/ui/window/count_palette.rs +src/ui/window/bricscad_visibility.rs src/ui/window/layer_walk.rs src/ui/window/quick_calc/view.rs src/ui/window/quick_calc/variables_view.rs diff --git a/docs/ui/audit_counts.txt b/docs/ui/audit_counts.txt index 80f55accc5..bc3f77c2fc 100644 --- a/docs/ui/audit_counts.txt +++ b/docs/ui/audit_counts.txt @@ -9,6 +9,7 @@ src/ui/window/authoring_palettes.rs 0 0 src/ui/window/tool_palettes.rs 0 0 src/ui/window/parameters_manager.rs 0 0 src/ui/window/count_palette.rs 0 17 +src/ui/window/bricscad_visibility.rs 0 0 src/ui/window/layer_walk.rs 0 0 src/ui/window/quick_calc/view.rs 3 44 src/ui/window/quick_calc/variables_view.rs 0 32 diff --git a/docs/wiki/commands/VISIBILITYSTATES.md b/docs/wiki/commands/VISIBILITYSTATES.md index 54e846eb26..6c9890d339 100644 --- a/docs/wiki/commands/VISIBILITYSTATES.md +++ b/docs/wiki/commands/VISIBILITYSTATES.md @@ -1,6 +1,6 @@ --- summary: Creates and edits the visibility states of a BricsCAD parametric block in model space of the block's own drawing, stored the way BricsCAD stores them. -related: BVSTATE, BVSHOW, BVHIDE +related: VISIBILITYSTATESPANELOPEN, BVSTATE, BVSHOW, BVHIDE web: Not available in the web app. --- @@ -28,3 +28,4 @@ web: Not available in the web app. - The command works in model space only. In the Block Editor it does nothing, because the copies of the block that its references show would keep the old states; edit the block's own drawing instead. - The drawing must be DWG 2010 or later. Dynamic blocks made in OCS or AutoCAD use [`BVSTATE`](BVSTATE-Command) instead. - Each run of the command is one undo step. +- The [Visibility States palette](VISIBILITYSTATESPANELOPEN-Command) does the same with the mouse, and also orders the states. diff --git a/docs/wiki/commands/VISIBILITYSTATESPANELCLOSE.md b/docs/wiki/commands/VISIBILITYSTATESPANELCLOSE.md new file mode 100644 index 0000000000..5fbc37dba0 --- /dev/null +++ b/docs/wiki/commands/VISIBILITYSTATESPANELCLOSE.md @@ -0,0 +1,8 @@ +--- +summary: Closes the Visibility States palette. +related: VISIBILITYSTATESPANELOPEN, VISIBILITYSTATES +web: Not available in the web app. +--- + +## Usage +Type `VISIBILITYSTATESPANELCLOSE`. The Visibility States palette closes; [`VISIBILITYSTATESPANELOPEN`](VISIBILITYSTATESPANELOPEN-Command) opens it again. diff --git a/docs/wiki/commands/VISIBILITYSTATESPANELOPEN.md b/docs/wiki/commands/VISIBILITYSTATESPANELOPEN.md new file mode 100644 index 0000000000..33eb55dff3 --- /dev/null +++ b/docs/wiki/commands/VISIBILITYSTATESPANELOPEN.md @@ -0,0 +1,40 @@ +--- +summary: Opens the Visibility States palette, where the visibility states of a BricsCAD parametric block are shown, switched, ordered and edited in model space of the block's own drawing. +related: VISIBILITYSTATES, VISIBILITYSTATESPANELCLOSE, BVSTATE +ribbon: Parametric tab › Manage panel › Visibility States +web: Not available in the web app. +--- + +## Usage +1. Open the drawing of a BricsCAD parametric block (the block is the drawing's model space), or any drawing to make its model space one. +2. Run `VISIBILITYSTATESPANELOPEN`, or click **Visibility States** on the Parametric tab. `VISIBILITYSTATESPANELCLOSE` closes the palette. + +## The parameters +Each visibility parameter is listed with the number of objects it rules and its states. The state shown is marked. + +| Control | What it does | +|---|---| +| A state | Shows that state. | +| ▲ / ▼ | Moves the state up or down. Properties lists the states of a block reference in this order. | +| ▸ (or double-click) | Opens the state's page. | +| **Add state** | Adds a state with every object of the parameter hidden, shows it and opens its page. | +| **+** at the top | Adds a parameter: type its name and its first state, then select the objects it starts with. | + +## A state's page +Every object the parameter rules is listed with its type, the layer it is on when shown, and its handle. + +| Control | What it does | +|---|---| +| Eye | Shows or hides the object in this state. | +| ✕ | Removes the object from the parameter: its states no longer show or hide it. | +| A row | Selects the object in the drawing. | +| Select objects button | Adds objects: they show in this state only. | +| **Show** | Shows this state. | +| ◂ | Back to the parameters. | + +A warning sign marks an object that shows the same in every state of the parameter. + +## Notes +- Each change is one undo step, and is stored the way BricsCAD stores it (see [`VISIBILITYSTATES`](VISIBILITYSTATES-Command), which does the same from the command line). +- The palette works in model space only. In the Block Editor or a layout it says so. +- States are not renamed or deleted here yet. diff --git a/docs/wiki/pages/Blocks-and-Attributes.md b/docs/wiki/pages/Blocks-and-Attributes.md index a0600ff6fa..a57bf02380 100644 --- a/docs/wiki/pages/Blocks-and-Attributes.md +++ b/docs/wiki/pages/Blocks-and-Attributes.md @@ -83,7 +83,7 @@ Dynamic blocks change shape through grips on each reference: a door that sets it **Visibility states.** `BVSTATE` creates and switches visibility states; `BVSHOW` and `BVHIDE` choose which objects show in the current state. Each reference then has a list to pick its state. -**BricsCAD parametric blocks.** A reference to a block made parametric in BricsCAD lists the states of its visibility parameters in Properties; the state you pick shows the way BricsCAD shows it. [`VISIBILITYSTATES`](VISIBILITYSTATES-Command) creates and edits those states in model space of the block's own drawing, stored where BricsCAD reads them. +**BricsCAD parametric blocks.** A reference to a block made parametric in BricsCAD lists the states of its visibility parameters in Properties; the state you pick shows the way BricsCAD shows it. [`VISIBILITYSTATES`](VISIBILITYSTATES-Command) creates and edits those states in model space of the block's own drawing, stored where BricsCAD reads them; the [Visibility States palette](VISIBILITYSTATESPANELOPEN-Command) does it with the mouse and orders the states. **Block properties table.** `BTABLE` defines combinations of parameter values in a table, so each reference picks a row. diff --git a/docs/wiki/since.json b/docs/wiki/since.json index e8f689be75..996aa3679a 100644 --- a/docs/wiki/since.json +++ b/docs/wiki/since.json @@ -906,6 +906,8 @@ "VERTICAL": "0.1.4", "VIEW": "0.1.3", "VISIBILITYSTATES": "2026.47", +"VISIBILITYSTATESPANELCLOSE": "2026.47", +"VISIBILITYSTATESPANELOPEN": "2026.47", "VISRETAIN": "0.7.0", "VISUALSTYLES": "0.7.0", "VPCLIP": "2026.39", diff --git a/locales/ar-SA/opencadstudio.ftl b/locales/ar-SA/opencadstudio.ftl index 7698fbbc97..d6770c0482 100644 --- a/locales/ar-SA/opencadstudio.ftl +++ b/locales/ar-SA/opencadstudio.ftl @@ -3602,6 +3602,42 @@ modify = .bvstate-exists = حالة الرؤية "__ocs_fmt_0__" موجودة بالفعل. .bvstate-last = لا يمكن حذف حالة الرؤية الوحيدة. .bvstate-needs-bedit = __ocs_fmt_0__: افتح الكتلة أولاً في محرر الكتل (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES أدخل معلمة جديدة: + .visibilitystates-parameter-or = VISIBILITYSTATES أدخل معلمة جديدة أو [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES أدخل حالة جديدة لـ __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES أدخل حالة جديدة لـ __ocs_fmt_0__ أو [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES حدد إجراءً [إضافة/إزالة/إظهار/إخفاء/تحديد الحالة] <إضافة>: + .visibilitystates-add-objects = إضافة كائنات + .visibilitystates-remove-objects = إزالة كائنات + .visibilitystates-make-visible = إظهار الكائنات + .visibilitystates-make-invisible = إخفاء الكائنات + .visibilitystates-select-state = تحديد الحالة + .visibilitystates-model-space = يعمل VISIBILITYSTATES في فضاء النموذج: افتح رسم كتلة BricsCAD. + .visibilitystates-unsupported = لا يمكن تحرير حالات الرؤية هنا. + .visibilitystates-old-format = تتطلب حالات الرؤية رسمًا بتنسيق DWG 2010 أو أحدث. + .visibilitystates-no-parameter = لا توجد معلمة رؤية بهذا الاسم. + .visibilitystates-no-state = لا توجد حالة رؤية بهذا الاسم. + .visibilitystates-state-exists = حالة الرؤية هذه موجودة بالفعل. + .visibilitystates-cannot-move = لا يمكن نقل حالة الرؤية أكثر من ذلك. + .visibilitystates-bad-name = أدخل اسمًا من أحرف وأرقام وشرطات سفلية. + .visibilitystates-name-taken = هذا الاسم يستخدمه متغير آخر. + .visibilitystates-no-objects = حدد كائنات من الفضاء الجاري تحريره. + .visibilitystates-panel-elsewhere = تُحرَّر حالات الرؤية في فضاء النموذج لرسم الكتلة نفسها. + .visibilitystates-panel-unsupported = لا يمكن تحرير حالات الرؤية في هذا الرسم هنا. + .visibilitystates-first-state = الحالة الأولى + .visibilitystates-panel-empty = لا توجد حالات رؤية في هذا الرسم. انقر + لإضافة معلمة. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (الكائنات: __ocs_fmt_1__) + .visibilitystates-move-up = نقل لأعلى + .visibilitystates-move-down = نقل لأسفل + .visibilitystates-state-objects = كائنات هذه الحالة + .visibilitystates-new-state = حالة جديدة + .visibilitystates-add-state = إضافة حالة + .visibilitystates-back = العودة إلى المعلمات + .visibilitystates-add-to-state = إضافة كائنات إلى هذه الحالة + .visibilitystates-no-objects-yet = لا تتحكم المعلمة في أي كائنات بعد. أضف كائنات إلى هذه الحالة. + .visibilitystates-remove-from-parameter = إزالة من المعلمة + .visibilitystates-same-everywhere = يظهر بالشكل نفسه في كل حالات المعلمة + .visibilitystates-same-everywhere-note = يظهر كائن واحد أو أكثر بالشكل نفسه في كل حالات هذه المعلمة. .bvstate-current = حالة الرؤية الحالية: __ocs_fmt_0__ .bvhide-select = حدد الكائنات المراد إخفاؤها: .bvshow-select = حدد الكائنات المراد إظهارها: diff --git a/locales/bg-BG/opencadstudio.ftl b/locales/bg-BG/opencadstudio.ftl index a764783c87..217bfd5ebf 100644 --- a/locales/bg-BG/opencadstudio.ftl +++ b/locales/bg-BG/opencadstudio.ftl @@ -3589,6 +3589,42 @@ modify = .bvstate-exists = Състоянието на видимост "__ocs_fmt_0__" вече съществува. .bvstate-last = Единственото състояние на видимост не може да бъде изтрито. .bvstate-needs-bedit = __ocs_fmt_0__: първо отворете блока в редактора на блокове (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Въведете нов параметър: + .visibilitystates-parameter-or = VISIBILITYSTATES Въведете нов параметър или [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Въведете ново състояние за __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Въведете ново състояние за __ocs_fmt_0__ или [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Изберете действие [Добави/Отстрани/Покажи/Скрий/Избери състояние] <Добави>: + .visibilitystates-add-objects = Добави обекти + .visibilitystates-remove-objects = Отстрани обекти + .visibilitystates-make-visible = Направи обектите видими + .visibilitystates-make-invisible = Направи обектите невидими + .visibilitystates-select-state = Избери състояние + .visibilitystates-model-space = VISIBILITYSTATES работи в пространството на модела: отворете чертежа на блока на BricsCAD. + .visibilitystates-unsupported = Състоянията на видимост тук не могат да се редактират. + .visibilitystates-old-format = Състоянията на видимост изискват чертеж във формат DWG 2010 или по-нов. + .visibilitystates-no-parameter = Няма параметър на видимост с това име. + .visibilitystates-no-state = Няма състояние на видимост с това име. + .visibilitystates-state-exists = Това състояние на видимост вече съществува. + .visibilitystates-cannot-move = Състоянието на видимост не може да се премести повече. + .visibilitystates-bad-name = Въведете име от букви, цифри и долни черти. + .visibilitystates-name-taken = Това име се използва от друга променлива. + .visibilitystates-no-objects = Изберете обекти от редактираното пространство. + .visibilitystates-panel-elsewhere = Състоянията на видимост се редактират в пространството на модела на собствения чертеж на блока. + .visibilitystates-panel-unsupported = Състоянията на видимост на този чертеж не могат да се редактират тук. + .visibilitystates-first-state = Първо състояние + .visibilitystates-panel-empty = В този чертеж няма състояния на видимост. Щракнете върху +, за да добавите параметър. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (обекти: __ocs_fmt_1__) + .visibilitystates-move-up = Премести нагоре + .visibilitystates-move-down = Премести надолу + .visibilitystates-state-objects = Обекти на това състояние + .visibilitystates-new-state = Ново състояние + .visibilitystates-add-state = Добави състояние + .visibilitystates-back = Обратно към параметрите + .visibilitystates-add-to-state = Добави обекти към това състояние + .visibilitystates-no-objects-yet = Параметърът все още не управлява обекти. Добавете обекти към това състояние. + .visibilitystates-remove-from-parameter = Премахни от параметъра + .visibilitystates-same-everywhere = Еднакво във всички състояния на параметъра + .visibilitystates-same-everywhere-note = Един или повече обекти изглеждат еднакво във всички състояния на този параметър. .bvstate-current = Текущо състояние на видимост: __ocs_fmt_0__ .bvhide-select = Изберете обекти за скриване: .bvshow-select = Изберете обекти за показване: diff --git a/locales/cs-CZ/opencadstudio.ftl b/locales/cs-CZ/opencadstudio.ftl index 5f2bcbab53..1b4575642d 100644 --- a/locales/cs-CZ/opencadstudio.ftl +++ b/locales/cs-CZ/opencadstudio.ftl @@ -3594,6 +3594,42 @@ modify = .bvstate-exists = Stav viditelnosti „__ocs_fmt_0__“ již existuje. .bvstate-last = Jediný stav viditelnosti nelze odstranit. .bvstate-needs-bedit = __ocs_fmt_0__: nejprve otevřete blok v editoru bloků (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Zadejte nový parametr: + .visibilitystates-parameter-or = VISIBILITYSTATES Zadejte nový parametr nebo [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Zadejte nový stav pro __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Zadejte nový stav pro __ocs_fmt_0__ nebo [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Vyberte akci [Přidat/Odebrat/Zobrazit/Skrýt/Vybrat stav] : + .visibilitystates-add-objects = Přidat objekty + .visibilitystates-remove-objects = Odebrat objekty + .visibilitystates-make-visible = Zobrazit objekty + .visibilitystates-make-invisible = Skrýt objekty + .visibilitystates-select-state = Vybrat stav + .visibilitystates-model-space = VISIBILITYSTATES pracuje v modelovém prostoru: otevřete výkres bloku BricsCAD. + .visibilitystates-unsupported = Stavy viditelnosti zde nelze upravovat. + .visibilitystates-old-format = Stavy viditelnosti vyžadují výkres ve formátu DWG 2010 nebo novějším. + .visibilitystates-no-parameter = Parametr viditelnosti s tímto názvem neexistuje. + .visibilitystates-no-state = Stav viditelnosti s tímto názvem neexistuje. + .visibilitystates-state-exists = Tento stav viditelnosti již existuje. + .visibilitystates-cannot-move = Stav viditelnosti nelze dále přesunout. + .visibilitystates-bad-name = Zadejte název z písmen, číslic a podtržítek. + .visibilitystates-name-taken = Tento název používá jiná proměnná. + .visibilitystates-no-objects = Vyberte objekty z upravovaného prostoru. + .visibilitystates-panel-elsewhere = Stavy viditelnosti se upravují v modelovém prostoru vlastního výkresu bloku. + .visibilitystates-panel-unsupported = Stavy viditelnosti tohoto výkresu zde nelze upravovat. + .visibilitystates-first-state = První stav + .visibilitystates-panel-empty = V tomto výkresu nejsou žádné stavy viditelnosti. Klikněte na + a přidejte parametr. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (objektů: __ocs_fmt_1__) + .visibilitystates-move-up = Posunout nahoru + .visibilitystates-move-down = Posunout dolů + .visibilitystates-state-objects = Objekty tohoto stavu + .visibilitystates-new-state = Nový stav + .visibilitystates-add-state = Přidat stav + .visibilitystates-back = Zpět na parametry + .visibilitystates-add-to-state = Přidat objekty do tohoto stavu + .visibilitystates-no-objects-yet = Parametr zatím neřídí žádné objekty. Přidejte do tohoto stavu objekty. + .visibilitystates-remove-from-parameter = Odebrat z parametru + .visibilitystates-same-everywhere = Ve všech stavech parametru stejné + .visibilitystates-same-everywhere-note = Jeden nebo více objektů se ve všech stavech tohoto parametru zobrazuje stejně. .bvstate-current = Aktuální stav viditelnosti: __ocs_fmt_0__ .bvhide-select = Vyberte objekty ke skrytí: .bvshow-select = Vyberte objekty k zobrazení: diff --git a/locales/de-DE/opencadstudio.ftl b/locales/de-DE/opencadstudio.ftl index 4147fb0fd8..d3b963c379 100644 --- a/locales/de-DE/opencadstudio.ftl +++ b/locales/de-DE/opencadstudio.ftl @@ -3590,6 +3590,42 @@ modify = .bvstate-exists = Sichtbarkeitsstatus "__ocs_fmt_0__" existiert bereits. .bvstate-last = Der einzige Sichtbarkeitsstatus kann nicht gelöscht werden. .bvstate-needs-bedit = __ocs_fmt_0__: Öffnen Sie den Block zuerst im Blockeditor (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Neuen Parameter eingeben: + .visibilitystates-parameter-or = VISIBILITYSTATES Neuen Parameter eingeben oder [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Neuen Status eingeben für __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Neuen Status eingeben für __ocs_fmt_0__ oder [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Aktion auswählen [Hinzufügen/Entfernen/SIchtbar machen/Unsichtbar machen/STatus auswählen] : + .visibilitystates-add-objects = Objekte hinzufügen + .visibilitystates-remove-objects = Objekte entfernen + .visibilitystates-make-visible = Objekte sichtbar machen + .visibilitystates-make-invisible = Objekte unsichtbar machen + .visibilitystates-select-state = Status auswählen + .visibilitystates-model-space = VISIBILITYSTATES arbeitet im Modellbereich: Öffnen Sie die Zeichnung des BricsCAD-Blocks. + .visibilitystates-unsupported = Die Sichtbarkeitsstatus hier können nicht bearbeitet werden. + .visibilitystates-old-format = Sichtbarkeitsstatus brauchen eine Zeichnung im Format DWG 2010 oder neuer. + .visibilitystates-no-parameter = Kein Sichtbarkeitsparameter mit diesem Namen. + .visibilitystates-no-state = Kein Sichtbarkeitsstatus mit diesem Namen. + .visibilitystates-state-exists = Dieser Sichtbarkeitsstatus ist bereits vorhanden. + .visibilitystates-cannot-move = Der Sichtbarkeitsstatus kann nicht weiter verschoben werden. + .visibilitystates-bad-name = Geben Sie einen Namen aus Buchstaben, Ziffern und Unterstrichen ein. + .visibilitystates-name-taken = Dieser Name wird von einer anderen Variablen verwendet. + .visibilitystates-no-objects = Wählen Sie Objekte des bearbeiteten Bereichs. + .visibilitystates-panel-elsewhere = Sichtbarkeitsstatus werden im Modellbereich der Zeichnung des Blocks bearbeitet. + .visibilitystates-panel-unsupported = Die Sichtbarkeitsstatus dieser Zeichnung können hier nicht bearbeitet werden. + .visibilitystates-first-state = Erster Status + .visibilitystates-panel-empty = In dieser Zeichnung gibt es keine Sichtbarkeitsstatus. Klicken Sie auf +, um einen Parameter hinzuzufügen. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ Objekte) + .visibilitystates-move-up = Nach oben + .visibilitystates-move-down = Nach unten + .visibilitystates-state-objects = Objekte dieses Status + .visibilitystates-new-state = Neuer Status + .visibilitystates-add-state = Status hinzufügen + .visibilitystates-back = Zurück zu den Parametern + .visibilitystates-add-to-state = Objekte zu diesem Status hinzufügen + .visibilitystates-no-objects-yet = Der Parameter steuert noch keine Objekte. Fügen Sie diesem Status Objekte hinzu. + .visibilitystates-remove-from-parameter = Aus Parameter entfernen + .visibilitystates-same-everywhere = In allen Status des Parameters gleich + .visibilitystates-same-everywhere-note = Ein oder mehrere Objekte sind in allen Status dieses Parameters gleich (un)sichtbar. .bvstate-current = Aktueller Sichtbarkeitsstatus: __ocs_fmt_0__ .bvhide-select = Auszublendende Objekte wählen: .bvshow-select = Einzublendende Objekte wählen: diff --git a/locales/el-GR/opencadstudio.ftl b/locales/el-GR/opencadstudio.ftl index 989fc721f2..dd7ee0d1f2 100644 --- a/locales/el-GR/opencadstudio.ftl +++ b/locales/el-GR/opencadstudio.ftl @@ -3590,6 +3590,42 @@ modify = .bvstate-exists = Η κατάσταση ορατότητας "__ocs_fmt_0__" υπάρχει ήδη. .bvstate-last = Η μοναδική κατάσταση ορατότητας δεν μπορεί να διαγραφεί. .bvstate-needs-bedit = __ocs_fmt_0__: ανοίξτε πρώτα το μπλοκ στον επεξεργαστή μπλοκ (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Δώστε νέα παράμετρο: + .visibilitystates-parameter-or = VISIBILITYSTATES Δώστε νέα παράμετρο ή [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Δώστε νέα κατάσταση για __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Δώστε νέα κατάσταση για __ocs_fmt_0__ ή [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Επιλέξτε ενέργεια [Προσθήκη/Αφαίρεση/Εμφάνιση/Απόκρυψη/Επιλογή κατάστασης] <Προσθήκη>: + .visibilitystates-add-objects = Προσθήκη αντικειμένων + .visibilitystates-remove-objects = Αφαίρεση αντικειμένων + .visibilitystates-make-visible = Εμφάνιση αντικειμένων + .visibilitystates-make-invisible = Απόκρυψη αντικειμένων + .visibilitystates-select-state = Επιλογή κατάστασης + .visibilitystates-model-space = Η VISIBILITYSTATES λειτουργεί στον χώρο μοντέλου: ανοίξτε το σχέδιο του μπλοκ BricsCAD. + .visibilitystates-unsupported = Οι καταστάσεις ορατότητας εδώ δεν μπορούν να επεξεργαστούν. + .visibilitystates-old-format = Οι καταστάσεις ορατότητας απαιτούν σχέδιο σε μορφή DWG 2010 ή νεότερη. + .visibilitystates-no-parameter = Δεν υπάρχει παράμετρος ορατότητας με αυτό το όνομα. + .visibilitystates-no-state = Δεν υπάρχει κατάσταση ορατότητας με αυτό το όνομα. + .visibilitystates-state-exists = Αυτή η κατάσταση ορατότητας υπάρχει ήδη. + .visibilitystates-cannot-move = Η κατάσταση ορατότητας δεν μπορεί να μετακινηθεί άλλο. + .visibilitystates-bad-name = Δώστε όνομα από γράμματα, ψηφία και κάτω παύλες. + .visibilitystates-name-taken = Αυτό το όνομα χρησιμοποιείται από άλλη μεταβλητή. + .visibilitystates-no-objects = Επιλέξτε αντικείμενα του χώρου που επεξεργάζεστε. + .visibilitystates-panel-elsewhere = Οι καταστάσεις ορατότητας επεξεργάζονται στον χώρο μοντέλου του σχεδίου του ίδιου του μπλοκ. + .visibilitystates-panel-unsupported = Οι καταστάσεις ορατότητας αυτού του σχεδίου δεν μπορούν να επεξεργαστούν εδώ. + .visibilitystates-first-state = Πρώτη κατάσταση + .visibilitystates-panel-empty = Δεν υπάρχουν καταστάσεις ορατότητας σε αυτό το σχέδιο. Κάντε κλικ στο + για να προσθέσετε παράμετρο. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ αντικείμενα) + .visibilitystates-move-up = Μετακίνηση πάνω + .visibilitystates-move-down = Μετακίνηση κάτω + .visibilitystates-state-objects = Αντικείμενα αυτής της κατάστασης + .visibilitystates-new-state = Νέα κατάσταση + .visibilitystates-add-state = Προσθήκη κατάστασης + .visibilitystates-back = Επιστροφή στις παραμέτρους + .visibilitystates-add-to-state = Προσθήκη αντικειμένων σε αυτή την κατάσταση + .visibilitystates-no-objects-yet = Η παράμετρος δεν ελέγχει ακόμη αντικείμενα. Προσθέστε αντικείμενα σε αυτή την κατάσταση. + .visibilitystates-remove-from-parameter = Αφαίρεση από την παράμετρο + .visibilitystates-same-everywhere = Ίδια εμφάνιση σε όλες τις καταστάσεις της παραμέτρου + .visibilitystates-same-everywhere-note = Ένα ή περισσότερα αντικείμενα εμφανίζονται ίδια σε όλες τις καταστάσεις αυτής της παραμέτρου. .bvstate-current = Τρέχουσα κατάσταση ορατότητας: __ocs_fmt_0__ .bvhide-select = Επιλέξτε αντικείμενα για απόκρυψη: .bvshow-select = Επιλέξτε αντικείμενα για εμφάνιση: diff --git a/locales/en-US/opencadstudio.ftl b/locales/en-US/opencadstudio.ftl index adb4a30937..1025816ed6 100644 --- a/locales/en-US/opencadstudio.ftl +++ b/locales/en-US/opencadstudio.ftl @@ -3591,6 +3591,42 @@ modify = .bvstate-exists = Visibility state "__ocs_fmt_0__" already exists. .bvstate-last = The only visibility state cannot be deleted. .bvstate-needs-bedit = __ocs_fmt_0__: open the block in the Block Editor first (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Enter a new parameter: + .visibilitystates-parameter-or = VISIBILITYSTATES Enter a new parameter or [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Enter a new state for __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Enter a new state for __ocs_fmt_0__ or [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Select action [Add objects/Remove objects/make objects Visible/make objects Invisible/Select state] : + .visibilitystates-add-objects = Add objects + .visibilitystates-remove-objects = Remove objects + .visibilitystates-make-visible = make objects Visible + .visibilitystates-make-invisible = make objects Invisible + .visibilitystates-select-state = Select state + .visibilitystates-model-space = VISIBILITYSTATES works in model space: open the drawing of the BricsCAD block. + .visibilitystates-unsupported = The visibility states here cannot be edited. + .visibilitystates-old-format = Visibility states need a drawing in DWG 2010 format or later. + .visibilitystates-no-parameter = No visibility parameter of that name. + .visibilitystates-no-state = No visibility state of that name. + .visibilitystates-state-exists = That visibility state exists already. + .visibilitystates-cannot-move = The visibility state cannot move further. + .visibilitystates-bad-name = Enter a name of letters, digits and underscores. + .visibilitystates-name-taken = That name is used by another variable. + .visibilitystates-no-objects = Select objects of the space being edited. + .visibilitystates-panel-elsewhere = Visibility states are edited in model space of the block's own drawing. + .visibilitystates-panel-unsupported = The visibility states of this drawing cannot be edited here. + .visibilitystates-first-state = First state + .visibilitystates-panel-empty = There are no visibility states in this drawing. Click + to add a parameter. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objects) + .visibilitystates-move-up = Move up + .visibilitystates-move-down = Move down + .visibilitystates-state-objects = Objects of this state + .visibilitystates-new-state = New state + .visibilitystates-add-state = Add state + .visibilitystates-back = Back to the parameters + .visibilitystates-add-to-state = Add objects to this state + .visibilitystates-no-objects-yet = The parameter rules no objects yet. Add objects to this state. + .visibilitystates-remove-from-parameter = Remove from parameter + .visibilitystates-same-everywhere = Shown the same in every state of the parameter + .visibilitystates-same-everywhere-note = One or more objects show the same in every state of this parameter. .bvstate-current = Current visibility state: __ocs_fmt_0__ .bvhide-select = Select objects to hide: .bvshow-select = Select objects to make visible: diff --git a/locales/es-ES/opencadstudio.ftl b/locales/es-ES/opencadstudio.ftl index 7d23d3eda9..01926c72fe 100644 --- a/locales/es-ES/opencadstudio.ftl +++ b/locales/es-ES/opencadstudio.ftl @@ -3590,6 +3590,42 @@ modify = .bvstate-exists = El estado de visibilidad "__ocs_fmt_0__" ya existe. .bvstate-last = No se puede suprimir el único estado de visibilidad. .bvstate-needs-bedit = __ocs_fmt_0__: abra primero el bloque en el Editor de bloques (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Indique un nuevo parámetro: + .visibilitystates-parameter-or = VISIBILITYSTATES Indique un nuevo parámetro o [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Indique un nuevo estado para __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Indique un nuevo estado para __ocs_fmt_0__ o [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Seleccione una acción [Añadir/Quitar/Mostrar/Ocultar/Seleccionar estado] : + .visibilitystates-add-objects = Añadir objetos + .visibilitystates-remove-objects = Quitar objetos + .visibilitystates-make-visible = Mostrar objetos + .visibilitystates-make-invisible = Ocultar objetos + .visibilitystates-select-state = Seleccionar estado + .visibilitystates-model-space = VISIBILITYSTATES funciona en el espacio modelo: abra el dibujo del bloque de BricsCAD. + .visibilitystates-unsupported = Aquí no se pueden editar los estados de visibilidad. + .visibilitystates-old-format = Los estados de visibilidad requieren un dibujo en formato DWG 2010 o posterior. + .visibilitystates-no-parameter = No hay ningún parámetro de visibilidad con ese nombre. + .visibilitystates-no-state = No hay ningún estado de visibilidad con ese nombre. + .visibilitystates-state-exists = Ese estado de visibilidad ya existe. + .visibilitystates-cannot-move = El estado de visibilidad no se puede desplazar más. + .visibilitystates-bad-name = Indique un nombre con letras, dígitos y guiones bajos. + .visibilitystates-name-taken = Ese nombre lo usa otra variable. + .visibilitystates-no-objects = Seleccione objetos del espacio que se está editando. + .visibilitystates-panel-elsewhere = Los estados de visibilidad se editan en el espacio modelo del propio dibujo del bloque. + .visibilitystates-panel-unsupported = Los estados de visibilidad de este dibujo no se pueden editar aquí. + .visibilitystates-first-state = Primer estado + .visibilitystates-panel-empty = No hay estados de visibilidad en este dibujo. Haga clic en + para añadir un parámetro. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objetos) + .visibilitystates-move-up = Subir + .visibilitystates-move-down = Bajar + .visibilitystates-state-objects = Objetos de este estado + .visibilitystates-new-state = Nuevo estado + .visibilitystates-add-state = Añadir estado + .visibilitystates-back = Volver a los parámetros + .visibilitystates-add-to-state = Añadir objetos a este estado + .visibilitystates-no-objects-yet = El parámetro aún no controla ningún objeto. Añada objetos a este estado. + .visibilitystates-remove-from-parameter = Quitar del parámetro + .visibilitystates-same-everywhere = Igual en todos los estados del parámetro + .visibilitystates-same-everywhere-note = Uno o varios objetos se muestran igual en todos los estados de este parámetro. .bvstate-current = Estado de visibilidad actual: __ocs_fmt_0__ .bvhide-select = Seleccione los objetos que se ocultarán: .bvshow-select = Seleccione los objetos que se harán visibles: diff --git a/locales/fi-FI/opencadstudio.ftl b/locales/fi-FI/opencadstudio.ftl index 4ea8c93e21..df92ac0110 100644 --- a/locales/fi-FI/opencadstudio.ftl +++ b/locales/fi-FI/opencadstudio.ftl @@ -3589,6 +3589,42 @@ modify = .bvstate-exists = Näkyvyystila "__ocs_fmt_0__" on jo olemassa. .bvstate-last = Ainoaa näkyvyystilaa ei voi poistaa. .bvstate-needs-bedit = __ocs_fmt_0__: avaa lohko ensin lohkoeditorissa (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Anna uusi parametri: + .visibilitystates-parameter-or = VISIBILITYSTATES Anna uusi parametri tai [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Anna uusi tila parametrille __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Anna uusi tila parametrille __ocs_fmt_0__ tai [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Valitse toiminto [Lisää/Poista/Näytä/Piilota/Valitse tila] : + .visibilitystates-add-objects = Lisää objekteja + .visibilitystates-remove-objects = Poista objekteja + .visibilitystates-make-visible = Näytä objektit + .visibilitystates-make-invisible = Piilota objektit + .visibilitystates-select-state = Valitse tila + .visibilitystates-model-space = VISIBILITYSTATES toimii mallitilassa: avaa BricsCAD-lohkon piirustus. + .visibilitystates-unsupported = Näkyvyystiloja ei voi muokata tässä. + .visibilitystates-old-format = Näkyvyystilat edellyttävät DWG 2010 -muotoista tai uudempaa piirustusta. + .visibilitystates-no-parameter = Tämännimistä näkyvyysparametria ei ole. + .visibilitystates-no-state = Tämännimistä näkyvyystilaa ei ole. + .visibilitystates-state-exists = Näkyvyystila on jo olemassa. + .visibilitystates-cannot-move = Näkyvyystilaa ei voi siirtää pidemmälle. + .visibilitystates-bad-name = Anna nimi, jossa on vain kirjaimia, numeroita ja alaviivoja. + .visibilitystates-name-taken = Nimi on toisen muuttujan käytössä. + .visibilitystates-no-objects = Valitse objekteja muokattavasta tilasta. + .visibilitystates-panel-elsewhere = Näkyvyystiloja muokataan lohkon oman piirustuksen mallitilassa. + .visibilitystates-panel-unsupported = Tämän piirustuksen näkyvyystiloja ei voi muokata tässä. + .visibilitystates-first-state = Ensimmäinen tila + .visibilitystates-panel-empty = Tässä piirustuksessa ei ole näkyvyystiloja. Lisää parametri napsauttamalla +. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objektia) + .visibilitystates-move-up = Siirrä ylös + .visibilitystates-move-down = Siirrä alas + .visibilitystates-state-objects = Tämän tilan objektit + .visibilitystates-new-state = Uusi tila + .visibilitystates-add-state = Lisää tila + .visibilitystates-back = Takaisin parametreihin + .visibilitystates-add-to-state = Lisää objekteja tähän tilaan + .visibilitystates-no-objects-yet = Parametri ei vielä ohjaa objekteja. Lisää objekteja tähän tilaan. + .visibilitystates-remove-from-parameter = Poista parametrista + .visibilitystates-same-everywhere = Sama kaikissa parametrin tiloissa + .visibilitystates-same-everywhere-note = Yksi tai useampi objekti näkyy samoin kaikissa tämän parametrin tiloissa. .bvstate-current = Nykyinen näkyvyystila: __ocs_fmt_0__ .bvhide-select = Valitse piilotettavat objektit: .bvshow-select = Valitse näytettävät objektit: diff --git a/locales/fr-FR/opencadstudio.ftl b/locales/fr-FR/opencadstudio.ftl index f14d31d04f..6aef2f892b 100644 --- a/locales/fr-FR/opencadstudio.ftl +++ b/locales/fr-FR/opencadstudio.ftl @@ -3590,6 +3590,42 @@ modify = .bvstate-exists = L'état de visibilité "__ocs_fmt_0__" existe déjà. .bvstate-last = Le seul état de visibilité ne peut pas être supprimé. .bvstate-needs-bedit = __ocs_fmt_0__ : ouvrez d'abord le bloc dans l'éditeur de blocs (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Entrez un nouveau paramètre : + .visibilitystates-parameter-or = VISIBILITYSTATES Entrez un nouveau paramètre ou [__ocs_fmt_0__] : + .visibilitystates-state = VISIBILITYSTATES Entrez un nouvel état pour __ocs_fmt_0__ : + .visibilitystates-state-or = VISIBILITYSTATES Entrez un nouvel état pour __ocs_fmt_0__ ou [__ocs_fmt_1__] : + .visibilitystates-action = VISIBILITYSTATES Choisissez une action [Ajouter/Retirer/Montrer/Cacher/Sélectionner l'état] : + .visibilitystates-add-objects = Ajouter des objets + .visibilitystates-remove-objects = Retirer des objets + .visibilitystates-make-visible = Rendre les objets visibles + .visibilitystates-make-invisible = Rendre les objets invisibles + .visibilitystates-select-state = Sélectionner l'état + .visibilitystates-model-space = VISIBILITYSTATES fonctionne dans l'espace objet : ouvrez le dessin du bloc BricsCAD. + .visibilitystates-unsupported = Les états de visibilité ne sont pas modifiables ici. + .visibilitystates-old-format = Les états de visibilité nécessitent un dessin au format DWG 2010 ou ultérieur. + .visibilitystates-no-parameter = Aucun paramètre de visibilité de ce nom. + .visibilitystates-no-state = Aucun état de visibilité de ce nom. + .visibilitystates-state-exists = Cet état de visibilité existe déjà. + .visibilitystates-cannot-move = L'état de visibilité ne peut pas être déplacé davantage. + .visibilitystates-bad-name = Entrez un nom composé de lettres, de chiffres et de traits de soulignement. + .visibilitystates-name-taken = Ce nom est utilisé par une autre variable. + .visibilitystates-no-objects = Sélectionnez des objets de l'espace en cours de modification. + .visibilitystates-panel-elsewhere = Les états de visibilité se modifient dans l'espace objet du dessin propre au bloc. + .visibilitystates-panel-unsupported = Les états de visibilité de ce dessin ne sont pas modifiables ici. + .visibilitystates-first-state = Premier état + .visibilitystates-panel-empty = Ce dessin ne contient aucun état de visibilité. Cliquez sur + pour ajouter un paramètre. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objets) + .visibilitystates-move-up = Monter + .visibilitystates-move-down = Descendre + .visibilitystates-state-objects = Objets de cet état + .visibilitystates-new-state = Nouvel état + .visibilitystates-add-state = Ajouter un état + .visibilitystates-back = Retour aux paramètres + .visibilitystates-add-to-state = Ajouter des objets à cet état + .visibilitystates-no-objects-yet = Le paramètre ne pilote encore aucun objet. Ajoutez des objets à cet état. + .visibilitystates-remove-from-parameter = Retirer du paramètre + .visibilitystates-same-everywhere = Identique dans tous les états du paramètre + .visibilitystates-same-everywhere-note = Un ou plusieurs objets s'affichent de la même façon dans tous les états de ce paramètre. .bvstate-current = État de visibilité courant : __ocs_fmt_0__ .bvhide-select = Sélectionnez les objets à masquer : .bvshow-select = Sélectionnez les objets à rendre visibles : diff --git a/locales/hi-IN/opencadstudio.ftl b/locales/hi-IN/opencadstudio.ftl index b59595fe61..6ed6cc118b 100644 --- a/locales/hi-IN/opencadstudio.ftl +++ b/locales/hi-IN/opencadstudio.ftl @@ -3578,6 +3578,42 @@ modify = .bvstate-exists = दृश्यता स्थिति "__ocs_fmt_0__" पहले से मौजूद है। .bvstate-last = एकमात्र दृश्यता स्थिति हटाई नहीं जा सकती। .bvstate-needs-bedit = __ocs_fmt_0__: पहले ब्लॉक को ब्लॉक एडिटर में खोलें (BEDIT)। + .visibilitystates-parameter = VISIBILITYSTATES नया पैरामीटर दर्ज करें: + .visibilitystates-parameter-or = VISIBILITYSTATES नया पैरामीटर दर्ज करें या [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES __ocs_fmt_0__ के लिए नई स्थिति दर्ज करें: + .visibilitystates-state-or = VISIBILITYSTATES __ocs_fmt_0__ के लिए नई स्थिति दर्ज करें या [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES क्रिया चुनें [जोड़ें/हटाएँ/दिखाएँ/छिपाएँ/स्थिति चुनें] <जोड़ें>: + .visibilitystates-add-objects = ऑब्जेक्ट जोड़ें + .visibilitystates-remove-objects = ऑब्जेक्ट हटाएँ + .visibilitystates-make-visible = ऑब्जेक्ट दिखाएँ + .visibilitystates-make-invisible = ऑब्जेक्ट छिपाएँ + .visibilitystates-select-state = स्थिति चुनें + .visibilitystates-model-space = VISIBILITYSTATES मॉडल स्पेस में काम करता है: BricsCAD ब्लॉक की ड्रॉइंग खोलें। + .visibilitystates-unsupported = यहाँ दृश्यता स्थितियाँ संपादित नहीं की जा सकतीं। + .visibilitystates-old-format = दृश्यता स्थितियों के लिए DWG 2010 या बाद के फ़ॉर्मैट की ड्रॉइंग आवश्यक है। + .visibilitystates-no-parameter = इस नाम का कोई दृश्यता पैरामीटर नहीं है। + .visibilitystates-no-state = इस नाम की कोई दृश्यता स्थिति नहीं है। + .visibilitystates-state-exists = यह दृश्यता स्थिति पहले से मौजूद है। + .visibilitystates-cannot-move = दृश्यता स्थिति को और आगे नहीं ले जाया जा सकता। + .visibilitystates-bad-name = अक्षरों, अंकों और अंडरस्कोर से बना नाम दर्ज करें। + .visibilitystates-name-taken = यह नाम किसी अन्य वेरिएबल द्वारा उपयोग किया जा रहा है। + .visibilitystates-no-objects = संपादित हो रहे स्पेस के ऑब्जेक्ट चुनें। + .visibilitystates-panel-elsewhere = दृश्यता स्थितियाँ ब्लॉक की अपनी ड्रॉइंग के मॉडल स्पेस में संपादित की जाती हैं। + .visibilitystates-panel-unsupported = इस ड्रॉइंग की दृश्यता स्थितियाँ यहाँ संपादित नहीं की जा सकतीं। + .visibilitystates-first-state = पहली स्थिति + .visibilitystates-panel-empty = इस ड्रॉइंग में कोई दृश्यता स्थिति नहीं है। पैरामीटर जोड़ने के लिए + पर क्लिक करें। + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ ऑब्जेक्ट) + .visibilitystates-move-up = ऊपर ले जाएँ + .visibilitystates-move-down = नीचे ले जाएँ + .visibilitystates-state-objects = इस स्थिति के ऑब्जेक्ट + .visibilitystates-new-state = नई स्थिति + .visibilitystates-add-state = स्थिति जोड़ें + .visibilitystates-back = पैरामीटर पर वापस जाएँ + .visibilitystates-add-to-state = इस स्थिति में ऑब्जेक्ट जोड़ें + .visibilitystates-no-objects-yet = पैरामीटर अभी किसी ऑब्जेक्ट को नियंत्रित नहीं करता। इस स्थिति में ऑब्जेक्ट जोड़ें। + .visibilitystates-remove-from-parameter = पैरामीटर से हटाएँ + .visibilitystates-same-everywhere = पैरामीटर की हर स्थिति में एक जैसा + .visibilitystates-same-everywhere-note = एक या अधिक ऑब्जेक्ट इस पैरामीटर की हर स्थिति में एक जैसे दिखते हैं। .bvstate-current = वर्तमान दृश्यता स्थिति: __ocs_fmt_0__ .bvhide-select = छिपाने के लिए ऑब्जेक्ट चुनें: .bvshow-select = दिखाने के लिए ऑब्जेक्ट चुनें: diff --git a/locales/hu-HU/opencadstudio.ftl b/locales/hu-HU/opencadstudio.ftl index 9e8ae9db60..adb14f00ae 100644 --- a/locales/hu-HU/opencadstudio.ftl +++ b/locales/hu-HU/opencadstudio.ftl @@ -3586,6 +3586,42 @@ modify = .bvstate-exists = A(z) „__ocs_fmt_0__” láthatósági állapot már létezik. .bvstate-last = Az egyetlen láthatósági állapot nem törölhető. .bvstate-needs-bedit = __ocs_fmt_0__: előbb nyissa meg a blokkot a blokkszerkesztőben (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Adjon meg új paramétert: + .visibilitystates-parameter-or = VISIBILITYSTATES Adjon meg új paramétert vagy [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Adjon meg új állapotot a(z) __ocs_fmt_0__ paraméterhez: + .visibilitystates-state-or = VISIBILITYSTATES Adjon meg új állapotot a(z) __ocs_fmt_0__ paraméterhez vagy [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Válasszon műveletet [Hozzáadás/Eltávolítás/Megjelenítés/Rejtés/Állapot kiválasztása] : + .visibilitystates-add-objects = Objektumok hozzáadása + .visibilitystates-remove-objects = Objektumok eltávolítása + .visibilitystates-make-visible = Objektumok megjelenítése + .visibilitystates-make-invisible = Objektumok elrejtése + .visibilitystates-select-state = Állapot kiválasztása + .visibilitystates-model-space = A VISIBILITYSTATES modelltérben működik: nyissa meg a BricsCAD-blokk rajzát. + .visibilitystates-unsupported = Az itteni láthatósági állapotok nem szerkeszthetők. + .visibilitystates-old-format = A láthatósági állapotokhoz DWG 2010 vagy újabb formátumú rajz szükséges. + .visibilitystates-no-parameter = Nincs ilyen nevű láthatósági paraméter. + .visibilitystates-no-state = Nincs ilyen nevű láthatósági állapot. + .visibilitystates-state-exists = Ez a láthatósági állapot már létezik. + .visibilitystates-cannot-move = A láthatósági állapot nem mozgatható tovább. + .visibilitystates-bad-name = Betűkből, számjegyekből és aláhúzásjelekből álló nevet adjon meg. + .visibilitystates-name-taken = Ezt a nevet egy másik változó használja. + .visibilitystates-no-objects = A szerkesztett tér objektumait válassza ki. + .visibilitystates-panel-elsewhere = A láthatósági állapotok a blokk saját rajzának modellterében szerkeszthetők. + .visibilitystates-panel-unsupported = Ennek a rajznak a láthatósági állapotai itt nem szerkeszthetők. + .visibilitystates-first-state = Első állapot + .visibilitystates-panel-empty = Ebben a rajzban nincsenek láthatósági állapotok. Paraméter hozzáadásához kattintson a + gombra. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objektum) + .visibilitystates-move-up = Feljebb + .visibilitystates-move-down = Lejjebb + .visibilitystates-state-objects = Az állapot objektumai + .visibilitystates-new-state = Új állapot + .visibilitystates-add-state = Állapot hozzáadása + .visibilitystates-back = Vissza a paraméterekhez + .visibilitystates-add-to-state = Objektumok hozzáadása ehhez az állapothoz + .visibilitystates-no-objects-yet = A paraméter még nem vezérel objektumokat. Adjon objektumokat ehhez az állapothoz. + .visibilitystates-remove-from-parameter = Eltávolítás a paraméterből + .visibilitystates-same-everywhere = A paraméter minden állapotában azonos + .visibilitystates-same-everywhere-note = Egy vagy több objektum a paraméter minden állapotában azonosan jelenik meg. .bvstate-current = Aktuális láthatósági állapot: __ocs_fmt_0__ .bvhide-select = Jelölje ki az elrejtendő objektumokat: .bvshow-select = Jelölje ki a megjelenítendő objektumokat: diff --git a/locales/it-IT/opencadstudio.ftl b/locales/it-IT/opencadstudio.ftl index 699ef16044..66021a85e2 100644 --- a/locales/it-IT/opencadstudio.ftl +++ b/locales/it-IT/opencadstudio.ftl @@ -3589,6 +3589,42 @@ modify = .bvstate-exists = Lo stato di visibilità "__ocs_fmt_0__" esiste già. .bvstate-last = L'unico stato di visibilità non può essere eliminato. .bvstate-needs-bedit = __ocs_fmt_0__: aprire prima il blocco nell'Editor blocchi (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Immettere un nuovo parametro: + .visibilitystates-parameter-or = VISIBILITYSTATES Immettere un nuovo parametro o [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Immettere un nuovo stato per __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Immettere un nuovo stato per __ocs_fmt_0__ o [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Selezionare un'azione [Aggiungi/Rimuovi/Mostra/Nascondi/Seleziona stato] : + .visibilitystates-add-objects = Aggiungi oggetti + .visibilitystates-remove-objects = Rimuovi oggetti + .visibilitystates-make-visible = Rendi visibili gli oggetti + .visibilitystates-make-invisible = Rendi invisibili gli oggetti + .visibilitystates-select-state = Seleziona stato + .visibilitystates-model-space = VISIBILITYSTATES funziona nello spazio modello: aprire il disegno del blocco BricsCAD. + .visibilitystates-unsupported = Gli stati di visibilità qui non sono modificabili. + .visibilitystates-old-format = Gli stati di visibilità richiedono un disegno in formato DWG 2010 o successivo. + .visibilitystates-no-parameter = Nessun parametro di visibilità con questo nome. + .visibilitystates-no-state = Nessuno stato di visibilità con questo nome. + .visibilitystates-state-exists = Questo stato di visibilità esiste già. + .visibilitystates-cannot-move = Lo stato di visibilità non può essere spostato oltre. + .visibilitystates-bad-name = Immettere un nome composto da lettere, cifre e caratteri di sottolineatura. + .visibilitystates-name-taken = Questo nome è usato da un'altra variabile. + .visibilitystates-no-objects = Selezionare oggetti dello spazio in modifica. + .visibilitystates-panel-elsewhere = Gli stati di visibilità si modificano nello spazio modello del disegno del blocco stesso. + .visibilitystates-panel-unsupported = Gli stati di visibilità di questo disegno non sono modificabili qui. + .visibilitystates-first-state = Primo stato + .visibilitystates-panel-empty = In questo disegno non ci sono stati di visibilità. Fare clic su + per aggiungere un parametro. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ oggetti) + .visibilitystates-move-up = Sposta su + .visibilitystates-move-down = Sposta giù + .visibilitystates-state-objects = Oggetti di questo stato + .visibilitystates-new-state = Nuovo stato + .visibilitystates-add-state = Aggiungi stato + .visibilitystates-back = Torna ai parametri + .visibilitystates-add-to-state = Aggiungi oggetti a questo stato + .visibilitystates-no-objects-yet = Il parametro non controlla ancora alcun oggetto. Aggiungere oggetti a questo stato. + .visibilitystates-remove-from-parameter = Rimuovi dal parametro + .visibilitystates-same-everywhere = Uguale in tutti gli stati del parametro + .visibilitystates-same-everywhere-note = Uno o più oggetti appaiono uguali in tutti gli stati di questo parametro. .bvstate-current = Stato di visibilità corrente: __ocs_fmt_0__ .bvhide-select = Selezionare gli oggetti da nascondere: .bvshow-select = Selezionare gli oggetti da rendere visibili: diff --git a/locales/ja-JP/opencadstudio.ftl b/locales/ja-JP/opencadstudio.ftl index 3aadcf6bd3..95601f52ba 100644 --- a/locales/ja-JP/opencadstudio.ftl +++ b/locales/ja-JP/opencadstudio.ftl @@ -3580,6 +3580,42 @@ modify = .bvstate-exists = 可視性状態「__ocs_fmt_0__」は既に存在します。 .bvstate-last = 唯一の可視性状態は削除できません。 .bvstate-needs-bedit = __ocs_fmt_0__: 先にブロック エディタでブロックを開いてください (BEDIT)。 + .visibilitystates-parameter = VISIBILITYSTATES 新しいパラメーターを入力: + .visibilitystates-parameter-or = VISIBILITYSTATES 新しいパラメーターを入力 または [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES __ocs_fmt_0__ の新しい状態を入力: + .visibilitystates-state-or = VISIBILITYSTATES __ocs_fmt_0__ の新しい状態を入力 または [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES 操作を選択 [追加/除外/表示/非表示/状態を選択] <追加>: + .visibilitystates-add-objects = オブジェクトを追加 + .visibilitystates-remove-objects = オブジェクトを除外 + .visibilitystates-make-visible = オブジェクトを表示 + .visibilitystates-make-invisible = オブジェクトを非表示 + .visibilitystates-select-state = 状態を選択 + .visibilitystates-model-space = VISIBILITYSTATES はモデル空間で動作します: BricsCAD ブロックの図面を開いてください。 + .visibilitystates-unsupported = ここでは可視性状態を編集できません。 + .visibilitystates-old-format = 可視性状態には DWG 2010 以降の形式の図面が必要です。 + .visibilitystates-no-parameter = その名前の可視性パラメーターはありません。 + .visibilitystates-no-state = その名前の可視性状態はありません。 + .visibilitystates-state-exists = その可視性状態は既に存在します。 + .visibilitystates-cannot-move = 可視性状態をこれ以上移動できません。 + .visibilitystates-bad-name = 文字、数字、アンダースコアで構成される名前を入力してください。 + .visibilitystates-name-taken = その名前は別の変数で使用されています。 + .visibilitystates-no-objects = 編集中の空間のオブジェクトを選択してください。 + .visibilitystates-panel-elsewhere = 可視性状態はブロック自体の図面のモデル空間で編集します。 + .visibilitystates-panel-unsupported = この図面の可視性状態はここでは編集できません。 + .visibilitystates-first-state = 最初の状態 + .visibilitystates-panel-empty = この図面には可視性状態がありません。+ をクリックしてパラメーターを追加してください。 + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ 個のオブジェクト) + .visibilitystates-move-up = 上へ移動 + .visibilitystates-move-down = 下へ移動 + .visibilitystates-state-objects = この状態のオブジェクト + .visibilitystates-new-state = 新しい状態 + .visibilitystates-add-state = 状態を追加 + .visibilitystates-back = パラメーターに戻る + .visibilitystates-add-to-state = この状態にオブジェクトを追加 + .visibilitystates-no-objects-yet = このパラメーターはまだオブジェクトを制御していません。この状態にオブジェクトを追加してください。 + .visibilitystates-remove-from-parameter = パラメーターから除外 + .visibilitystates-same-everywhere = パラメーターのすべての状態で同じ表示 + .visibilitystates-same-everywhere-note = 1 つ以上のオブジェクトが、このパラメーターのすべての状態で同じように表示されます。 .bvstate-current = 現在の可視性状態: __ocs_fmt_0__ .bvhide-select = 非表示にするオブジェクトを選択: .bvshow-select = 表示するオブジェクトを選択: diff --git a/locales/ko-KR/opencadstudio.ftl b/locales/ko-KR/opencadstudio.ftl index f07d3a936f..d2270baac6 100644 --- a/locales/ko-KR/opencadstudio.ftl +++ b/locales/ko-KR/opencadstudio.ftl @@ -3589,6 +3589,42 @@ modify = .bvstate-exists = 가시성 상태 "__ocs_fmt_0__"이(가) 이미 있습니다. .bvstate-last = 유일한 가시성 상태는 삭제할 수 없습니다. .bvstate-needs-bedit = __ocs_fmt_0__: 먼저 블록 편집기에서 블록을 여십시오(BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES 새 매개변수 입력: + .visibilitystates-parameter-or = VISIBILITYSTATES 새 매개변수 입력 또는 [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES __ocs_fmt_0__의 새 상태 입력: + .visibilitystates-state-or = VISIBILITYSTATES __ocs_fmt_0__의 새 상태 입력 또는 [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES 작업 선택 [추가/제거/표시/숨기기/상태 선택] <추가>: + .visibilitystates-add-objects = 객체 추가 + .visibilitystates-remove-objects = 객체 제거 + .visibilitystates-make-visible = 객체 표시 + .visibilitystates-make-invisible = 객체 숨기기 + .visibilitystates-select-state = 상태 선택 + .visibilitystates-model-space = VISIBILITYSTATES는 모형 공간에서 작동합니다: BricsCAD 블록의 도면을 여십시오. + .visibilitystates-unsupported = 여기서는 가시성 상태를 편집할 수 없습니다. + .visibilitystates-old-format = 가시성 상태에는 DWG 2010 이상 형식의 도면이 필요합니다. + .visibilitystates-no-parameter = 해당 이름의 가시성 매개변수가 없습니다. + .visibilitystates-no-state = 해당 이름의 가시성 상태가 없습니다. + .visibilitystates-state-exists = 해당 가시성 상태가 이미 있습니다. + .visibilitystates-cannot-move = 가시성 상태를 더 이상 이동할 수 없습니다. + .visibilitystates-bad-name = 문자, 숫자, 밑줄로 된 이름을 입력하십시오. + .visibilitystates-name-taken = 다른 변수가 이 이름을 사용하고 있습니다. + .visibilitystates-no-objects = 편집 중인 공간의 객체를 선택하십시오. + .visibilitystates-panel-elsewhere = 가시성 상태는 블록 자체 도면의 모형 공간에서 편집합니다. + .visibilitystates-panel-unsupported = 이 도면의 가시성 상태는 여기서 편집할 수 없습니다. + .visibilitystates-first-state = 첫 번째 상태 + .visibilitystates-panel-empty = 이 도면에는 가시성 상태가 없습니다. +를 클릭하여 매개변수를 추가하십시오. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (객체 __ocs_fmt_1__개) + .visibilitystates-move-up = 위로 이동 + .visibilitystates-move-down = 아래로 이동 + .visibilitystates-state-objects = 이 상태의 객체 + .visibilitystates-new-state = 새 상태 + .visibilitystates-add-state = 상태 추가 + .visibilitystates-back = 매개변수로 돌아가기 + .visibilitystates-add-to-state = 이 상태에 객체 추가 + .visibilitystates-no-objects-yet = 매개변수가 아직 객체를 제어하지 않습니다. 이 상태에 객체를 추가하십시오. + .visibilitystates-remove-from-parameter = 매개변수에서 제거 + .visibilitystates-same-everywhere = 매개변수의 모든 상태에서 동일하게 표시 + .visibilitystates-same-everywhere-note = 하나 이상의 객체가 이 매개변수의 모든 상태에서 동일하게 표시됩니다. .bvstate-current = 현재 가시성 상태: __ocs_fmt_0__ .bvhide-select = 숨길 객체 선택: .bvshow-select = 표시할 객체 선택: diff --git a/locales/lo-LA/opencadstudio.ftl b/locales/lo-LA/opencadstudio.ftl index 691ad84891..ca5302c796 100644 --- a/locales/lo-LA/opencadstudio.ftl +++ b/locales/lo-LA/opencadstudio.ftl @@ -3591,6 +3591,42 @@ modify = .bvstate-exists = ສະຖານະການເບິ່ງເຫັນ "__ocs_fmt_0__" ມີຢູ່ແລ້ວ. .bvstate-last = ບໍ່ສາມາດລຶບສະຖານະການເບິ່ງເຫັນດຽວໄດ້. .bvstate-needs-bedit = __ocs_fmt_0__: ເປີດບລັອກໃນຕົວແກ້ໄຂບລັອກກ່ອນ (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES ປ້ອນພາຣາມິເຕີໃໝ່: + .visibilitystates-parameter-or = VISIBILITYSTATES ປ້ອນພາຣາມິເຕີໃໝ່ ຫຼື [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES ປ້ອນສະຖານະໃໝ່ສຳລັບ __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES ປ້ອນສະຖານະໃໝ່ສຳລັບ __ocs_fmt_0__ ຫຼື [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES ເລືອກການກະທຳ [ເພີ່ມ/ເອົາອອກ/ສະແດງ/ເຊື່ອງ/ເລືອກສະຖານະ] <ເພີ່ມ>: + .visibilitystates-add-objects = ເພີ່ມວັດຖຸ + .visibilitystates-remove-objects = ເອົາວັດຖຸອອກ + .visibilitystates-make-visible = ສະແດງວັດຖຸ + .visibilitystates-make-invisible = ເຊື່ອງວັດຖຸ + .visibilitystates-select-state = ເລືອກສະຖານະ + .visibilitystates-model-space = VISIBILITYSTATES ເຮັດວຽກໃນພື້ນທີ່ໂມເດວ: ເປີດແບບແຕ້ມຂອງບລັອກ BricsCAD. + .visibilitystates-unsupported = ບໍ່ສາມາດແກ້ໄຂສະຖານະການເບິ່ງເຫັນຢູ່ນີ້ໄດ້. + .visibilitystates-old-format = ສະຖານະການເບິ່ງເຫັນຕ້ອງການແບບແຕ້ມໃນຮູບແບບ DWG 2010 ຫຼືໃໝ່ກວ່າ. + .visibilitystates-no-parameter = ບໍ່ມີພາຣາມິເຕີການເບິ່ງເຫັນທີ່ມີຊື່ນີ້. + .visibilitystates-no-state = ບໍ່ມີສະຖານະການເບິ່ງເຫັນທີ່ມີຊື່ນີ້. + .visibilitystates-state-exists = ສະຖານະການເບິ່ງເຫັນນີ້ມີຢູ່ແລ້ວ. + .visibilitystates-cannot-move = ບໍ່ສາມາດຍ້າຍສະຖານະການເບິ່ງເຫັນໄປຕື່ມໄດ້. + .visibilitystates-bad-name = ປ້ອນຊື່ທີ່ປະກອບດ້ວຍຕົວອັກສອນ, ຕົວເລກ ແລະ ຂີດກ້ອງ. + .visibilitystates-name-taken = ຊື່ນີ້ຖືກໃຊ້ໂດຍຕົວແປອື່ນແລ້ວ. + .visibilitystates-no-objects = ເລືອກວັດຖຸຂອງພື້ນທີ່ທີ່ກຳລັງແກ້ໄຂ. + .visibilitystates-panel-elsewhere = ສະຖານະການເບິ່ງເຫັນຖືກແກ້ໄຂໃນພື້ນທີ່ໂມເດວຂອງແບບແຕ້ມຂອງບລັອກເອງ. + .visibilitystates-panel-unsupported = ບໍ່ສາມາດແກ້ໄຂສະຖານະການເບິ່ງເຫັນຂອງແບບແຕ້ມນີ້ຢູ່ນີ້ໄດ້. + .visibilitystates-first-state = ສະຖານະທຳອິດ + .visibilitystates-panel-empty = ບໍ່ມີສະຖານະການເບິ່ງເຫັນໃນແບບແຕ້ມນີ້. ຄລິກ + ເພື່ອເພີ່ມພາຣາມິເຕີ. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ ວັດຖຸ) + .visibilitystates-move-up = ຍ້າຍຂຶ້ນ + .visibilitystates-move-down = ຍ້າຍລົງ + .visibilitystates-state-objects = ວັດຖຸຂອງສະຖານະນີ້ + .visibilitystates-new-state = ສະຖານະໃໝ່ + .visibilitystates-add-state = ເພີ່ມສະຖານະ + .visibilitystates-back = ກັບຄືນຫາພາຣາມິເຕີ + .visibilitystates-add-to-state = ເພີ່ມວັດຖຸໃສ່ສະຖານະນີ້ + .visibilitystates-no-objects-yet = ພາຣາມິເຕີຍັງບໍ່ໄດ້ຄວບຄຸມວັດຖຸໃດເທື່ອ. ເພີ່ມວັດຖຸໃສ່ສະຖານະນີ້. + .visibilitystates-remove-from-parameter = ເອົາອອກຈາກພາຣາມິເຕີ + .visibilitystates-same-everywhere = ສະແດງຄືກັນໃນທຸກສະຖານະຂອງພາຣາມິເຕີ + .visibilitystates-same-everywhere-note = ວັດຖຸໜຶ່ງ ຫຼື ຫຼາຍອັນສະແດງຄືກັນໃນທຸກສະຖານະຂອງພາຣາມິເຕີນີ້. .bvstate-current = ສະຖານະການເບິ່ງເຫັນປັດຈຸບັນ: __ocs_fmt_0__ .bvhide-select = ເລືອກວັດຖຸທີ່ຈະເຊື່ອງ: .bvshow-select = ເລືອກວັດຖຸທີ່ຈະສະແດງ: diff --git a/locales/nl-NL/opencadstudio.ftl b/locales/nl-NL/opencadstudio.ftl index c397e3fb38..26e4e165f3 100644 --- a/locales/nl-NL/opencadstudio.ftl +++ b/locales/nl-NL/opencadstudio.ftl @@ -3590,6 +3590,42 @@ modify = .bvstate-exists = Zichtbaarheidsstatus "__ocs_fmt_0__" bestaat al. .bvstate-last = De enige zichtbaarheidsstatus kan niet worden verwijderd. .bvstate-needs-bedit = __ocs_fmt_0__: open het blok eerst in de blokeditor (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Geef een nieuwe parameter: + .visibilitystates-parameter-or = VISIBILITYSTATES Geef een nieuwe parameter of [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Geef een nieuwe status voor __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Geef een nieuwe status voor __ocs_fmt_0__ of [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Kies een actie [Toevoegen/Verwijderen/Zichtbaar maken/Onzichtbaar maken/Status kiezen] : + .visibilitystates-add-objects = Objecten toevoegen + .visibilitystates-remove-objects = Objecten verwijderen + .visibilitystates-make-visible = Objecten zichtbaar maken + .visibilitystates-make-invisible = Objecten onzichtbaar maken + .visibilitystates-select-state = Status kiezen + .visibilitystates-model-space = VISIBILITYSTATES werkt in de modelruimte: open de tekening van het BricsCAD-blok. + .visibilitystates-unsupported = De zichtbaarheidsstatussen hier kunnen niet worden bewerkt. + .visibilitystates-old-format = Zichtbaarheidsstatussen vereisen een tekening in DWG 2010-indeling of nieuwer. + .visibilitystates-no-parameter = Geen zichtbaarheidsparameter met die naam. + .visibilitystates-no-state = Geen zichtbaarheidsstatus met die naam. + .visibilitystates-state-exists = Die zichtbaarheidsstatus bestaat al. + .visibilitystates-cannot-move = De zichtbaarheidsstatus kan niet verder worden verplaatst. + .visibilitystates-bad-name = Geef een naam van letters, cijfers en onderstrepingstekens. + .visibilitystates-name-taken = Die naam wordt door een andere variabele gebruikt. + .visibilitystates-no-objects = Selecteer objecten van de ruimte die wordt bewerkt. + .visibilitystates-panel-elsewhere = Zichtbaarheidsstatussen worden bewerkt in de modelruimte van de eigen tekening van het blok. + .visibilitystates-panel-unsupported = De zichtbaarheidsstatussen van deze tekening kunnen hier niet worden bewerkt. + .visibilitystates-first-state = Eerste status + .visibilitystates-panel-empty = Deze tekening bevat geen zichtbaarheidsstatussen. Klik op + om een parameter toe te voegen. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objecten) + .visibilitystates-move-up = Omhoog + .visibilitystates-move-down = Omlaag + .visibilitystates-state-objects = Objecten van deze status + .visibilitystates-new-state = Nieuwe status + .visibilitystates-add-state = Status toevoegen + .visibilitystates-back = Terug naar de parameters + .visibilitystates-add-to-state = Objecten aan deze status toevoegen + .visibilitystates-no-objects-yet = De parameter stuurt nog geen objecten aan. Voeg objecten aan deze status toe. + .visibilitystates-remove-from-parameter = Uit parameter verwijderen + .visibilitystates-same-everywhere = In elke status van de parameter hetzelfde + .visibilitystates-same-everywhere-note = Een of meer objecten worden in elke status van deze parameter hetzelfde weergegeven. .bvstate-current = Huidige zichtbaarheidsstatus: __ocs_fmt_0__ .bvhide-select = Selecteer te verbergen objecten: .bvshow-select = Selecteer zichtbaar te maken objecten: diff --git a/locales/pl-PL/opencadstudio.ftl b/locales/pl-PL/opencadstudio.ftl index 90dd85a317..7292d90b55 100644 --- a/locales/pl-PL/opencadstudio.ftl +++ b/locales/pl-PL/opencadstudio.ftl @@ -3589,6 +3589,42 @@ modify = .bvstate-exists = Stan widoczności "__ocs_fmt_0__" już istnieje. .bvstate-last = Nie można usunąć jedynego stanu widoczności. .bvstate-needs-bedit = __ocs_fmt_0__: najpierw otwórz blok w edytorze bloków (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Podaj nowy parametr: + .visibilitystates-parameter-or = VISIBILITYSTATES Podaj nowy parametr lub [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Podaj nowy stan dla __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Podaj nowy stan dla __ocs_fmt_0__ lub [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Wybierz akcję [Dodaj/Usuń/Pokaż/Ukryj/Wybierz stan] : + .visibilitystates-add-objects = Dodaj obiekty + .visibilitystates-remove-objects = Usuń obiekty + .visibilitystates-make-visible = Pokaż obiekty + .visibilitystates-make-invisible = Ukryj obiekty + .visibilitystates-select-state = Wybierz stan + .visibilitystates-model-space = VISIBILITYSTATES działa w obszarze modelu: otwórz rysunek bloku BricsCAD. + .visibilitystates-unsupported = Stanów widoczności nie można tu edytować. + .visibilitystates-old-format = Stany widoczności wymagają rysunku w formacie DWG 2010 lub nowszym. + .visibilitystates-no-parameter = Brak parametru widoczności o tej nazwie. + .visibilitystates-no-state = Brak stanu widoczności o tej nazwie. + .visibilitystates-state-exists = Ten stan widoczności już istnieje. + .visibilitystates-cannot-move = Stanu widoczności nie można przesunąć dalej. + .visibilitystates-bad-name = Podaj nazwę złożoną z liter, cyfr i podkreśleń. + .visibilitystates-name-taken = Ta nazwa jest używana przez inną zmienną. + .visibilitystates-no-objects = Wybierz obiekty z edytowanego obszaru. + .visibilitystates-panel-elsewhere = Stany widoczności edytuje się w obszarze modelu własnego rysunku bloku. + .visibilitystates-panel-unsupported = Stanów widoczności tego rysunku nie można tu edytować. + .visibilitystates-first-state = Pierwszy stan + .visibilitystates-panel-empty = Ten rysunek nie zawiera stanów widoczności. Kliknij +, aby dodać parametr. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (obiekty: __ocs_fmt_1__) + .visibilitystates-move-up = Przenieś w górę + .visibilitystates-move-down = Przenieś w dół + .visibilitystates-state-objects = Obiekty tego stanu + .visibilitystates-new-state = Nowy stan + .visibilitystates-add-state = Dodaj stan + .visibilitystates-back = Powrót do parametrów + .visibilitystates-add-to-state = Dodaj obiekty do tego stanu + .visibilitystates-no-objects-yet = Parametr nie steruje jeszcze żadnymi obiektami. Dodaj obiekty do tego stanu. + .visibilitystates-remove-from-parameter = Usuń z parametru + .visibilitystates-same-everywhere = Tak samo we wszystkich stanach parametru + .visibilitystates-same-everywhere-note = Co najmniej jeden obiekt wygląda tak samo we wszystkich stanach tego parametru. .bvstate-current = Bieżący stan widoczności: __ocs_fmt_0__ .bvhide-select = Wybierz obiekty do ukrycia: .bvshow-select = Wybierz obiekty do pokazania: diff --git a/locales/pt-BR/opencadstudio.ftl b/locales/pt-BR/opencadstudio.ftl index f2392c79a1..1c5da5dfbe 100644 --- a/locales/pt-BR/opencadstudio.ftl +++ b/locales/pt-BR/opencadstudio.ftl @@ -3590,6 +3590,42 @@ modify = .bvstate-exists = O estado de visibilidade "__ocs_fmt_0__" já existe. .bvstate-last = O único estado de visibilidade não pode ser excluído. .bvstate-needs-bedit = __ocs_fmt_0__: abra primeiro o bloco no Editor de blocos (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Digite um novo parâmetro: + .visibilitystates-parameter-or = VISIBILITYSTATES Digite um novo parâmetro ou [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Digite um novo estado para __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Digite um novo estado para __ocs_fmt_0__ ou [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Selecione uma ação [Adicionar/Remover/Mostrar/Ocultar/Selecionar estado] : + .visibilitystates-add-objects = Adicionar objetos + .visibilitystates-remove-objects = Remover objetos + .visibilitystates-make-visible = Tornar objetos visíveis + .visibilitystates-make-invisible = Tornar objetos invisíveis + .visibilitystates-select-state = Selecionar estado + .visibilitystates-model-space = VISIBILITYSTATES funciona no espaço do modelo: abra o desenho do bloco BricsCAD. + .visibilitystates-unsupported = Os estados de visibilidade aqui não podem ser editados. + .visibilitystates-old-format = Os estados de visibilidade exigem um desenho no formato DWG 2010 ou posterior. + .visibilitystates-no-parameter = Nenhum parâmetro de visibilidade com esse nome. + .visibilitystates-no-state = Nenhum estado de visibilidade com esse nome. + .visibilitystates-state-exists = Esse estado de visibilidade já existe. + .visibilitystates-cannot-move = O estado de visibilidade não pode ser movido além disso. + .visibilitystates-bad-name = Digite um nome com letras, dígitos e sublinhados. + .visibilitystates-name-taken = Esse nome é usado por outra variável. + .visibilitystates-no-objects = Selecione objetos do espaço em edição. + .visibilitystates-panel-elsewhere = Os estados de visibilidade são editados no espaço do modelo do próprio desenho do bloco. + .visibilitystates-panel-unsupported = Os estados de visibilidade deste desenho não podem ser editados aqui. + .visibilitystates-first-state = Primeiro estado + .visibilitystates-panel-empty = Não há estados de visibilidade neste desenho. Clique em + para adicionar um parâmetro. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ objetos) + .visibilitystates-move-up = Mover para cima + .visibilitystates-move-down = Mover para baixo + .visibilitystates-state-objects = Objetos deste estado + .visibilitystates-new-state = Novo estado + .visibilitystates-add-state = Adicionar estado + .visibilitystates-back = Voltar aos parâmetros + .visibilitystates-add-to-state = Adicionar objetos a este estado + .visibilitystates-no-objects-yet = O parâmetro ainda não controla nenhum objeto. Adicione objetos a este estado. + .visibilitystates-remove-from-parameter = Remover do parâmetro + .visibilitystates-same-everywhere = Igual em todos os estados do parâmetro + .visibilitystates-same-everywhere-note = Um ou mais objetos aparecem iguais em todos os estados deste parâmetro. .bvstate-current = Estado de visibilidade atual: __ocs_fmt_0__ .bvhide-select = Selecione os objetos a ocultar: .bvshow-select = Selecione os objetos a tornar visíveis: diff --git a/locales/ru-RU/opencadstudio.ftl b/locales/ru-RU/opencadstudio.ftl index fd54c89bae..e2578efdb8 100644 --- a/locales/ru-RU/opencadstudio.ftl +++ b/locales/ru-RU/opencadstudio.ftl @@ -3593,6 +3593,42 @@ modify = .bvstate-exists = Состояние видимости "__ocs_fmt_0__" уже существует. .bvstate-last = Единственное состояние видимости нельзя удалить. .bvstate-needs-bedit = __ocs_fmt_0__: сначала откройте блок в редакторе блоков (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Введите новый параметр: + .visibilitystates-parameter-or = VISIBILITYSTATES Введите новый параметр или [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Введите новое состояние для __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Введите новое состояние для __ocs_fmt_0__ или [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Выберите действие [Добавить/Убрать/Показать/Скрыть/Выбрать состояние] <Добавить>: + .visibilitystates-add-objects = Добавить объекты + .visibilitystates-remove-objects = Убрать объекты + .visibilitystates-make-visible = Сделать объекты видимыми + .visibilitystates-make-invisible = Сделать объекты невидимыми + .visibilitystates-select-state = Выбрать состояние + .visibilitystates-model-space = VISIBILITYSTATES работает в пространстве модели: откройте чертёж блока BricsCAD. + .visibilitystates-unsupported = Здесь нельзя редактировать состояния видимости. + .visibilitystates-old-format = Для состояний видимости нужен чертёж в формате DWG 2010 или новее. + .visibilitystates-no-parameter = Нет параметра видимости с таким именем. + .visibilitystates-no-state = Нет состояния видимости с таким именем. + .visibilitystates-state-exists = Такое состояние видимости уже существует. + .visibilitystates-cannot-move = Состояние видимости нельзя переместить дальше. + .visibilitystates-bad-name = Введите имя из букв, цифр и символов подчёркивания. + .visibilitystates-name-taken = Это имя используется другой переменной. + .visibilitystates-no-objects = Выберите объекты редактируемого пространства. + .visibilitystates-panel-elsewhere = Состояния видимости редактируются в пространстве модели собственного чертежа блока. + .visibilitystates-panel-unsupported = Состояния видимости этого чертежа нельзя редактировать здесь. + .visibilitystates-first-state = Первое состояние + .visibilitystates-panel-empty = В этом чертеже нет состояний видимости. Нажмите +, чтобы добавить параметр. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (объектов: __ocs_fmt_1__) + .visibilitystates-move-up = Переместить вверх + .visibilitystates-move-down = Переместить вниз + .visibilitystates-state-objects = Объекты этого состояния + .visibilitystates-new-state = Новое состояние + .visibilitystates-add-state = Добавить состояние + .visibilitystates-back = Назад к параметрам + .visibilitystates-add-to-state = Добавить объекты в это состояние + .visibilitystates-no-objects-yet = Параметр пока не управляет ни одним объектом. Добавьте объекты в это состояние. + .visibilitystates-remove-from-parameter = Убрать из параметра + .visibilitystates-same-everywhere = Одинаково во всех состояниях параметра + .visibilitystates-same-everywhere-note = Один или несколько объектов выглядят одинаково во всех состояниях этого параметра. .bvstate-current = Текущее состояние видимости: __ocs_fmt_0__ .bvhide-select = Выберите объекты, которые нужно скрыть: .bvshow-select = Выберите объекты, которые нужно показать: diff --git a/locales/tr-TR/opencadstudio.ftl b/locales/tr-TR/opencadstudio.ftl index 05e045862b..e41393994c 100644 --- a/locales/tr-TR/opencadstudio.ftl +++ b/locales/tr-TR/opencadstudio.ftl @@ -3572,6 +3572,42 @@ modify = .bvstate-exists = "__ocs_fmt_0__" görünürlük durumu zaten var. .bvstate-last = Tek görünürlük durumu silinemez. .bvstate-needs-bedit = __ocs_fmt_0__: önce bloğu Blok Düzenleyici'de açın (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Yeni bir parametre girin: + .visibilitystates-parameter-or = VISIBILITYSTATES Yeni bir parametre girin veya [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES __ocs_fmt_0__ için yeni bir durum girin: + .visibilitystates-state-or = VISIBILITYSTATES __ocs_fmt_0__ için yeni bir durum girin veya [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Bir eylem seçin [Ekle/Çıkar/Göster/Gizle/Durum seç] : + .visibilitystates-add-objects = Nesne ekle + .visibilitystates-remove-objects = Nesne çıkar + .visibilitystates-make-visible = Nesneleri göster + .visibilitystates-make-invisible = Nesneleri gizle + .visibilitystates-select-state = Durum seç + .visibilitystates-model-space = VISIBILITYSTATES model alanında çalışır: BricsCAD bloğunun çizimini açın. + .visibilitystates-unsupported = Buradaki görünürlük durumları düzenlenemez. + .visibilitystates-old-format = Görünürlük durumları DWG 2010 veya daha yeni biçimde bir çizim gerektirir. + .visibilitystates-no-parameter = Bu adda bir görünürlük parametresi yok. + .visibilitystates-no-state = Bu adda bir görünürlük durumu yok. + .visibilitystates-state-exists = Bu görünürlük durumu zaten var. + .visibilitystates-cannot-move = Görünürlük durumu daha fazla taşınamaz. + .visibilitystates-bad-name = Harf, rakam ve alt çizgiden oluşan bir ad girin. + .visibilitystates-name-taken = Bu ad başka bir değişken tarafından kullanılıyor. + .visibilitystates-no-objects = Düzenlenen alanın nesnelerini seçin. + .visibilitystates-panel-elsewhere = Görünürlük durumları, bloğun kendi çiziminin model alanında düzenlenir. + .visibilitystates-panel-unsupported = Bu çizimin görünürlük durumları burada düzenlenemez. + .visibilitystates-first-state = İlk durum + .visibilitystates-panel-empty = Bu çizimde görünürlük durumu yok. Parametre eklemek için + düğmesine tıklayın. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ nesne) + .visibilitystates-move-up = Yukarı taşı + .visibilitystates-move-down = Aşağı taşı + .visibilitystates-state-objects = Bu durumun nesneleri + .visibilitystates-new-state = Yeni durum + .visibilitystates-add-state = Durum ekle + .visibilitystates-back = Parametrelere dön + .visibilitystates-add-to-state = Bu duruma nesne ekle + .visibilitystates-no-objects-yet = Parametre henüz hiçbir nesneyi denetlemiyor. Bu duruma nesne ekleyin. + .visibilitystates-remove-from-parameter = Parametreden çıkar + .visibilitystates-same-everywhere = Parametrenin her durumunda aynı + .visibilitystates-same-everywhere-note = Bir veya daha fazla nesne bu parametrenin her durumunda aynı görünür. .bvstate-current = Geçerli görünürlük durumu: __ocs_fmt_0__ .bvhide-select = Gizlenecek nesneleri seçin: .bvshow-select = Görünür yapılacak nesneleri seçin: diff --git a/locales/vi-VN/opencadstudio.ftl b/locales/vi-VN/opencadstudio.ftl index 60565d7aa9..4abbc97638 100644 --- a/locales/vi-VN/opencadstudio.ftl +++ b/locales/vi-VN/opencadstudio.ftl @@ -3597,6 +3597,42 @@ modify = .bvstate-exists = Trạng thái hiển thị "__ocs_fmt_0__" đã tồn tại. .bvstate-last = Trạng thái hiển thị duy nhất không thể bị xóa. .bvstate-needs-bedit = __ocs_fmt_0__: mở khối trong Block Editor trước (BEDIT). + .visibilitystates-parameter = VISIBILITYSTATES Nhập tham số mới: + .visibilitystates-parameter-or = VISIBILITYSTATES Nhập tham số mới hoặc [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES Nhập trạng thái mới cho __ocs_fmt_0__: + .visibilitystates-state-or = VISIBILITYSTATES Nhập trạng thái mới cho __ocs_fmt_0__ hoặc [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES Chọn thao tác [Thêm/Bỏ/Hiện/Ẩn/Chọn trạng thái] : + .visibilitystates-add-objects = Thêm đối tượng + .visibilitystates-remove-objects = Bỏ đối tượng + .visibilitystates-make-visible = Hiện đối tượng + .visibilitystates-make-invisible = Ẩn đối tượng + .visibilitystates-select-state = Chọn trạng thái + .visibilitystates-model-space = VISIBILITYSTATES hoạt động trong không gian mô hình: hãy mở bản vẽ của khối BricsCAD. + .visibilitystates-unsupported = Không thể chỉnh sửa các trạng thái hiển thị ở đây. + .visibilitystates-old-format = Trạng thái hiển thị cần bản vẽ định dạng DWG 2010 trở lên. + .visibilitystates-no-parameter = Không có tham số hiển thị nào có tên này. + .visibilitystates-no-state = Không có trạng thái hiển thị nào có tên này. + .visibilitystates-state-exists = Trạng thái hiển thị này đã tồn tại. + .visibilitystates-cannot-move = Không thể di chuyển trạng thái hiển thị thêm nữa. + .visibilitystates-bad-name = Nhập tên gồm chữ cái, chữ số và dấu gạch dưới. + .visibilitystates-name-taken = Tên này đang được một biến khác sử dụng. + .visibilitystates-no-objects = Chọn đối tượng thuộc không gian đang chỉnh sửa. + .visibilitystates-panel-elsewhere = Trạng thái hiển thị được chỉnh sửa trong không gian mô hình của chính bản vẽ khối. + .visibilitystates-panel-unsupported = Không thể chỉnh sửa các trạng thái hiển thị của bản vẽ này ở đây. + .visibilitystates-first-state = Trạng thái đầu tiên + .visibilitystates-panel-empty = Bản vẽ này không có trạng thái hiển thị nào. Nhấp + để thêm tham số. + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ đối tượng) + .visibilitystates-move-up = Di chuyển lên + .visibilitystates-move-down = Di chuyển xuống + .visibilitystates-state-objects = Đối tượng của trạng thái này + .visibilitystates-new-state = Trạng thái mới + .visibilitystates-add-state = Thêm trạng thái + .visibilitystates-back = Quay lại các tham số + .visibilitystates-add-to-state = Thêm đối tượng vào trạng thái này + .visibilitystates-no-objects-yet = Tham số chưa điều khiển đối tượng nào. Hãy thêm đối tượng vào trạng thái này. + .visibilitystates-remove-from-parameter = Bỏ khỏi tham số + .visibilitystates-same-everywhere = Giống nhau ở mọi trạng thái của tham số + .visibilitystates-same-everywhere-note = Một hoặc nhiều đối tượng hiển thị giống nhau ở mọi trạng thái của tham số này. .bvstate-current = Trạng thái hiển thị hiện tại: __ocs_fmt_0__ .bvhide-select = Chọn đối tượng cần ẩn: .bvshow-select = Chọn các đối tượng để hiển thị: diff --git a/locales/zh-CN/opencadstudio.ftl b/locales/zh-CN/opencadstudio.ftl index bf7bd07bb2..372a2673b3 100644 --- a/locales/zh-CN/opencadstudio.ftl +++ b/locales/zh-CN/opencadstudio.ftl @@ -3577,6 +3577,42 @@ modify = .bvstate-exists = 可见性状态“__ocs_fmt_0__”已存在。 .bvstate-last = 不能删除唯一的可见性状态。 .bvstate-needs-bedit = __ocs_fmt_0__: 请先在块编辑器中打开该块 (BEDIT)。 + .visibilitystates-parameter = VISIBILITYSTATES 输入新参数: + .visibilitystates-parameter-or = VISIBILITYSTATES 输入新参数或 [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES 输入 __ocs_fmt_0__ 的新状态: + .visibilitystates-state-or = VISIBILITYSTATES 输入 __ocs_fmt_0__ 的新状态或 [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES 选择操作 [添加/移除/显示/隐藏/选择状态] <添加>: + .visibilitystates-add-objects = 添加对象 + .visibilitystates-remove-objects = 移除对象 + .visibilitystates-make-visible = 显示对象 + .visibilitystates-make-invisible = 隐藏对象 + .visibilitystates-select-state = 选择状态 + .visibilitystates-model-space = VISIBILITYSTATES 在模型空间中工作: 请打开 BricsCAD 块的图形。 + .visibilitystates-unsupported = 此处的可见性状态无法编辑。 + .visibilitystates-old-format = 可见性状态需要 DWG 2010 或更高版本格式的图形。 + .visibilitystates-no-parameter = 没有该名称的可见性参数。 + .visibilitystates-no-state = 没有该名称的可见性状态。 + .visibilitystates-state-exists = 该可见性状态已存在。 + .visibilitystates-cannot-move = 该可见性状态无法再移动。 + .visibilitystates-bad-name = 请输入由字母、数字和下划线组成的名称。 + .visibilitystates-name-taken = 该名称已被另一个变量使用。 + .visibilitystates-no-objects = 请选择正在编辑的空间中的对象。 + .visibilitystates-panel-elsewhere = 可见性状态在块自身图形的模型空间中编辑。 + .visibilitystates-panel-unsupported = 此图形的可见性状态无法在此处编辑。 + .visibilitystates-first-state = 第一个状态 + .visibilitystates-panel-empty = 此图形中没有可见性状态。单击 + 添加参数。 + .visibilitystates-parameter-objects = __ocs_fmt_0__ (__ocs_fmt_1__ 个对象) + .visibilitystates-move-up = 上移 + .visibilitystates-move-down = 下移 + .visibilitystates-state-objects = 此状态的对象 + .visibilitystates-new-state = 新建状态 + .visibilitystates-add-state = 添加状态 + .visibilitystates-back = 返回参数列表 + .visibilitystates-add-to-state = 将对象添加到此状态 + .visibilitystates-no-objects-yet = 该参数尚未控制任何对象。请将对象添加到此状态。 + .visibilitystates-remove-from-parameter = 从参数中移除 + .visibilitystates-same-everywhere = 在参数的所有状态中显示相同 + .visibilitystates-same-everywhere-note = 一个或多个对象在此参数的所有状态中显示相同。 .bvstate-current = 当前可见性状态: __ocs_fmt_0__ .bvhide-select = 选择要隐藏的对象: .bvshow-select = 选择要显示的对象: diff --git a/locales/zh-TW/opencadstudio.ftl b/locales/zh-TW/opencadstudio.ftl index 355e21a6fc..cf714233e1 100644 --- a/locales/zh-TW/opencadstudio.ftl +++ b/locales/zh-TW/opencadstudio.ftl @@ -3589,6 +3589,42 @@ modify = .bvstate-exists = 可見性狀態「__ocs_fmt_0__」已存在。 .bvstate-last = 無法刪除唯一的可見性狀態。 .bvstate-needs-bedit = __ocs_fmt_0__:請先在圖塊編輯器中開啟圖塊(BEDIT)。 + .visibilitystates-parameter = VISIBILITYSTATES 輸入新參數: + .visibilitystates-parameter-or = VISIBILITYSTATES 輸入新參數或 [__ocs_fmt_0__]: + .visibilitystates-state = VISIBILITYSTATES 輸入 __ocs_fmt_0__ 的新狀態: + .visibilitystates-state-or = VISIBILITYSTATES 輸入 __ocs_fmt_0__ 的新狀態或 [__ocs_fmt_1__]: + .visibilitystates-action = VISIBILITYSTATES 選取動作 [加入/移除/顯示/隱藏/選取狀態] <加入>: + .visibilitystates-add-objects = 加入物件 + .visibilitystates-remove-objects = 移除物件 + .visibilitystates-make-visible = 顯示物件 + .visibilitystates-make-invisible = 隱藏物件 + .visibilitystates-select-state = 選取狀態 + .visibilitystates-model-space = VISIBILITYSTATES 在模型空間中運作:請開啟 BricsCAD 圖塊的圖面。 + .visibilitystates-unsupported = 此處的可見性狀態無法編輯。 + .visibilitystates-old-format = 可見性狀態需要 DWG 2010 或更新格式的圖面。 + .visibilitystates-no-parameter = 沒有此名稱的可見性參數。 + .visibilitystates-no-state = 沒有此名稱的可見性狀態。 + .visibilitystates-state-exists = 此可見性狀態已存在。 + .visibilitystates-cannot-move = 此可見性狀態無法再移動。 + .visibilitystates-bad-name = 請輸入由字母、數字和底線組成的名稱。 + .visibilitystates-name-taken = 此名稱已由另一個變數使用。 + .visibilitystates-no-objects = 請選取正在編輯之空間中的物件。 + .visibilitystates-panel-elsewhere = 可見性狀態需在圖塊本身圖面的模型空間中編輯。 + .visibilitystates-panel-unsupported = 此圖面的可見性狀態無法在此處編輯。 + .visibilitystates-first-state = 第一個狀態 + .visibilitystates-panel-empty = 此圖面中沒有可見性狀態。按一下 + 以新增參數。 + .visibilitystates-parameter-objects = __ocs_fmt_0__(__ocs_fmt_1__ 個物件) + .visibilitystates-move-up = 上移 + .visibilitystates-move-down = 下移 + .visibilitystates-state-objects = 此狀態的物件 + .visibilitystates-new-state = 新狀態 + .visibilitystates-add-state = 新增狀態 + .visibilitystates-back = 返回參數 + .visibilitystates-add-to-state = 將物件加入此狀態 + .visibilitystates-no-objects-yet = 此參數尚未控制任何物件。請將物件加入此狀態。 + .visibilitystates-remove-from-parameter = 從參數中移除 + .visibilitystates-same-everywhere = 在參數的所有狀態中顯示相同 + .visibilitystates-same-everywhere-note = 一個或多個物件在此參數的所有狀態中顯示相同。 .bvstate-current = 目前可見性狀態:__ocs_fmt_0__ .bvhide-select = 選取要隱藏的物件: .bvshow-select = 選取要顯示的物件: diff --git a/src/app/commands/bricscad_visibility.rs b/src/app/commands/bricscad_visibility.rs index ed31f7001a..4d55d9060e 100644 --- a/src/app/commands/bricscad_visibility.rs +++ b/src/app/commands/bricscad_visibility.rs @@ -1,13 +1,15 @@ -//! VISIBILITYSTATES: the visibility states of a BricsCAD parametric block, in -//! model space of the block's own drawing (see -//! `scene::bricscad_parameters::author`). +//! VISIBILITYSTATES and its palette (VISIBILITYSTATESPANELOPEN): the +//! visibility states of a BricsCAD parametric block, in model space of the +//! block's own drawing (see `scene::bricscad_parameters::author`). use crate::app::{Message, OpenCADStudio}; use crate::command::CadCommand; use crate::modules::draw::modify::visibilitystates::{VisibilityStatesCommand, SEP}; use crate::scene::bricscad_parameters::{self as bricscad, Action}; +use crate::ui::window::bricscad_visibility::{Model, VisMsg}; use document::Handle; use iced::Task; +use std::rc::Rc; /// Marks the step that runs after the objects are picked. const PICKED: &str = "PICKED"; @@ -17,10 +19,8 @@ impl OpenCADStudio { /// is left alone: the anonymous copies its references show would keep the /// states it had. fn visibility_states_owner(&mut self, i: usize) -> Option { - if self.tabs[i].active_block_edit_session().is_none() - && self.tabs[i].scene.current_layout == "Model" - { - return Some(self.tabs[i].scene.document.header.model_space_block_handle); + if let Some(owner) = Self::model_space_owner(&self.tabs[i]) { + return Some(owner); } self.command_line.push_error( crate::t!( @@ -31,11 +31,27 @@ impl OpenCADStudio { None } + fn model_space_owner(tab: &crate::app::DocumentTab) -> Option { + (tab.active_block_edit_session().is_none() && tab.scene.current_layout == "Model") + .then_some(tab.scene.document.header.model_space_block_handle) + } + pub(super) fn dispatch_bricscad_visibility( &mut self, cmd: &str, i: usize, ) -> Option> { + match cmd { + "VISIBILITYSTATESPANELOPEN" => { + self.set_bricscad_visibility_panel(true); + return Some(Task::none()); + } + "VISIBILITYSTATESPANELCLOSE" => { + self.set_bricscad_visibility_panel(false); + return Some(Task::none()); + } + _ => {} + } if cmd == "VISIBILITYSTATES" { let Some(owner) = self.visibility_states_owner(i) else { return Some(Task::none()); @@ -63,23 +79,43 @@ impl OpenCADStudio { _ => return Some(Task::none()), }; if action != Action::Select && !picked && self.tabs[i].scene.selected.is_empty() { - use crate::modules::draw::select::SelectObjectsCommand; - let pending = format!("{cmd}{SEP}{PICKED}"); - let command = - SelectObjectsCommand::with_prompt("VISIBILITYSTATES", &pending, "Select objects:"); - self.command_line.push_info(&command.prompt()); - self.tabs[i].active_cmd = Some(Box::new(command)); + self.pick_for_bricscad_visibility(i, cmd); return Some(Task::none()); } self.tabs[i].active_cmd = None; - let Some(owner) = self.visibility_states_owner(i) else { - return Some(Task::none()); - }; let objects = if action == Action::Select { Vec::new() } else { self.tabs[i].scene.selected_handles_in_order() }; + self.apply_bricscad_visibility(i, parameter, state, action, &objects); + Some(Task::none()) + } + + /// Ask for the objects of `cmd` (`_VISIBILITYSTATES` with its fields). + fn pick_for_bricscad_visibility(&mut self, i: usize, cmd: &str) { + use crate::modules::draw::select::SelectObjectsCommand; + self.tabs[i].scene.deselect_all(); + let pending = format!("{cmd}{SEP}{PICKED}"); + let command = + SelectObjectsCommand::with_prompt("VISIBILITYSTATES", &pending, "Select objects:"); + self.command_line.push_info(&command.prompt()); + self.tabs[i].active_cmd = Some(Box::new(command)); + } + + /// One VISIBILITYSTATES step on model space of tab `i`, one undo step; + /// whether it was done. + fn apply_bricscad_visibility( + &mut self, + i: usize, + parameter: &str, + state: &str, + action: Action, + objects: &[Handle], + ) -> bool { + let Some(owner) = self.visibility_states_owner(i) else { + return false; + }; // The edit runs on a copy, so a refusal leaves the drawing as it was; // what the editor holds goes into the drawing first. self.tabs[i].scene.sync_native_parametric_graph(); @@ -87,7 +123,7 @@ impl OpenCADStudio { scene.document = self.tabs[i].scene.document.clone(); scene.load_named_parameters_from_document(); scene.load_parametric_constraints_from_document(); - match scene.edit_bricscad_visibility(owner, parameter, state, action, &objects) { + match scene.edit_bricscad_visibility(owner, parameter, state, action, objects) { Ok(()) => { self.push_undo_snapshot(i, "VISIBILITYSTATES"); self.apply_action_document_and_bump(i, scene.document); @@ -111,9 +147,172 @@ impl OpenCADStudio { .push_output(crate::tf!("Current visibility state: {}", shown).as_ref()); } self.refresh_properties(); + true + } + Err(error) => { + self.command_line.push_error(crate::t!(error).as_ref()); + false } - Err(error) => self.command_line.push_error(crate::t!(error).as_ref()), } - Some(Task::none()) + } + + pub(in crate::app) fn set_bricscad_visibility_panel(&mut self, open: bool) { + let id = crate::ui::dock::PanelId::BricscadVisibility; + self.bricscad_visibility.show = open; + if open { + self.dock_open_at_default(id); + } else { + self.dock_unpeek(id); + } + } + + /// What the palette shows of `tab`: model space's parameters, read once + /// per change of the drawing; `None` outside model space. + pub(in crate::app) fn bricscad_visibility_model( + &self, + tab: &crate::app::DocumentTab, + ) -> Option> { + Self::model_space_owner(tab)?; + let key = ( + tab.id, + tab.edit_revision, + crate::i18n::language_generation(), + ); + let mut cache = self.bricscad_visibility.cache.borrow_mut(); + match cache.as_ref() { + Some((at, model)) if *at == key => Some(model.clone()), + _ => { + let model = Rc::new(crate::ui::window::bricscad_visibility::read( + &tab.scene.document, + )); + *cache = Some((key, model.clone())); + Some(model) + } + } + } + + pub(in crate::app) fn on_bricscad_visibility(&mut self, message: VisMsg) -> Task { + let i = self.active_tab; + let panel = &mut self.bricscad_visibility; + match message { + VisMsg::Select(parameter, state) => { + self.apply_bricscad_visibility(i, ¶meter, &state, Action::Select, &[]); + } + VisMsg::Open(parameter, state) => { + panel.page = Some((parameter, state)); + panel.new_state = None; + panel.new_parameter = None; + } + VisMsg::Move(parameter, state, up) => { + let action = if up { Action::MoveUp } else { Action::MoveDown }; + self.apply_bricscad_visibility(i, ¶meter, &state, action, &[]); + } + VisMsg::Back => panel.page = None, + VisMsg::Fold(parameter) => { + let key = parameter.to_uppercase(); + if let Some(k) = panel.folded.iter().position(|p| *p == key) { + panel.folded.remove(k); + } else { + panel.folded.push(key); + } + } + VisMsg::NewParameter => { + panel.new_parameter = Some(Default::default()); + panel.new_state = None; + } + VisMsg::NewParameterName(name) => { + if let Some((n, _)) = panel.new_parameter.as_mut() { + *n = name; + } + } + VisMsg::NewParameterState(state) => { + if let Some((_, s)) = panel.new_parameter.as_mut() { + *s = state; + } + } + VisMsg::NewParameterPick => { + let Some((name, state)) = panel.new_parameter.take() else { + return Task::none(); + }; + let (name, state) = (name.trim().to_string(), state.trim().to_string()); + if name.is_empty() || state.is_empty() { + panel.new_parameter = Some((name, state)); + return Task::none(); + } + panel.page = Some((name.clone(), state.clone())); + if self.visibility_states_owner(i).is_some() { + self.pick_for_bricscad_visibility( + i, + &format!("_VISIBILITYSTATES{SEP}{name}{SEP}{state}{SEP}ADD"), + ); + } + } + VisMsg::NewState(parameter) => { + panel.new_state = Some((parameter, String::new())); + panel.new_parameter = None; + } + VisMsg::NewStateName(name) => { + if let Some((_, n)) = panel.new_state.as_mut() { + *n = name; + } + } + VisMsg::NewStateCommit => { + let Some((parameter, name)) = panel.new_state.take() else { + return Task::none(); + }; + let name = name.trim().to_string(); + if name.is_empty() { + return Task::none(); + } + if self.apply_bricscad_visibility(i, ¶meter, &name, Action::NewState, &[]) { + self.bricscad_visibility.page = Some((parameter, name)); + } else { + self.bricscad_visibility.new_state = Some((parameter, name)); + } + } + VisMsg::Cancel => { + panel.new_parameter = None; + panel.new_state = None; + } + VisMsg::Show(entity, shown) => { + if let Some((parameter, state)) = panel.page.clone() { + let action = if shown { + Action::Visible + } else { + Action::Invisible + }; + self.apply_bricscad_visibility(i, ¶meter, &state, action, &[entity]); + } + } + VisMsg::Remove(entity) => { + if let Some((parameter, state)) = panel.page.clone() { + self.apply_bricscad_visibility( + i, + ¶meter, + &state, + Action::Remove, + &[entity], + ); + } + } + VisMsg::AddObjects => { + if let Some((parameter, state)) = panel.page.clone() { + if self.visibility_states_owner(i).is_some() { + self.pick_for_bricscad_visibility( + i, + &format!("_VISIBILITYSTATES{SEP}{parameter}{SEP}{state}{SEP}ADD"), + ); + } + } + } + VisMsg::Highlight(entity) => { + if self.tabs[i].scene.document.get_entity(entity).is_some() { + self.tabs[i].scene.deselect_all(); + self.tabs[i].scene.select_entity(entity, true); + self.refresh_properties(); + } + } + } + Task::none() } } diff --git a/src/app/dock/update.rs b/src/app/dock/update.rs index 79545c604d..0e3da6d5bd 100644 --- a/src/app/dock/update.rs +++ b/src/app/dock/update.rs @@ -625,6 +625,7 @@ impl OpenCADStudio { } PanelId::PointCloudManager => self.pc_manager.show = true, PanelId::Count => self.set_count_palette(true), + PanelId::BricscadVisibility => self.set_bricscad_visibility_panel(true), PanelId::SheetSetManager => self.show_sheet_set_manager(true), PanelId::Layers => { self.sync_ribbon_layers(); @@ -722,6 +723,7 @@ impl OpenCADStudio { self.count_palette.show = false; self.ribbon.set_count_palette(false); } + PanelId::BricscadVisibility => self.bricscad_visibility.show = false, PanelId::SheetSetManager => { self.sheet_set.show = false; self.ribbon.set_sheet_set(false); @@ -873,6 +875,7 @@ impl OpenCADStudio { PanelId::NodeGraph => self.show_node_graph, PanelId::PointCloudManager => self.pc_manager.show, PanelId::Count => self.count_palette.show, + PanelId::BricscadVisibility => self.bricscad_visibility.show, PanelId::SheetSetManager => self.sheet_set.show, PanelId::Layers => self.show_layers, // The walk session is the pallet's state. While the Select Objects diff --git a/src/app/dock/view.rs b/src/app/dock/view.rs index 1f35adbf05..b37fc2f944 100644 --- a/src/app/dock/view.rs +++ b/src/app/dock/view.rs @@ -716,6 +716,12 @@ impl OpenCADStudio { crate::ui::dock::PanelId::NodeGraph => { tab.graph.panel(width, chrome, self.node_graph_links) } + crate::ui::dock::PanelId::BricscadVisibility => crate::ui::window::bricscad_visibility::view( + &self.bricscad_visibility, + self.bricscad_visibility_model(tab), + width, + chrome, + ), crate::ui::dock::PanelId::Count => crate::ui::window::count_palette::view( &self.count_palette, tab.count.as_ref(), diff --git a/src/app/message.rs b/src/app/message.rs index 8e7266ff8d..f0b2b8c2d3 100644 --- a/src/app/message.rs +++ b/src/app/message.rs @@ -2674,6 +2674,8 @@ pub enum Message { /// A click or search in the Point Cloud Manager. PcManager(crate::ui::window::pc_manager::PcManagerMsg), Count(crate::ui::window::count_palette::CountMsg), + /// The Visibility States palette of a BricsCAD parametric block. + BricscadVisibility(crate::ui::window::bricscad_visibility::VisMsg), /// The LayerWalk pallet (LAYWALK). Laywalk(crate::ui::window::layer_walk::LayerWalkMsg), /// The QuickCalc pallet. diff --git a/src/app/mod.rs b/src/app/mod.rs index f3c95588aa..f2e0425ae2 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1466,6 +1466,7 @@ pub(super) struct OpenCADStudio { /// Point Cloud Manager palette (POINTCLOUDMANAGER). pub(crate) pc_manager: crate::ui::window::pc_manager::PcManager, pub(crate) count_palette: crate::ui::window::count_palette::CountPalette, + pub(crate) bricscad_visibility: crate::ui::window::bricscad_visibility::VisibilityPanel, /// The QuickCalc pallet (QUICKCALC / QC). pub(crate) quick_calc: crate::ui::window::quick_calc::QuickCalcPalette, /// The Assistant pallet (ASSISTANT): chat with an external AI agent about this drawing. @@ -3186,6 +3187,7 @@ impl OpenCADStudio { show_browser: false, pc_manager: Default::default(), count_palette: Default::default(), + bricscad_visibility: Default::default(), quick_calc: Default::default(), assistant: Default::default(), sheet_set: Default::default(), diff --git a/src/app/update/dispatch.rs b/src/app/update/dispatch.rs index 5cf1a3d72d..93de6d562a 100644 --- a/src/app/update/dispatch.rs +++ b/src/app/update/dispatch.rs @@ -1943,6 +1943,7 @@ impl OpenCADStudio { Message::PdfShxDialog(message) => self.update_pdf_shx_dialog(message), Message::PcManager(message) => self.update_pc_manager(message), Message::Count(message) => self.on_count(message), + Message::BricscadVisibility(message) => self.on_bricscad_visibility(message), Message::Laywalk(message) => self.on_layer_walk(message), Message::QuickCalc(message) => self.on_quick_calc(message), Message::Assistant(message) => self.on_assistant(message), diff --git a/src/app/visibilitystates_tests.rs b/src/app/visibilitystates_tests.rs index ff79c7f2fc..9194a67032 100644 --- a/src/app/visibilitystates_tests.rs +++ b/src/app/visibilitystates_tests.rs @@ -167,3 +167,141 @@ fn objects_picked_when_the_command_asks_are_the_ones_it_takes() { crate::scene::bricscad_parameters::author_tests::describe(&scene.document) ); } + +mod palette { + use super::*; + use crate::scene::bricscad_parameters::author_tests::LINES; + use crate::ui::window::bricscad_visibility::VisMsg; + + fn send(app: &mut OpenCADStudio, message: VisMsg) { + let _ = app.update(Message::BricscadVisibility(message)); + } + + fn states(app: &OpenCADStudio) -> Vec<(String, Vec, usize)> { + let i = app.active_tab; + let model = app + .bricscad_visibility_model(&app.tabs[i]) + .expect("model space"); + model + .parameters + .as_ref() + .expect("the parameters can be edited") + .iter() + .map(|p| (p.name.clone(), p.states.clone(), p.current)) + .collect() + } + + fn shown_in(app: &OpenCADStudio, parameter: &str, state: &str) -> Vec { + let i = app.active_tab; + let model = app.bricscad_visibility_model(&app.tabs[i]).unwrap(); + let p = model + .parameters + .as_ref() + .unwrap() + .iter() + .find(|p| p.name == parameter) + .unwrap() + .clone(); + let s = p.states.iter().position(|x| x == state).unwrap(); + p.objects + .iter() + .filter(|(_, pattern)| pattern[s]) + .map(|(h, _)| h.value()) + .collect() + } + + #[test] + fn the_palette_switches_moves_adds_and_each_step_undoes() { + let mut app = opened("authoring-select.dwg"); + let i = app.active_tab; + let _ = app.dispatch_command("VISIBILITYSTATESPANELOPEN"); + assert!(app.bricscad_visibility.show); + let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::>(); + assert_eq!( + states(&app)[0], + ("P1".into(), s(&["S1", "S2", "S3", "S4"]), 2) + ); + + // A click on a state shows it. + send(&mut app, VisMsg::Select("P1".into(), "S1".into())); + assert_eq!(states(&app)[0].2, 0); + + // Up and down: the order Properties lists them in. + send(&mut app, VisMsg::Move("P1".into(), "S4".into(), true)); + assert_eq!( + states(&app)[0], + ("P1".into(), s(&["S1", "S2", "S4", "S3"]), 0) + ); + let _ = app.update(Message::Undo); + assert_eq!(states(&app)[0].1, s(&["S1", "S2", "S3", "S4"])); + + // A new state opens its page; a tick shows an object in it. + send(&mut app, VisMsg::NewState("P1".into())); + send(&mut app, VisMsg::NewStateName("Leer".into())); + send(&mut app, VisMsg::NewStateCommit); + assert_eq!( + app.bricscad_visibility.page, + Some(("P1".into(), "Leer".into())) + ); + assert_eq!(shown_in(&app, "P1", "Leer"), Vec::::new()); + send(&mut app, VisMsg::Show(Handle::from(LINES[0]), true)); + assert_eq!(shown_in(&app, "P1", "Leer"), vec![LINES[0]]); + + // Add objects: picked in the drawing, they show in this state only. + send(&mut app, VisMsg::AddObjects); + assert!( + app.tabs[i].active_cmd.is_some(), + "the palette asks for objects" + ); + let _ = app.tabs[i] + .active_cmd + .as_mut() + .unwrap() + .on_entity_pick(Handle::from(LINES[4]), glam::DVec3::ZERO); + feed(&mut app, ""); + assert!(app.tabs[i].active_cmd.is_none()); + assert_eq!(shown_in(&app, "P1", "Leer"), vec![LINES[0], LINES[4]]); + assert_eq!(shown_in(&app, "P1", "S1"), vec![LINES[0], LINES[1]]); + + // Removed from the parameter: no state rules it any more. + send(&mut app, VisMsg::Remove(Handle::from(LINES[4]))); + assert_eq!(shown_in(&app, "P1", "Leer"), vec![LINES[0]]); + let _ = app.update(Message::Undo); + assert_eq!(shown_in(&app, "P1", "Leer"), vec![LINES[0], LINES[4]]); + } + + #[test] + fn a_new_parameter_starts_with_the_objects_picked() { + let mut app = opened("authoring-start.dwg"); + let i = app.active_tab; + let _ = app.dispatch_command("VISIBILITYSTATESPANELOPEN"); + assert_eq!(states(&app), vec![]); + send(&mut app, VisMsg::NewParameter); + send(&mut app, VisMsg::NewParameterName("LAMPE".into())); + send(&mut app, VisMsg::NewParameterState("An".into())); + send(&mut app, VisMsg::NewParameterPick); + for handle in [LINES[1], LINES[2]] { + let _ = app.tabs[i] + .active_cmd + .as_mut() + .expect("the palette asks for objects") + .on_entity_pick(Handle::from(handle), glam::DVec3::ZERO); + } + feed(&mut app, ""); + assert_eq!(states(&app), vec![("LAMPE".into(), vec!["An".into()], 0)]); + assert_eq!(shown_in(&app, "LAMPE", "An"), vec![LINES[1], LINES[2]]); + assert_eq!( + app.bricscad_visibility.page, + Some(("LAMPE".into(), "An".into())) + ); + } + + #[test] + fn outside_model_space_the_palette_shows_nothing_to_edit() { + let mut app = opened("visibility-states.dwg"); + let i = app.active_tab; + assert!(app.bricscad_visibility_model(&app.tabs[i]).is_some()); + let _ = app.dispatch_command(&format!("BEDIT_BEGIN:{}", 0xEE)); + assert!(app.bricscad_visibility_model(&app.tabs[i]).is_none()); + } +} diff --git a/src/locale_catalog.rs b/src/locale_catalog.rs index d8a38cd94f..f57ed389f7 100644 --- a/src/locale_catalog.rs +++ b/src/locale_catalog.rs @@ -1756,6 +1756,42 @@ pub(super) fn message_attribute(source: &str) -> Option<(&'static str, &'static "Visibility state \"{}\" already exists." => Some(("modify", "bvstate-exists")), "The only visibility state cannot be deleted." => Some(("modify", "bvstate-last")), "{}: open the block in the Block Editor first (BEDIT)." => Some(("modify", "bvstate-needs-bedit")), + "VISIBILITYSTATES Enter a new parameter:" => Some(("modify", "visibilitystates-parameter")), + "VISIBILITYSTATES Enter a new parameter or [{}]:" => Some(("modify", "visibilitystates-parameter-or")), + "VISIBILITYSTATES Enter a new state for {}:" => Some(("modify", "visibilitystates-state")), + "VISIBILITYSTATES Enter a new state for {} or [{}]:" => Some(("modify", "visibilitystates-state-or")), + "VISIBILITYSTATES Select action [Add objects/Remove objects/make objects Visible/make objects Invisible/Select state] :" => Some(("modify", "visibilitystates-action")), + "Add objects" => Some(("modify", "visibilitystates-add-objects")), + "Remove objects" => Some(("modify", "visibilitystates-remove-objects")), + "make objects Visible" => Some(("modify", "visibilitystates-make-visible")), + "make objects Invisible" => Some(("modify", "visibilitystates-make-invisible")), + "Select state" => Some(("modify", "visibilitystates-select-state")), + "VISIBILITYSTATES works in model space: open the drawing of the BricsCAD block." => Some(("modify", "visibilitystates-model-space")), + "The visibility states here cannot be edited." => Some(("modify", "visibilitystates-unsupported")), + "Visibility states need a drawing in DWG 2010 format or later." => Some(("modify", "visibilitystates-old-format")), + "No visibility parameter of that name." => Some(("modify", "visibilitystates-no-parameter")), + "No visibility state of that name." => Some(("modify", "visibilitystates-no-state")), + "That visibility state exists already." => Some(("modify", "visibilitystates-state-exists")), + "The visibility state cannot move further." => Some(("modify", "visibilitystates-cannot-move")), + "Enter a name of letters, digits and underscores." => Some(("modify", "visibilitystates-bad-name")), + "That name is used by another variable." => Some(("modify", "visibilitystates-name-taken")), + "Select objects of the space being edited." => Some(("modify", "visibilitystates-no-objects")), + "Visibility states are edited in model space of the block's own drawing." => Some(("modify", "visibilitystates-panel-elsewhere")), + "The visibility states of this drawing cannot be edited here." => Some(("modify", "visibilitystates-panel-unsupported")), + "First state" => Some(("modify", "visibilitystates-first-state")), + "There are no visibility states in this drawing. Click + to add a parameter." => Some(("modify", "visibilitystates-panel-empty")), + "{} ({} objects)" => Some(("modify", "visibilitystates-parameter-objects")), + "Move up" => Some(("modify", "visibilitystates-move-up")), + "Move down" => Some(("modify", "visibilitystates-move-down")), + "Objects of this state" => Some(("modify", "visibilitystates-state-objects")), + "New state" => Some(("modify", "visibilitystates-new-state")), + "Add state" => Some(("modify", "visibilitystates-add-state")), + "Back to the parameters" => Some(("modify", "visibilitystates-back")), + "Add objects to this state" => Some(("modify", "visibilitystates-add-to-state")), + "The parameter rules no objects yet. Add objects to this state." => Some(("modify", "visibilitystates-no-objects-yet")), + "Remove from parameter" => Some(("modify", "visibilitystates-remove-from-parameter")), + "Shown the same in every state of the parameter" => Some(("modify", "visibilitystates-same-everywhere")), + "One or more objects show the same in every state of this parameter." => Some(("modify", "visibilitystates-same-everywhere-note")), "Current visibility state: {}" => Some(("modify", "bvstate-current")), "Select objects to hide:" => Some(("modify", "bvhide-select")), "Select objects to make visible:" => Some(("modify", "bvshow-select")), diff --git a/src/modules/draw/modify/visibilitystates.rs b/src/modules/draw/modify/visibilitystates.rs index 0a48e90c9e..b119dbe58a 100644 --- a/src/modules/draw/modify/visibilitystates.rs +++ b/src/modules/draw/modify/visibilitystates.rs @@ -45,14 +45,6 @@ impl VisibilityStatesCommand { .unwrap_or_default() } - fn list(names: &[String]) -> String { - if names.is_empty() { - String::new() - } else { - format!(" or [{}]", names.join("/")) - } - } - fn done(parts: &[&str]) -> CmdResult { let mut command = String::from("_VISIBILITYSTATES"); for part in parts { @@ -72,18 +64,30 @@ impl CadCommand for VisibilityStatesCommand { match &self.step { Step::Parameter => { let names: Vec = self.parameters.iter().map(|(n, _)| n.clone()).collect(); - crate::tf!( - "VISIBILITYSTATES Enter a new parameter{}:", - Self::list(&names) - ) - .into_owned() + if names.is_empty() { + crate::t!("VISIBILITYSTATES Enter a new parameter:").into_owned() + } else { + crate::tf!( + "VISIBILITYSTATES Enter a new parameter or [{}]:", + names.join("/") + ) + .into_owned() + } + } + Step::State(parameter) => { + let states = self.states(parameter); + if states.is_empty() { + crate::tf!("VISIBILITYSTATES Enter a new state for {}:", parameter) + .into_owned() + } else { + crate::tf!( + "VISIBILITYSTATES Enter a new state for {} or [{}]:", + parameter, + states.join("/") + ) + .into_owned() + } } - Step::State(parameter) => crate::tf!( - "VISIBILITYSTATES Enter a new state for {}{}:", - parameter, - Self::list(&self.states(parameter)) - ) - .into_owned(), Step::Action(..) => crate::t!( "VISIBILITYSTATES Select action [Add objects/Remove objects/make objects Visible/make objects Invisible/Select state] :" ) @@ -143,13 +147,14 @@ impl CadCommand for VisibilityStatesCommand { Some(CmdResult::NeedPoint) } Step::Action(parameter, state) => { + // A translated prompt hands back the whole source option. let keyword = text.trim_start_matches('_').to_ascii_uppercase(); let action = match keyword.as_str() { - "" | "A" | "ADD" => "ADD", - "R" | "REMOVE" => "REMOVE", - "V" | "VISIBLE" => "VISIBLE", - "I" | "INVISIBLE" => "INVISIBLE", - "S" | "SELECT" | "ST" | "STATE" => "SELECT", + "" | "A" | "ADD" | "ADD OBJECTS" => "ADD", + "R" | "REMOVE" | "REMOVE OBJECTS" => "REMOVE", + "V" | "VISIBLE" | "MAKE OBJECTS VISIBLE" => "VISIBLE", + "I" | "INVISIBLE" | "MAKE OBJECTS INVISIBLE" => "INVISIBLE", + "S" | "SELECT" | "ST" | "STATE" | "SELECT STATE" => "SELECT", _ => { return Some(CmdResult::ReportError( crate::t!("Invalid option keyword.").into_owned(), @@ -175,7 +180,11 @@ impl CadCommand for VisibilityStatesCommand { } inventory::submit!(crate::command::CommandRegistration { - names: &["VISIBILITYSTATES"] + names: &[ + "VISIBILITYSTATES", + "VISIBILITYSTATESPANELOPEN", + "VISIBILITYSTATESPANELCLOSE" + ] }); #[cfg(test)] @@ -218,6 +227,8 @@ mod tests { ("v", "VISIBLE"), ("_Invisible", "INVISIBLE"), ("S", "SELECT"), + ("make objects Visible", "VISIBLE"), + ("Select state", "SELECT"), ] { let mut command = command(); command.on_text_input("Label"); diff --git a/src/modules/parametric/mod.rs b/src/modules/parametric/mod.rs index a117a91c25..afefb28c52 100644 --- a/src/modules/parametric/mod.rs +++ b/src/modules/parametric/mod.rs @@ -180,6 +180,12 @@ impl CadModule for ParametricModule { "Parameters Manager", include_bytes!("../../../assets/icons/constrain/parameters.svg"), )), + // The visibility states of a BricsCAD parametric block. + RibbonItem::LargeTool(command( + "VISIBILITYSTATESPANELOPEN", + "Visibility States", + crate::ui::icons::EYE, + )), ], }, ] @@ -278,7 +284,7 @@ mod tests { ); assert_eq!( groups[2].tools.iter().map(item_id).collect::>(), - ["DELCONSTRAINT", "PARAMETERS"] + ["DELCONSTRAINT", "PARAMETERS", "VISIBILITYSTATESPANELOPEN"] ); let RibbonItem::LargeDropdown { items, default, .. } = &groups[1].tools[0] else { diff --git a/src/scene/bricscad_parameters.rs b/src/scene/bricscad_parameters.rs index 8f58a6997f..026b597d36 100644 --- a/src/scene/bricscad_parameters.rs +++ b/src/scene/bricscad_parameters.rs @@ -28,7 +28,7 @@ mod author; pub(crate) mod record; mod switch; -pub(crate) use author::{parameter_states, Action}; +pub(crate) use author::{parameter_states, parameter_views, shown_layers, Action, ParameterView}; pub(crate) use switch::can_switch; diff --git a/src/scene/bricscad_parameters/author.rs b/src/scene/bricscad_parameters/author.rs index 4d6edf648b..4bc1b11538 100644 --- a/src/scene/bricscad_parameters/author.rs +++ b/src/scene/bricscad_parameters/author.rs @@ -55,12 +55,22 @@ pub(crate) enum Action { Invisible, /// Make the state current. Select, + /// Add the state, with every object the parameter rules hidden, and make + /// it current (the palette's "Add state"; the command makes a state with + /// its first action). + NewState, + /// Move the state one place up or down in the parameter's list, the + /// order Properties lists the states in. + MoveUp, + MoveDown, } const UNSUPPORTED: &str = "The visibility states here cannot be edited."; const OLD_FORMAT: &str = "Visibility states need a drawing in DWG 2010 format or later."; const NO_PARAMETER: &str = "No visibility parameter of that name."; const NO_STATE: &str = "No visibility state of that name."; +const STATE_EXISTS: &str = "That visibility state exists already."; +const CANNOT_MOVE: &str = "The visibility state cannot move further."; const BAD_NAME: &str = "Enter a name of letters, digits and underscores."; const NAME_TAKEN: &str = "That name is used by another variable."; const NO_OBJECTS: &str = "Select objects of the space being edited."; @@ -154,6 +164,67 @@ impl Naming { } /// The visibility parameters of an owner, with their states, for the prompts. +/// A visibility parameter of an owner as the palette shows it. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct ParameterView { + pub(crate) name: String, + pub(crate) states: Vec, + /// The state shown, by index into `states`. + pub(crate) current: usize, + /// Each object the parameter rules, in drawing order, with whether it + /// shows in each state. + pub(crate) objects: Vec<(Handle, Vec)>, +} + +/// The visibility parameters of `owner` with the objects each rules; `None` +/// when they cannot be edited here. +pub(crate) fn parameter_views(document: &Document, owner: Handle) -> Option> { + let setup = Setup::read(document, owner).ok()?; + let order: FxHashMap = owner_members(document, owner) + .into_iter() + .enumerate() + .map(|(k, handle)| (handle, k)) + .collect(); + Some( + setup + .parameters + .iter() + .enumerate() + .map(|(p, parameter)| { + let mut objects: Vec<(Handle, Vec)> = setup + .groups + .iter() + .enumerate() + .filter_map(|(g, group)| { + let pattern = setup.signature(g).remove(&p)?; + Some( + group + .members + .iter() + .map(move |member| (member.entity, pattern.clone())), + ) + }) + .flatten() + .collect(); + objects.sort_by_key(|(entity, _)| order.get(entity).copied().unwrap_or(usize::MAX)); + ParameterView { + name: parameter.name.clone(), + states: parameter.states.clone(), + current: parameter + .current + .min(parameter.states.len().saturating_sub(1)), + objects, + } + }) + .collect(), + ) +} + +/// The layer each member of `owner` is on when no state hides it. +pub(crate) fn shown_layers(document: &Document, owner: Handle) -> FxHashMap { + original_layers(document, owner) +} + pub(crate) fn parameter_states(document: &Document, owner: Handle) -> Vec<(String, Vec)> { Setup::read(document, owner) .map(|setup| { @@ -222,7 +293,9 @@ impl Scene { .position(|p| p.name.eq_ignore_ascii_case(parameter)) { Some(p) => p, - None if matches!(action, Action::Select | Action::Remove) => return Err(NO_PARAMETER), + None if !matches!(action, Action::Add | Action::Visible | Action::Invisible) => { + return Err(NO_PARAMETER) + } None => { if !valid_name(parameter) { return Err(BAD_NAME); @@ -242,11 +315,31 @@ impl Scene { .iter() .position(|s| s.eq_ignore_ascii_case(state)) { + Some(_) if action == Action::NewState => return Err(STATE_EXISTS), Some(s) => s, - None if matches!(action, Action::Select | Action::Remove) => return Err(NO_STATE), - None => setup.parameters[p].add_state(state), + None if matches!( + action, + Action::Select | Action::Remove | Action::MoveUp | Action::MoveDown + ) => + { + return Err(NO_STATE) + } + None => { + if !valid_name(state) { + return Err(BAD_NAME); + } + setup.parameters[p].add_state(state) + } }; - if action == Action::Select { + if matches!(action, Action::MoveUp | Action::MoveDown) { + let parameter = &mut setup.parameters[p]; + let to = if action == Action::MoveUp { + s.checked_sub(1) + } else { + (s + 1 < parameter.states.len()).then_some(s + 1) + }; + parameter.swap_states(s, to.ok_or(CANNOT_MOVE)?); + } else if matches!(action, Action::Select | Action::NewState) { setup.parameters[p].current = s; } else { // BricsCAD works through a selection from its last object. @@ -295,7 +388,7 @@ impl Scene { &BTreeSet::new(), true, )?; - let chosen = (action == Action::Select).then_some(parameter_name); + let chosen = matches!(action, Action::Select | Action::NewState).then_some(parameter_name); number_keys(&mut self.document, owner, chosen.as_deref())?; self.load_named_parameters_from_document(); self.load_parametric_constraints_from_document(); @@ -485,6 +578,19 @@ impl Parameter { } /// A new state, in which every group is hidden. + /// Swap two states with their rows; the shown state stays shown. + fn swap_states(&mut self, a: usize, b: usize) { + self.states.swap(a, b); + for column in &mut self.columns { + column.values.swap(a, b); + } + if self.current == a { + self.current = b; + } else if self.current == b { + self.current = a; + } + } + fn add_state(&mut self, name: &str) -> usize { self.states.push(name.to_string()); for column in &mut self.columns { @@ -898,7 +1004,9 @@ impl Setup { let old = group.map(|g| self.signature(g)).unwrap_or_default(); let mut new = old.clone(); match (old.get(&p), action) { - (Some(_), Action::Add) | (None, Action::Remove) | (_, Action::Select) => {} + (Some(_), Action::Add) + | (None, Action::Remove) + | (_, Action::Select | Action::NewState | Action::MoveUp | Action::MoveDown) => {} (Some(_), Action::Remove) => { new.remove(&p); } diff --git a/src/scene/bricscad_parameters/author_tests.rs b/src/scene/bricscad_parameters/author_tests.rs index d6e1d62cab..60cfb43f60 100644 --- a/src/scene/bricscad_parameters/author_tests.rs +++ b/src/scene/bricscad_parameters/author_tests.rs @@ -3,7 +3,7 @@ //! along one run of the command on five lines (see the README there). The //! same run here leaves the same visibility setup. -use super::author::Action; +use super::author::{Action, Naming}; use super::record::Value; use super::*; use crate::scene::Scene; @@ -70,7 +70,7 @@ pub(super) fn run(scene: &mut Scene, steps: &[Step]) { state, *action, &objects, - super::author::Naming::GERMAN, + Naming::GERMAN, ) .unwrap_or_else(|error| panic!("{parameter} {state} {action:?} {lines:?}: {error}")); } @@ -428,6 +428,140 @@ fn a_new_group_takes_a_name_no_variable_has() { ); } +/// Each state of `parameter` by name with the objects it shows. +fn shown_by_state( + document: &Document, + parameter: &str, +) -> std::collections::BTreeMap> { + let model = document.header.model_space_block_handle; + let view = super::parameter_views(document, model) + .unwrap() + .into_iter() + .find(|p| p.name == parameter) + .unwrap(); + view.states + .iter() + .enumerate() + .map(|(s, state)| { + ( + state.clone(), + view.objects + .iter() + .filter(|(_, pattern)| pattern[s]) + .map(|(entity, _)| entity.value()) + .collect(), + ) + }) + .collect() +} + +fn states_of(document: &Document, parameter: &str) -> (Vec, usize) { + let model = document.header.model_space_block_handle; + let view = super::parameter_views(document, model) + .unwrap() + .into_iter() + .find(|p| p.name == parameter) + .unwrap(); + (view.states, view.current) +} + +/// The number the key variable of `parameter` holds. +fn key_number(document: &Document, parameter: &str) -> Value { + let model = document.header.model_space_block_handle; + for feature in features(document, model) { + let properties = super::properties(document, feature).unwrap(); + if properties.text("Name") != Some(parameter) { + continue; + } + for reactor in properties.get("Reactors").unwrap().items().unwrap() { + let reactor = super::properties(document, reactor.object().unwrap()).unwrap(); + if reactor.get("IsKeyVar") == Some(&Value::Flag(true)) { + return reactor.get("Value").unwrap().clone(); + } + } + } + panic!("no key of {parameter}"); +} + +#[test] +fn a_state_moves_with_its_objects_and_the_shown_state_stays_shown() { + let mut scene = fixture("authoring-select.dwg"); + let before = shown_by_state(&scene.document, "P1"); + assert_eq!( + states_of(&scene.document, "P1"), + (vec!["S1".into(), "S2".into(), "S3".into(), "S4".into()], 2) + ); + let layers = |document: &Document| -> Vec { + LINES + .iter() + .map(|h| { + document + .get_entity(Handle::from(*h)) + .unwrap() + .common() + .layer + .clone() + }) + .collect() + }; + let shown = layers(&scene.document); + run(&mut scene, &[("P1", "S3", Action::MoveUp, &[])]); + assert_eq!( + states_of(&scene.document, "P1"), + (vec!["S1".into(), "S3".into(), "S2".into(), "S4".into()], 1) + ); + assert_eq!(shown_by_state(&scene.document, "P1"), before); + assert_eq!(layers(&scene.document), shown, "the drawing shows the same"); + assert_eq!(key_number(&scene.document, "P1"), Value::Real(1.0)); + run(&mut scene, &[("P1", "S1", Action::MoveDown, &[])]); + assert_eq!( + states_of(&scene.document, "P1"), + (vec!["S3".into(), "S1".into(), "S2".into(), "S4".into()], 0) + ); + assert_eq!(shown_by_state(&scene.document, "P1"), before); + // Past either end nothing moves. + let model = scene.document.header.model_space_block_handle; + let unchanged = scene.document.clone(); + for (state, action) in [("S3", Action::MoveUp), ("S4", Action::MoveDown)] { + assert!(scene + .edit_bricscad_visibility_named(model, "P1", state, action, &[], Naming::GERMAN) + .is_err()); + } + assert!(scene.document == unchanged); +} + +#[test] +fn a_new_state_hides_every_object_of_its_parameter_and_is_shown() { + let mut scene = fixture("authoring-select.dwg"); + run(&mut scene, &[("P1", "Leer", Action::NewState, &[])]); + let (states, current) = states_of(&scene.document, "P1"); + assert_eq!(states.last().map(String::as_str), Some("Leer")); + assert_eq!(current, states.len() - 1); + assert_eq!( + shown_by_state(&scene.document, "P1")["Leer"], + Vec::::new() + ); + // L1 and L2 are ruled by P1 (L2 also by P2): both hidden now. + for handle in [0x92, 0x93] { + assert_eq!( + scene + .document + .get_entity(Handle::from(handle)) + .unwrap() + .common() + .layer, + "*SUPPRESS" + ); + } + let model = scene.document.header.model_space_block_handle; + assert!(scene + .edit_bricscad_visibility_named(model, "P1", "leer", Action::NewState, &[], Naming::GERMAN) + .is_err()); + assert!(scene + .edit_bricscad_visibility_named(model, "P9", "S1", Action::NewState, &[], Naming::GERMAN) + .is_err()); +} + /// The key of `parameter`: whether enabled, its number, its variable's /// expression and value. fn key_of( @@ -510,7 +644,8 @@ fn a_disabled_key_is_left_alone_until_its_state_is_picked() { &mut scene, &[ ("P1", "S1", Action::Select, &[]), - ("P1", "S4", Action::Invisible, &[4]), + ("P1", "S4", Action::MoveUp, &[]), + ("P1", "Neu", Action::NewState, &[]), ("P1", "S2", Action::Visible, &[5]), ], ); @@ -520,8 +655,8 @@ fn a_disabled_key_is_left_alone_until_its_state_is_picked() { "P2 was not asked about" ); assert_eq!( - current_state(&scene.document, model, "P2").as_deref(), - Some("Sichtbar"), + states_of(&scene.document, "P2").1, + 0, "still shows Sichtbar" ); run(&mut scene, &[("P2", "Unsichtbar", Action::Select, &[])]); diff --git a/src/ui/dock.rs b/src/ui/dock.rs index 76eb0eec44..ec458c5d15 100644 --- a/src/ui/dock.rs +++ b/src/ui/dock.rs @@ -133,6 +133,8 @@ pub enum PanelId { PointCloudManager, /// Block counts (COUNTLIST). Count, + /// Visibility states of a BricsCAD parametric block (VISIBILITYSTATESPANELOPEN). + BricscadVisibility, /// The open sheet sets: subsets and sheets. SheetSetManager, /// The Layer Manager (LAYERS). @@ -151,7 +153,7 @@ pub enum PanelId { impl PanelId { /// Every panel, in the order the pallet menu lists them. - pub const ALL: [PanelId; 17] = [ + pub const ALL: [PanelId; 18] = [ PanelId::Properties, PanelId::GraphicAttributes, PanelId::BlockPalette, @@ -163,6 +165,7 @@ impl PanelId { PanelId::NodeGraph, PanelId::PointCloudManager, PanelId::Count, + PanelId::BricscadVisibility, PanelId::SheetSetManager, PanelId::Layers, PanelId::Laywalk, @@ -185,6 +188,7 @@ impl PanelId { PanelId::NodeGraph => "Node Graph", PanelId::PointCloudManager => "Point Cloud Manager", PanelId::Count => "Count", + PanelId::BricscadVisibility => "Visibility States", PanelId::SheetSetManager => "Sheet Set Manager", PanelId::Layers => "Layer Manager", PanelId::Laywalk => "Layer Walk", @@ -211,6 +215,7 @@ impl PanelId { PanelId::NodeGraph => crate::ui::icons::NODE_GRAPH, PanelId::PointCloudManager => include_bytes!("../../assets/icons/pc_attach.svg"), PanelId::Count => include_bytes!("../../assets/icons/data_extract.svg"), + PanelId::BricscadVisibility => include_bytes!("../../assets/icons/ui/eye.svg"), PanelId::SheetSetManager => include_bytes!("../../assets/icons/sheetset.svg"), PanelId::Layers => include_bytes!("../../assets/icons/layers/panel.svg"), PanelId::Laywalk => include_bytes!("../../assets/icons/layers/laywalk.svg"), @@ -235,6 +240,7 @@ impl PanelId { PanelId::NodeGraph => 220.0, PanelId::PointCloudManager => 280.0, PanelId::Count => 280.0, + PanelId::BricscadVisibility => 280.0, PanelId::SheetSetManager => 280.0, PanelId::Layers => 560.0, PanelId::Laywalk => 420.0, diff --git a/src/ui/ribbon/keytips.rs b/src/ui/ribbon/keytips.rs index ef61c7db19..4673882e93 100644 --- a/src/ui/ribbon/keytips.rs +++ b/src/ui/ribbon/keytips.rs @@ -477,6 +477,7 @@ const CODES: &[(&str, &str, &str)] = &[ ("parametric", "DCHIDEALL", "HD"), ("parametric", "DELCONSTRAINT", "DE"), ("parametric", "PARAMETERS", "PM"), + ("parametric", "VISIBILITYSTATESPANELOPEN", "VS"), // Model (the reference Solid tab). ("model", "MODEL_PRIMITIVES", "SS"), ("MODEL_PRIMITIVES", "BOX", "BO"), diff --git a/src/ui/window/bricscad_visibility.rs b/src/ui/window/bricscad_visibility.rs new file mode 100644 index 0000000000..3794052deb --- /dev/null +++ b/src/ui/window/bricscad_visibility.rs @@ -0,0 +1,430 @@ +//! The Visibility States palette (VISIBILITYSTATESPANELOPEN): the visibility +//! parameters of a BricsCAD parametric block in model space of the block's +//! own drawing, edited the way `VISIBILITYSTATES` edits them. +//! +//! The overview lists each parameter with its states; a click on a state +//! shows it, the arrow opens the state's page. A state's page lists every +//! object the parameter rules with whether it shows in that state, and adds +//! or removes objects. Every change goes through the command's own edit +//! (`scene::bricscad_parameters::author`), one undo step each. + +use crate::app::Message; +use crate::scene::bricscad_parameters::ParameterView; +use crate::ui::dock::PanelId; +use crate::ui::kit; +use crate::ui::kit::field_style; +use crate::ui::style::kit_metrics as km; +use document::Handle; +use iced::widget::{column, container, row, text_input, Space}; +use iced::{Element, Fill, Length, Padding}; +use rustc_hash::FxHashMap; +use std::cell::RefCell; +use std::rc::Rc; + +const ADD_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/plus.svg"); +const OPEN_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/tri_right.svg"); +const BACK_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/tri_left.svg"); +const UP_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/tri_up.svg"); +const DOWN_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/tri_down.svg"); +const SHOWN_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/eye.svg"); +const HIDDEN_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/eye_off.svg"); +const REMOVE_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/close.svg"); +const PICK_ICON: &[u8] = include_bytes!("../../../assets/icons/blocks/select_objects.svg"); +const WARNING_ICON: &[u8] = include_bytes!("../../../assets/icons/ui/warning_triangle.svg"); + +/// The palette's own state; the parameters come from the drawing. +#[derive(Debug, Clone, Default)] +pub struct VisibilityPanel { + pub show: bool, + /// The state whose page is open: parameter and state. + pub page: Option<(String, String)>, + /// A parameter being added: its name and its first state. + pub new_parameter: Option<(String, String)>, + /// A state being added: the parameter and the name typed. + pub new_state: Option<(String, String)>, + /// Folded parameters (names in upper case). + pub folded: Vec, + /// What the drawing holds, read at (document id, edit revision, language). + pub cache: RefCell)>>, +} + +/// A drawing's visibility parameters as the palette shows them. +#[derive(Debug, Default)] +pub struct Model { + /// `None` when they cannot be edited here. + pub parameters: Option>, + /// Each ruled object's line: type, layer when shown, handle. + pub labels: FxHashMap, +} + +#[derive(Debug, Clone)] +pub enum VisMsg { + /// Show the state (parameter, state). + Select(String, String), + /// Open the state's page. + Open(String, String), + /// Move the state one place up (`true`) or down in the parameter's list. + Move(String, String, bool), + Back, + Fold(String), + NewParameter, + NewParameterName(String), + NewParameterState(String), + /// Pick the objects the new parameter starts with. + NewParameterPick, + NewState(String), + NewStateName(String), + NewStateCommit, + Cancel, + /// Show or hide an object in the open state. + Show(Handle, bool), + /// The parameter no longer rules the object. + Remove(Handle), + /// Pick objects for the open state. + AddObjects, + /// Select the object in the drawing. + Highlight(Handle), +} + +fn msg(m: VisMsg) -> Message { + Message::BricscadVisibility(m) +} + +fn icon<'a>(bytes: &'static [u8]) -> Element<'a, Message> { + crate::ui::icons::semantic(bytes, km::ROW_ICON) +} + +/// Read what `document`'s model space holds for the palette. +pub fn read(document: &document::Document) -> Model { + let owner = document.header.model_space_block_handle; + let parameters = crate::scene::bricscad_parameters::parameter_views(document, owner); + let layers = crate::scene::bricscad_parameters::shown_layers(document, owner); + let mut labels = FxHashMap::default(); + for parameter in parameters.iter().flatten() { + for (entity, _) in ¶meter.objects { + labels.entry(*entity).or_insert_with(|| { + let kind = document + .get_entity(*entity) + .map(|e| crate::t!(crate::entities::names::ui_name(e)).into_owned()) + .unwrap_or_default(); + let layer = layers.get(entity).cloned().unwrap_or_default(); + format!("{kind} · {layer} · {:X}", entity.value()) + }); + } + } + Model { parameters, labels } +} + +/// `None` outside model space. +pub fn view<'a>( + panel: &'a VisibilityPanel, + model: Option>, + width: f32, + chrome: crate::ui::dock::Chrome, +) -> Element<'a, Message> { + let title_bar = crate::ui::dock::title_bar( + PanelId::BricscadVisibility, + crate::t!("Visibility States").into_owned(), + chrome, + ); + let body = match model.as_deref() { + None => kit::empty_state(crate::t!( + "Visibility states are edited in model space of the block's own drawing." + )), + Some(Model { + parameters: None, .. + }) => kit::empty_state(crate::t!( + "The visibility states of this drawing cannot be edited here." + )), + Some(Model { + parameters: Some(parameters), + labels, + }) => { + let page = panel.page.as_ref().and_then(|(parameter, state)| { + let p = parameters + .iter() + .find(|p| p.name.eq_ignore_ascii_case(parameter))?; + let s = p + .states + .iter() + .position(|x| x.eq_ignore_ascii_case(state))?; + Some((p, s)) + }); + match page { + Some((parameter, s)) => state_page(parameter, s, labels), + None => overview(panel, parameters), + } + } + }; + kit::palette(title_bar, body, width) +} + +fn name_field<'a>( + placeholder: String, + value: &str, + on_input: impl Fn(String) -> VisMsg + 'a, + on_submit: Option, +) -> Element<'a, Message> { + let mut field = text_input(&placeholder, value) + .size(crate::ui::style::text::UI) + .padding([0.0, km::CELL_PAD_X]) + .style(field_style) + .on_input(move |v| msg(on_input(v))); + if let Some(m) = on_submit { + field = field.on_submit(msg(m)); + } + field.into() +} + +fn overview<'a>(panel: &'a VisibilityPanel, parameters: &[ParameterView]) -> Element<'a, Message> { + let top = kit::band( + row![ + kit::tool_button( + icon(ADD_ICON), + crate::t!("Add parameter").into_owned(), + Some(msg(VisMsg::NewParameter)), + panel.new_parameter.is_some(), + ), + Space::new().width(Fill), + ] + .spacing(km::TOOL_GAP) + .align_y(iced::Center), + ); + let mut list = column![]; + if let Some((name, state)) = &panel.new_parameter { + list = list.push( + container( + column![ + name_field( + crate::t!("Parameter name").into_owned(), + name, + VisMsg::NewParameterName, + None, + ), + name_field( + crate::t!("First state").into_owned(), + state, + VisMsg::NewParameterState, + Some(VisMsg::NewParameterPick), + ), + row![ + Space::new().width(Fill), + kit::text_button( + crate::t!("Cancel").into_owned(), + Some(msg(VisMsg::Cancel)), + false, + ), + kit::text_button( + crate::t!("Select objects").into_owned(), + (!name.trim().is_empty() && !state.trim().is_empty()) + .then(|| msg(VisMsg::NewParameterPick)), + true, + ), + ] + .spacing(km::TOOL_GAP) + .align_y(iced::Center), + ] + .spacing(km::TOOL_GAP), + ) + .padding(Padding { + top: km::TOOL_GAP, + bottom: km::TOOL_GAP, + left: km::GRID_INSET_L, + right: km::GRID_INSET_R, + }), + ); + } + if parameters.is_empty() && panel.new_parameter.is_none() { + list = list.push(kit::empty_state(crate::t!( + "There are no visibility states in this drawing. Click + to add a parameter." + ))); + } + for parameter in parameters { + let key = parameter.name.to_uppercase(); + let folded = panel.folded.contains(&key); + list = list.push(kit::category_bar( + crate::tf!("{} ({} objects)", parameter.name, parameter.objects.len()).into_owned(), + folded, + msg(VisMsg::Fold(parameter.name.clone())), + )); + if folded { + continue; + } + for (s, state) in parameter.states.iter().enumerate() { + let current = s == parameter.current; + let step = |bytes: &'static [u8], up: bool, possible: bool, tip: String| { + kit::tooltip( + kit::toggle_cell( + icon(bytes), + possible + .then(|| msg(VisMsg::Move(parameter.name.clone(), state.clone(), up))), + ), + tip, + kit::TipPosition::Bottom, + ) + }; + let open = row![ + step(UP_ICON, true, s > 0, crate::t!("Move up").into_owned()), + step( + DOWN_ICON, + false, + s + 1 < parameter.states.len(), + crate::t!("Move down").into_owned() + ), + kit::tooltip( + kit::toggle_cell( + icon(OPEN_ICON), + Some(msg(VisMsg::Open(parameter.name.clone(), state.clone()))), + ), + crate::t!("Objects of this state").into_owned(), + kit::TipPosition::Bottom, + ), + ] + .align_y(iced::Center); + list = list.push( + kit::tree_row(state.clone()) + .icon(kit::menu::dot( + km::CHECK / 2.0, + if current { + crate::ui::style::chrome::accent + } else { + crate::ui::style::chrome::surface_raised + }, + )) + .selected(current) + .trailing(open) + .on_press(msg(VisMsg::Select(parameter.name.clone(), state.clone()))) + .on_double_click(msg(VisMsg::Open(parameter.name.clone(), state.clone()))) + .view(), + ); + } + match &panel.new_state { + Some((p, name)) if p.eq_ignore_ascii_case(¶meter.name) => { + list = list.push( + container( + row![ + name_field( + crate::t!("New state").into_owned(), + name, + VisMsg::NewStateName, + Some(VisMsg::NewStateCommit), + ), + kit::text_button( + crate::t!("Cancel").into_owned(), + Some(msg(VisMsg::Cancel)), + false, + ), + kit::text_button( + crate::t!("Add").into_owned(), + (!name.trim().is_empty()).then(|| msg(VisMsg::NewStateCommit)), + true, + ), + ] + .spacing(km::TOOL_GAP) + .align_y(iced::Center), + ) + .padding(Padding::ZERO.left(km::GRID_INSET_L).right(km::GRID_INSET_R)), + ); + } + _ => { + list = list.push( + kit::tree_row(crate::t!("Add state").into_owned()) + .icon(icon(ADD_ICON)) + .muted(true) + .on_press(msg(VisMsg::NewState(parameter.name.clone()))) + .view(), + ); + } + } + } + column![top, container(kit::scroll_area(list)).height(Fill)].into() +} + +fn state_page<'a>( + parameter: &ParameterView, + s: usize, + labels: &FxHashMap, +) -> Element<'a, Message> { + let state = ¶meter.states[s]; + let current = s == parameter.current; + let top = kit::band( + row![ + kit::tool_button( + icon(BACK_ICON), + crate::t!("Back to the parameters").into_owned(), + Some(msg(VisMsg::Back)), + false, + ), + container(kit::value_text( + format!("{} › {}", parameter.name, state), + false + )) + .width(Fill), + kit::text_button( + crate::t!("Show").into_owned(), + (!current).then(|| msg(VisMsg::Select(parameter.name.clone(), state.clone()))), + false, + ), + kit::tool_button( + icon(PICK_ICON), + crate::t!("Add objects to this state").into_owned(), + Some(msg(VisMsg::AddObjects)), + false, + ), + ] + .spacing(km::TOOL_GAP) + .align_y(iced::Center), + ); + let mut list = column![]; + if parameter.objects.is_empty() { + list = list.push(kit::empty_state(crate::t!( + "The parameter rules no objects yet. Add objects to this state." + ))); + } + let mut constant = false; + for (entity, pattern) in ¶meter.objects { + let shown = pattern.get(s).copied().unwrap_or(false); + let same_everywhere = pattern.iter().all(|v| *v == pattern[0]); + constant |= same_everywhere; + let label = labels.get(entity).cloned().unwrap_or_default(); + let toggle = kit::toggle_cell( + icon(if shown { SHOWN_ICON } else { HIDDEN_ICON }), + Some(msg(VisMsg::Show(*entity, !shown))), + ); + let remove = kit::tooltip( + kit::toggle_cell(icon(REMOVE_ICON), Some(msg(VisMsg::Remove(*entity)))), + crate::t!("Remove from parameter").into_owned(), + kit::TipPosition::Bottom, + ); + let mut cells: Vec<(Element<'a, Message>, Length)> = vec![ + (toggle, Length::Shrink), + (kit::text_cell(label, !shown), Length::Fill), + ]; + if same_everywhere { + cells.push(( + kit::tooltip( + icon(WARNING_ICON), + crate::t!("Shown the same in every state of the parameter").into_owned(), + kit::TipPosition::Bottom, + ), + Length::Shrink, + )); + } + cells.push((remove, Length::Shrink)); + list = list.push( + kit::list_row(cells) + .on_press(msg(VisMsg::Highlight(*entity))) + .view(), + ); + } + let footer = constant.then(|| { + kit::footer_text(crate::t!( + "One or more objects show the same in every state of this parameter." + )) + }); + let mut page = column![top, container(kit::scroll_area(list)).height(Fill)]; + if let Some(footer) = footer { + page = page.push(footer); + } + page.into() +} diff --git a/src/ui/window/mod.rs b/src/ui/window/mod.rs index 230e47f76e..665146b478 100644 --- a/src/ui/window/mod.rs +++ b/src/ui/window/mod.rs @@ -18,6 +18,7 @@ pub mod block_palette; pub mod block_properties_table; pub mod block_save_as; pub mod block_visibility; +pub mod bricscad_visibility; pub mod browser; pub mod count_palette; pub mod design_center;