1use crate::record::{Field, Record, ToRecord};
25use crate::value::Tagged;
26use crate::{BindingError, IfcModel};
27
28#[derive(Debug, Clone, PartialEq)]
30pub struct PropertyEdit {
31 pub object: u64,
33 pub set: String,
35 pub name: String,
37 pub action: EditAction,
39}
40
41#[derive(Debug, Clone, PartialEq)]
43pub enum EditAction {
44 Set {
46 value: Tagged,
48 set_type: Option<String>,
51 },
52 Remove,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct PropertyEditResult {
59 pub properties: Vec<Option<u64>>,
62 pub created: Vec<u64>,
64 pub removed: Vec<u64>,
66}
67
68impl PropertyEdit {
69 pub fn set(object: u64, set: &str, name: &str, value: Tagged) -> Self {
71 Self {
72 object,
73 set: set.to_owned(),
74 name: name.to_owned(),
75 action: EditAction::Set {
76 value,
77 set_type: None,
78 },
79 }
80 }
81
82 pub fn remove(object: u64, set: &str, name: &str) -> Self {
84 Self {
85 object,
86 set: set.to_owned(),
87 name: name.to_owned(),
88 action: EditAction::Remove,
89 }
90 }
91
92 pub fn from_tagged(value: &Tagged) -> Result<Self, BindingError> {
98 let invalid =
99 |detail: &str| BindingError::InvalidValue(format!("a property edit {detail}"));
100 let Tagged::List(fields) = value else {
101 return Err(invalid("is a LIST"));
102 };
103 let text = |index: usize, what: &str| match fields.get(index) {
104 Some(Tagged::Text(text)) => Ok(text.clone()),
105 _ => Err(invalid(&format!(
106 "has its {what} as TEXT at position {index}"
107 ))),
108 };
109 let object = match fields.get(1) {
110 Some(Tagged::Ref(id)) => *id,
111 Some(Tagged::Integer(id)) => u64::try_from(*id)
112 .map_err(|_| BindingError::OutOfRange(format!("object id {id}")))?,
113 _ => return Err(invalid("has its object as REF or INTEGER at position 1")),
114 };
115 let (set, name) = (text(2, "set name")?, text(3, "property name")?);
116 let action = match fields.first() {
117 Some(Tagged::Enum(op))
118 if op.eq_ignore_ascii_case("SET") && (5..=6).contains(&fields.len()) =>
119 {
120 let set_type = match fields.get(5) {
121 None | Some(Tagged::Null) => None,
122 Some(Tagged::Text(text)) => Some(text.clone()),
123 _ => return Err(invalid("has its set type as TEXT or NULL at position 5")),
124 };
125 EditAction::Set {
126 value: fields[4].clone(),
127 set_type,
128 }
129 }
130 Some(Tagged::Enum(op)) if op.eq_ignore_ascii_case("REMOVE") && fields.len() == 4 => {
131 EditAction::Remove
132 }
133 _ => {
134 return Err(invalid(
135 "starts with ENUM SET (5 or 6 fields) or REMOVE (4 fields)",
136 ))
137 }
138 };
139 Ok(Self {
140 object,
141 set,
142 name,
143 action,
144 })
145 }
146}
147
148impl IfcModel {
149 pub fn set_properties(
170 &mut self,
171 edits: Vec<PropertyEdit>,
172 ) -> Result<PropertyEditResult, BindingError> {
173 #[cfg(feature = "properties-write")]
174 {
175 let seed = crate::relations::fresh_seed()?;
176 self.tracked(|this| this.set_properties_seeded(edits, seed))
177 }
178 #[cfg(not(feature = "properties-write"))]
179 {
180 let _ = edits;
181 Err(BindingError::FeatureDisabled("properties-write"))
182 }
183 }
184
185 pub fn set_properties_seeded(
192 &mut self,
193 edits: Vec<PropertyEdit>,
194 seed: u128,
195 ) -> Result<PropertyEditResult, BindingError> {
196 #[cfg(feature = "properties-write")]
197 {
198 self.tracked(|this| write::apply(this, edits, seed))
199 }
200 #[cfg(not(feature = "properties-write"))]
201 {
202 let _ = (edits, seed);
203 Err(BindingError::FeatureDisabled("properties-write"))
204 }
205 }
206
207 pub fn set_property(
211 &mut self,
212 object: u64,
213 set: &str,
214 name: &str,
215 value: Tagged,
216 set_type: Option<String>,
217 ) -> Result<u64, BindingError> {
218 #[cfg(feature = "properties-write")]
219 {
220 let seed = crate::relations::fresh_seed()?;
221 self.tracked(|this| this.set_property_seeded(object, set, name, value, set_type, seed))
222 }
223 #[cfg(not(feature = "properties-write"))]
224 {
225 let _ = (object, set, name, value, set_type);
226 Err(BindingError::FeatureDisabled("properties-write"))
227 }
228 }
229
230 pub fn set_property_seeded(
237 &mut self,
238 object: u64,
239 set: &str,
240 name: &str,
241 value: Tagged,
242 set_type: Option<String>,
243 seed: u128,
244 ) -> Result<u64, BindingError> {
245 let mut edit = PropertyEdit::set(object, set, name, value);
246 if let EditAction::Set { set_type: slot, .. } = &mut edit.action {
247 *slot = set_type;
248 }
249 let result = self.tracked(|this| this.set_properties_seeded(vec![edit], seed))?;
250 result
251 .properties
252 .first()
253 .copied()
254 .flatten()
255 .ok_or_else(|| BindingError::InvalidModel("the edit left no property".into()))
256 }
257
258 pub fn remove_property(
261 &mut self,
262 object: u64,
263 set: &str,
264 name: &str,
265 ) -> Result<(), BindingError> {
266 #[cfg(feature = "properties-write")]
267 {
268 let seed = crate::relations::fresh_seed()?;
269 self.tracked(|this| this.remove_property_seeded(object, set, name, seed))
270 }
271 #[cfg(not(feature = "properties-write"))]
272 {
273 let _ = (object, set, name);
274 Err(BindingError::FeatureDisabled("properties-write"))
275 }
276 }
277
278 pub fn remove_property_seeded(
285 &mut self,
286 object: u64,
287 set: &str,
288 name: &str,
289 seed: u128,
290 ) -> Result<(), BindingError> {
291 self.tracked(|this| {
292 this.set_properties_seeded(vec![PropertyEdit::remove(object, set, name)], seed)
293 })
294 .map(drop)
295 }
296}
297
298impl ToRecord for PropertyEditResult {
299 fn to_record(&self) -> Record {
300 Record::new(
301 "PropertyEditResult",
302 vec![
303 (
304 "properties",
305 Field::List(self.properties.iter().map(|id| Field::id(*id)).collect()),
306 ),
307 ("created", Field::ids(self.created.iter().copied())),
308 ("removed", Field::ids(self.removed.iter().copied())),
309 ],
310 )
311 }
312}
313
314#[cfg(feature = "properties-write")]
315pub(crate) mod write {
316 use ifc::{apply_property_edits, EntityId, PropertyEditError, PropertyEditFailure, SetType};
317
318 use super::{EditAction, PropertyEdit, PropertyEditResult};
319 use crate::properties::read::property_error;
320 use crate::{BindingError, IfcModel};
321
322 pub(super) fn apply(
323 model: &mut IfcModel,
324 edits: Vec<PropertyEdit>,
325 seed: u128,
326 ) -> Result<PropertyEditResult, BindingError> {
327 let edits = edits
328 .into_iter()
329 .enumerate()
330 .map(|(index, edit)| facade_edit(edit).map_err(|error| at(index, error)))
331 .collect::<Result<Vec<_>, _>>()?;
332 let outcome = apply_property_edits(&mut model.inner, &edits, seed).map_err(edit_error)?;
333 let ids = |ids: Vec<EntityId>| ids.into_iter().map(|EntityId(id)| id).collect();
334 Ok(PropertyEditResult {
335 properties: outcome
336 .properties
337 .into_iter()
338 .map(|id| id.map(|EntityId(id)| id))
339 .collect(),
340 created: ids(outcome.created),
341 removed: ids(outcome.removed),
342 })
343 }
344
345 fn facade_edit(edit: PropertyEdit) -> Result<ifc::PropertyEdit, BindingError> {
346 let object = EntityId(edit.object);
347 Ok(match edit.action {
348 EditAction::Set { value, set_type } => {
349 let mut facade =
350 ifc::PropertyEdit::set(object, edit.set, edit.name, value.into_value()?);
351 if let Some(name) = set_type {
352 let set_type = SetType::from_entity(&name).ok_or_else(|| {
353 BindingError::InvalidValue(format!(
354 "set type {name:?} is neither IfcPropertySet nor IfcElementQuantity"
355 ))
356 })?;
357 facade = facade.with_set_type(set_type);
358 }
359 facade
360 }
361 EditAction::Remove => ifc::PropertyEdit::remove(object, edit.set, edit.name),
362 })
363 }
364
365 fn at(index: usize, error: BindingError) -> BindingError {
367 match error {
368 BindingError::InvalidValue(detail) => {
369 BindingError::InvalidValue(format!("edit {index}: {detail}"))
370 }
371 BindingError::OutOfRange(detail) => {
372 BindingError::OutOfRange(format!("edit {index}: {detail}"))
373 }
374 other => other,
375 }
376 }
377
378 pub(crate) fn edit_error(error: PropertyEditError) -> BindingError {
379 use PropertyEditFailure as F;
380 let detail = error.to_string();
381 let position = error.edit.map(|edit| format!("edit {edit}: "));
382 let prefixed = |inner: String| match &position {
383 Some(position) => format!("{position}{inner}"),
384 None => inner,
385 };
386 match error.failure {
387 F::MissingEntity(EntityId(id)) => BindingError::MissingEntity(id),
388 F::Resolve(resolve) => match property_error(resolve) {
389 BindingError::UnsupportedSchema(inner) => {
391 BindingError::UnsupportedSchema(prefixed(inner))
392 }
393 BindingError::WrongEntityType(inner) => {
394 BindingError::WrongEntityType(prefixed(inner))
395 }
396 BindingError::InvalidModel(inner) => BindingError::InvalidModel(prefixed(inner)),
397 BindingError::MissingReference(inner) => {
398 BindingError::MissingReference(prefixed(inner))
399 }
400 BindingError::BudgetExceeded(inner) => {
401 BindingError::BudgetExceeded(prefixed(inner))
402 }
403 BindingError::Unsupported(inner) => BindingError::Unsupported(prefixed(inner)),
404 other => other,
405 },
406 F::Authoring(authoring) => authoring_error(authoring, detail),
407 F::InvalidValue(_) | F::SeedReused { .. } => BindingError::InvalidValue(detail),
408 F::Template(_) => BindingError::TemplateViolation(detail),
409 F::MissingProperty { .. } => BindingError::MissingProperty(detail),
410 F::WrongSetType(_) => BindingError::WrongEntityType(detail),
411 F::Unsupported(_) => BindingError::Unsupported(detail),
412 F::CatalogUnavailable(_) => BindingError::FeatureDisabled("property-catalog"),
413 F::CatalogNotLoaded { .. } => BindingError::CatalogNotLoaded(detail),
414 _ => BindingError::InvalidModel(detail),
418 }
419 }
420
421 fn authoring_error(error: ifc::properties::PropertyError, detail: String) -> BindingError {
422 use ifc::properties::PropertyError as E;
423 match error {
424 E::MissingEntity { id } => BindingError::MissingEntity(id.0),
425 E::NotAQuantity { .. } | E::NotAQuantitySet { .. } => {
426 BindingError::WrongEntityType(detail)
427 }
428 E::MultipleSchemas { .. } | E::UnsupportedSchema { .. } => {
429 BindingError::UnsupportedSchema(detail)
430 }
431 E::MalformedEntitySlots { .. } => BindingError::InvalidModel(detail),
432 _ => BindingError::InvalidValue(detail),
433 }
434 }
435}