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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions src/app/block_parameter_properties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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 {
Expand Down Expand Up @@ -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)
};
Expand Down Expand Up @@ -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 {
Expand All @@ -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),
}
};
Expand Down
177 changes: 177 additions & 0 deletions src/app/bricscad_visibility_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
//! 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, and a state picked there is shown the way
//! BricsCAD shows it.

use super::*;
use crate::scene::model::object::{BlockParameterComponent, BlockParameterKey, 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, shown state and states, with their keys.
fn visibility_rows(app: &OpenCADStudio) -> Vec<(String, String, Vec<String>, BlockParameterKey)> {
app.tabs[app.active_tab]
.properties
.sections
.iter()
.flat_map(|section| &section.props)
.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
.sections
.iter()
.flat_map(|section| &section.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:?}"),
}
}

/// 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_lists_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!(
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",
"{reference:X} shows its block's name, not its copy's"
);
}
}

#[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}"
);
}
}
12 changes: 11 additions & 1 deletion src/app/control/block_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
9 changes: 9 additions & 0 deletions src/app/properties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1073,6 +1073,15 @@ impl OpenCADStudio {
custom_properties.extend(Self::visibility_property(doc, handle));
}
custom_properties.extend(Self::visible_blocks_property(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(),
Expand Down
99 changes: 99 additions & 0 deletions src/app/visibility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -626,6 +635,96 @@ impl OpenCADStudio {
})
}

/// The visibility parameters of a reference to a BricsCAD parametric
/// 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<Property> {
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| {
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(
&parameter,
)),
},
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<Option<document::Document>, &'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(&parameter)) {
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, &parameter.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
Expand Down
Loading