Skip to main content

openbim_ifc_binding_core/authoring/
removal.rs

1//! Removing a product with what it solely owns, and purging what nothing
2//! uses (#478, feature `author`); removing a shape representation the same
3//! way (#481).
4//!
5//! [`IfcModel::remove_product`] and [`IfcModel::purge`] run the facade's
6//! `AuthorOp::RemoveProduct` and `AuthorOp::Purge` as a batch of one, or,
7//! with `dry_run`, only stage it: the report is the same and the model is
8//! unchanged. Every host returns the [`RemovalReport`] as its record.
9//!
10//! Refusals: `missing-entity` for no such product; `wrong-entity-type` for
11//! one that is neither an `IfcProduct` nor an `IfcTypeObject`;
12//! `still-referenced` for a placement other placements are relative to
13//! (unless re-based), a type object that still types objects (unless
14//! they are untyped), or an entity that stays and still needs something
15//! removed; `unsupported` for a placement that cannot be re-based;
16//! `unsupported-schema` for a purge class the release does not declare;
17//! `feature-disabled` without the `author` feature.
18
19use crate::record::{Field, Record, ToRecord};
20use crate::{BindingError, IfcModel};
21
22/// What [`IfcModel::remove_product`] does where it would otherwise refuse.
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
24#[non_exhaustive]
25pub struct RemoveProductOptions {
26    /// Re-base placements relative to a removed placement onto its
27    /// parent, composing the transforms, instead of refusing.
28    pub rebase_placements: bool,
29    /// Remove a type object's typing relationship, leaving its occurrences
30    /// untyped, instead of refusing.
31    pub untype_occurrences: bool,
32    /// Report what would be removed and kept without changing the model.
33    pub dry_run: bool,
34}
35
36impl RemoveProductOptions {
37    /// Every option off.
38    #[must_use]
39    pub const fn new() -> Self {
40        Self {
41            rebase_placements: false,
42            untype_occurrences: false,
43            dry_run: false,
44        }
45    }
46}
47
48/// What [`IfcModel::purge`] removes.
49#[derive(Debug, Clone, Default, PartialEq, Eq)]
50#[non_exhaustive]
51pub struct PurgeOptions {
52    /// Entity types to purge, subtypes included; empty for every resource
53    /// entity no `IfcRoot` reaches.
54    pub classes: Vec<String>,
55    /// Also purge unreferenced `IfcRoot`s of `classes`.
56    pub include_roots: bool,
57    /// Also purge an unreferenced owner history with its actors (and,
58    /// without classes, unused representation contexts).
59    pub include_owner_history: bool,
60    /// Report what would be purged without changing the model.
61    pub dry_run: bool,
62}
63
64impl PurgeOptions {
65    /// The default purge, applied.
66    #[must_use]
67    pub fn new() -> Self {
68        Self::default()
69    }
70}
71
72/// One removed entity.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct RemovedEntity {
75    /// Its id.
76    pub id: u64,
77    /// Its type, upper case as the file writes it.
78    pub type_name: String,
79}
80
81/// One entity the removal reached and kept.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct KeptEntity {
84    /// Its id.
85    pub id: u64,
86    /// Its type, upper case.
87    pub type_name: String,
88    /// Why it stays: `shared` (`users` still need it), `related-object`
89    /// (a type, container, filling: an object of its own), `definition`
90    /// (a material, classification reference, unit, context or owner
91    /// history, which only a purge removes) or `protected` (a purge
92    /// skipped it: an `IfcRoot` or the owner history, unless asked).
93    pub reason: String,
94    /// For `shared`, the entities that stay and use it.
95    pub users: Vec<u64>,
96}
97
98/// What a removal or purge did, or, for a dry run, would do.
99#[derive(Debug, Clone, Default, PartialEq, Eq)]
100pub struct RemovalReport {
101    /// Every entity removed, in id order.
102    pub removed: Vec<RemovedEntity>,
103    /// Entities reached and kept, with the reason.
104    pub kept: Vec<KeptEntity>,
105    /// Relationships and layer assignments that lost a removed member and
106    /// stay.
107    pub detached: Vec<u64>,
108    /// Placements re-based onto a kept ancestor.
109    pub rebased: Vec<u64>,
110    /// Whether the model was changed: `false` for a dry run.
111    pub applied: bool,
112}
113
114impl ToRecord for RemovedEntity {
115    fn to_record(&self) -> Record {
116        Record::new(
117            "RemovedEntity",
118            vec![
119                ("id", Field::Id(self.id)),
120                ("type_name", Field::Text(self.type_name.clone())),
121            ],
122        )
123    }
124}
125
126impl ToRecord for KeptEntity {
127    fn to_record(&self) -> Record {
128        Record::new(
129            "KeptEntity",
130            vec![
131                ("id", Field::Id(self.id)),
132                ("type_name", Field::Text(self.type_name.clone())),
133                ("reason", Field::Text(self.reason.clone())),
134                ("users", Field::ids(self.users.iter().copied())),
135            ],
136        )
137    }
138}
139
140impl ToRecord for RemovalReport {
141    fn to_record(&self) -> Record {
142        Record::new(
143            "RemovalReport",
144            vec![
145                ("removed", Field::records(&self.removed)),
146                ("kept", Field::records(&self.kept)),
147                ("detached", Field::ids(self.detached.iter().copied())),
148                ("rebased", Field::ids(self.rebased.iter().copied())),
149                ("applied", Field::Bool(self.applied)),
150            ],
151        )
152    }
153}
154
155impl IfcModel {
156    /// Remove product (or type object) `id` with everything it solely
157    /// owns, keeping what is shared, as one checked transaction; with
158    /// `options.dry_run`, only report. See the module docs for the
159    /// refusals.
160    pub fn remove_product(
161        &mut self,
162        id: u64,
163        options: RemoveProductOptions,
164    ) -> Result<RemovalReport, BindingError> {
165        #[cfg(feature = "author")]
166        {
167            let op = ifc::AuthorOp::RemoveProduct {
168                product: ifc::EntityId(id),
169                options: ifc::RemoveProductOptions::new()
170                    .rebase_placements(options.rebase_placements)
171                    .untype_occurrences(options.untype_occurrences),
172            };
173            self.removal(op, options.dry_run)
174        }
175        #[cfg(not(feature = "author"))]
176        {
177            let _ = (id, options);
178            Err(BindingError::FeatureDisabled("author"))
179        }
180    }
181
182    /// Purge unreferenced entities as one checked transaction; with
183    /// `options.dry_run`, only report. See the module docs.
184    pub fn purge(&mut self, options: PurgeOptions) -> Result<RemovalReport, BindingError> {
185        #[cfg(feature = "author")]
186        {
187            let op = ifc::AuthorOp::Purge(
188                ifc::PurgeOptions::new()
189                    .classes(options.classes)
190                    .include_roots(options.include_roots)
191                    .include_owner_history(options.include_owner_history),
192            );
193            self.removal(op, options.dry_run)
194        }
195        #[cfg(not(feature = "author"))]
196        {
197            let _ = options;
198            Err(BindingError::FeatureDisabled("author"))
199        }
200    }
201
202    /// Remove shape representation `id` with what only it uses (#481):
203    /// taken off its product definition shape (which goes when left
204    /// empty), representation map or shape aspects first, then removed by
205    /// the cascade of [`Self::remove_product`]. With `dry_run`, only
206    /// report. `still-referenced` for a representation map an
207    /// `IfcMappedItem` still maps; `wrong-entity-type` for an entity that
208    /// is not an `IfcShapeModel`.
209    pub fn remove_representation(
210        &mut self,
211        id: u64,
212        dry_run: bool,
213    ) -> Result<RemovalReport, BindingError> {
214        #[cfg(feature = "author")]
215        {
216            let op = ifc::AuthorOp::RemoveRepresentation {
217                representation: ifc::EntityId(id),
218            };
219            self.removal(op, dry_run)
220        }
221        #[cfg(not(feature = "author"))]
222        {
223            let _ = (id, dry_run);
224            Err(BindingError::FeatureDisabled("author"))
225        }
226    }
227
228    #[cfg(feature = "author")]
229    fn removal(&mut self, op: ifc::AuthorOp, dry_run: bool) -> Result<RemovalReport, BindingError> {
230        // No removal creates an `IfcRoot`, so no `GlobalId` is drawn from
231        // the seed.
232        const SEED: u128 = 0;
233        let schema = self.declared_schema()?;
234        let ops = [op];
235        let reports = if dry_run {
236            ifc::stage_authoring(&self.inner, schema, &ops, SEED)
237                .map_err(super::convert::error)?
238                .reports
239        } else {
240            self.tracked(|this| ifc::apply_authoring(&mut this.inner, schema, &ops, SEED))
241                .map_err(super::convert::error)?
242                .reports
243        };
244        let report = reports
245            .into_iter()
246            .next()
247            .flatten()
248            .ok_or_else(|| BindingError::InvalidModel("the removal made no report".into()))?;
249        Ok(RemovalReport {
250            removed: report
251                .removed
252                .into_iter()
253                .map(|entity| RemovedEntity {
254                    id: entity.id.0,
255                    type_name: entity.type_name,
256                })
257                .collect(),
258            kept: report
259                .kept
260                .into_iter()
261                .map(|entity| KeptEntity {
262                    id: entity.id.0,
263                    type_name: entity.type_name,
264                    reason: entity.reason.as_str().to_owned(),
265                    users: entity.users.into_iter().map(|user| user.0).collect(),
266                })
267                .collect(),
268            detached: report.detached.into_iter().map(|id| id.0).collect(),
269            rebased: report.rebased.into_iter().map(|id| id.0).collect(),
270            applied: !dry_run,
271        })
272    }
273}