Skip to main content

openbim_ifc_binding_core/
property_edit.rs

1//! Writing property sets and quantities (feature `properties-write`, #123).
2//!
3//! The write side of [`IfcModel::property_sets`]: a property is addressed
4//! by the same object, set name and property name the read side reports,
5//! and its value is the read side's `value`, a typed `IfcValue` (or `$`), a
6//! list of them for an enumerated or list value, or a typed measure for a
7//! quantity. The facade's checked edit (`ifc::apply_property_edits`) does
8//! the work: it plans the whole batch, validates every value against the
9//! declared release and, with the `property-catalog` feature, the release's
10//! PSD/QTO catalog, and commits one transaction, or refuses and changes
11//! nothing.
12//!
13//! An occurrence's inherited value is overridden on the occurrence, never
14//! changed on the shared type set; address the type object to change that.
15//! A set or a property entity the object shares is copied before it
16//! changes.
17//!
18//! Hosts carry an edit in their own idiom. The C tape form, read by
19//! [`PropertyEdit::from_tagged`], is one `LIST`: an `ENUM` `SET` or
20//! `REMOVE`, the object (`REF` or `INTEGER`), the set name and the property
21//! name (`TEXT`), then, for `SET`, the value and an optional set type
22//! (`TEXT` or `NULL`).
23
24use crate::record::{Field, Record, ToRecord};
25use crate::value::Tagged;
26use crate::{BindingError, IfcModel};
27
28/// One edit of a batch.
29#[derive(Debug, Clone, PartialEq)]
30pub struct PropertyEdit {
31    /// The occurrence or type object whose own set is edited.
32    pub object: u64,
33    /// The set's name.
34    pub set: String,
35    /// The property's name.
36    pub name: String,
37    /// What the edit does.
38    pub action: EditAction,
39}
40
41/// What a [`PropertyEdit`] does.
42#[derive(Debug, Clone, PartialEq)]
43pub enum EditAction {
44    /// Write `value`, creating the property and its set when absent.
45    Set {
46        /// The value in the read side's form.
47        value: Tagged,
48        /// `IfcPropertySet` or `IfcElementQuantity` (any case), for a set
49        /// the edit creates and nothing else describes.
50        set_type: Option<String>,
51    },
52    /// Remove the property from the object's own set.
53    Remove,
54}
55
56/// What a committed batch did.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct PropertyEditResult {
59    /// Per edit: the entity holding the property after the batch, `None`
60    /// when the batch leaves none.
61    pub properties: Vec<Option<u64>>,
62    /// Entities created, in commit order.
63    pub created: Vec<u64>,
64    /// Entities removed.
65    pub removed: Vec<u64>,
66}
67
68impl PropertyEdit {
69    /// An edit writing `value`.
70    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    /// An edit removing the property.
83    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    /// Read the C tape form (see the module docs).
93    ///
94    /// # Errors
95    ///
96    /// `invalid-value` for anything else.
97    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    /// Apply `edits` as one checked transaction: every edit, in order, or,
150    /// when any is refused, none, and the model is unchanged.
151    ///
152    /// Refused with `missing-entity` for an object not in the model,
153    /// `wrong-entity-type` for an object that carries no property sets or a
154    /// set type that disagrees with the set, `unsupported-schema` for a
155    /// release other than IFC2X3, IFC4 or IFC4X3, `invalid-value` for a
156    /// value the release does not admit, `template-violation` for one the
157    /// catalog or the property's enumeration does not, `missing-property`
158    /// for a removal of a property the object does not state (also one it
159    /// only inherits), `unsupported` for a value form this writer does not
160    /// write or when the build or host has no random source for the seed
161    /// (as [`crate::relations::new_guid`]), `invalid-model` when the file's records prevent the edit, and
162    /// `feature-disabled` without the `properties-write` feature, or without
163    /// a catalog feature for a `Pset_` or `Qto_` set, and
164    /// `catalog-not-loaded` for such a set in a `property-catalog-runtime`
165    /// build before [`crate::catalog::load`] loaded its release, and
166    /// `invalid-value` for a `GlobalId` derived from a seed the model
167    /// already holds. The message names the refused edit's position. The
168    /// new `GlobalId`s derive from a fresh seed per call.
169    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    /// [`Self::set_properties`]
186    /// with the seed the `GlobalId`s of new sets and relationships derive
187    /// from: a host with entropy of its own (the browser) passes it. The
188    /// seed names the batch: a fixed seed reproduces its `GlobalId`s, also
189    /// after a write/read cycle; reusing it where the model holds one it
190    /// derives is refused (`invalid-value`).
191    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    /// Write one value; [`Self::set_properties`] with one edit, with its
208    /// refusals, `unsupported` for a missing random source among them.
209    /// Returns the entity that holds the property afterwards.
210    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    /// [`Self::set_property`]
231    /// with the seed the `GlobalId`s of new sets and relationships derive
232    /// from: a host with entropy of its own (the browser) passes it. The
233    /// seed names the batch: a fixed seed reproduces its `GlobalId`s, also
234    /// after a write/read cycle; reusing it where the model holds one it
235    /// derives is refused (`invalid-value`).
236    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    /// Remove one property; [`Self::set_properties`] with one edit, with its
259    /// refusals, `unsupported` for a missing random source among them.
260    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    /// [`Self::remove_property`]
279    /// with the seed the `GlobalId`s of new sets and relationships derive
280    /// from: a host with entropy of its own (the browser) passes it. The
281    /// seed names the batch: a fixed seed reproduces its `GlobalId`s, also
282    /// after a write/read cycle; reusing it where the model holds one it
283    /// derives is refused (`invalid-value`).
284    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    /// `error` with the edit's position in front of its detail.
366    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                // The resolver's codes, with the edit's position.
390                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            // The model's own records: an object without the GlobalId or
415            // owner history a new record needs, or a planned transaction
416            // whose preflight found a reference the file keeps.
417            _ => 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}