Salome HOME
c93c694ba09ed3281477273ac0e78475d739e8d8
[modules/shaper.git] / src / Model / Model_Document.h
1 // Copyright (C) 2014-2022  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #ifndef Model_Document_H_
21 #define Model_Document_H_
22
23 #include <Model.h>
24 #include <ModelAPI_Document.h>
25 #include <ModelAPI_Feature.h>
26 #include <ModelAPI_Result.h>
27 #include <ModelAPI_ResultParameter.h>
28
29 #include <TDocStd_Document.hxx>
30 #include <map>
31 #include <set>
32
33 class Handle_Model_Document;
34 class Model_Objects;
35 class ModelAPI_AttributeSelectionList;
36
37 /**\class Model_Document
38  * \ingroup DataModel
39  * \brief Document for internal data structure of any object storage.
40  * Document contains all data that must be stored/retrieved in the file.
41  * Also it provides access to this data: open/save, transactions management etc.
42  */
43 class Model_Document : public ModelAPI_Document
44 {
45  public:
46   //! Returns the kind of the document: "PartSet", "Part", or something else.
47   //! This kind is used for feature buttons enable/disable depending on active document
48   //! (it uses workbench "document" identifier in XML configuration file for this)
49   MODEL_EXPORT virtual const std::string& kind() const {return myKind;}
50
51   //! Loads the OCAF document from the file.
52   //! \param theDirName directory of the loaded file
53   //! \param theFileName a name of the file to load
54   //! \param theThis the common shared pointer to the document to manage with it later
55   //! \returns true if file was loaded successfully
56   MODEL_EXPORT virtual bool load(
57     const char* theDirName, const char* theFileName, DocumentPtr theThis);
58
59   //! Loads the OCAF document from the file into the current document.
60   //! All the features are added after the active feature.
61   //! \param theFileName name of the file to import
62   //! \param theImported list of features imported from the file
63   //! \param theCheckOnly verify the document does not contain unappropriate features
64   //!                     (useful for import to PartSet), but do not import it
65   //! \returns true if file was loaded successfully
66   MODEL_EXPORT virtual bool importPart(const char* theFileName,
67                                    std::list<std::shared_ptr<ModelAPI_Feature> >& theImported,
68                                    bool theCheckOnly = false);
69
70   //! Saves the OCAF document to the file.
71   //! \param theDirName directory where the document will be saved
72   //! \param theFileName a name of the document file to store
73   //! \param theResults the result full file names that were stored by "save"
74   //! \returns true if file was stored successfully
75   MODEL_EXPORT virtual bool save(
76     const char* theDirName, const char* theFileName, std::list<std::string>& theResults);
77
78   //! Export the list of features to the file
79   //! \param theFilename path to save the file
80   //! \param theExportFeatures list of features to export
81   MODEL_EXPORT virtual bool save(const char* theFilename,
82     const std::list<std::shared_ptr<ModelAPI_Feature> >& theExportFeatures) const;
83
84   //! Removes document data
85   //! \param theForever if it is false, document is just hidden
86   //!                   (to keep possibility make it back on Undo/Redo)
87   MODEL_EXPORT virtual void close(const bool theForever = false);
88
89   //! Starts a new operation (opens a transaction)
90   MODEL_EXPORT virtual void startOperation();
91   //! Finishes the previously started operation (closes the transaction)
92   //! \returns true if transaction in this document is not empty and really was performed
93   MODEL_EXPORT virtual bool finishOperation();
94   //! Aborts the operation
95   MODEL_EXPORT virtual void abortOperation();
96   //! Returns true if operation has been started, but not yet finished or aborted
97   MODEL_EXPORT virtual bool isOperation() const;
98   //! Returns true if document was modified (since creation/opening)
99   MODEL_EXPORT virtual bool isModified();
100
101   //! Returns True if there are available Undo-s
102   MODEL_EXPORT virtual bool canUndo();
103   //! Undoes last operation
104   MODEL_EXPORT virtual void undo();
105   //! Returns True if there are available Redo-s
106   MODEL_EXPORT virtual bool canRedo();
107   //! Redoes last operation
108   MODEL_EXPORT virtual void redo();
109   //! Clears undo/redo lists
110   MODEL_EXPORT virtual void clearUndoRedo();
111
112   //! Adds to the document the new feature of the given feature id
113   //! \param theID creates feature and puts it in the document
114   //! \param theMakeCurrent to make current this new feature in this document
115   MODEL_EXPORT virtual FeaturePtr addFeature(std::string theID, const bool theMakeCurrent = true);
116
117   //! Return a list of features, which refers to the feature
118   //! \param theFeature a feature
119   //! \param theRefs a list of reference features
120   //! \param isSendError a flag whether the error message should be send
121   MODEL_EXPORT virtual void refsToFeature(FeaturePtr theFeature,
122                                           std::set<FeaturePtr>& theRefs,
123                                           const bool isSendError = true);
124
125   //! Removes the feature from the document (with result)
126   //! It is necessary to flush REDISPLAY signal manually after this method because
127   //! the method sends it, but for the performance purpose does not flush it
128   //! \param theFeature a removed feature
129   MODEL_EXPORT virtual void removeFeature(FeaturePtr theFeature);
130
131   //! Moves the feature to make it after the given one in the history.
132   MODEL_EXPORT virtual void moveFeature(
133     FeaturePtr theMoved, FeaturePtr theAfterThis, const bool theSplit = false);
134
135   //! Returns the first found object in the group by the object name
136   //! \param theGroupID group that contains an object
137   //! \param theName name of the object to search
138   //! \returns null if such object is not found
139   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Object> objectByName(
140     const std::string& theGroupID, const std::wstring& theName);
141
142   //! Returns the object index in the group. Object must be visible. Otherwise returns -1.
143   //! \param theObject object of this document
144   //! \param theAllowFolder take into account grouping feature by folders
145   //! \returns index started from zero, or -1 if object is invisible or belongs to another document
146   MODEL_EXPORT virtual const int index(std::shared_ptr<ModelAPI_Object> theObject,
147                                        const bool theAllowFolder = false);
148
149   //! Internal sub-document by ID
150   MODEL_EXPORT virtual std::shared_ptr<Model_Document> subDoc(int theDocID);
151
152   ///! Returns the id of the document
153   MODEL_EXPORT virtual const int id() const
154   {
155     return myID;
156   }
157
158   //! Returns the feature in the group by the index (started from zero)
159   //! \param theGroupID group that contains a feature
160   //! \param theIndex zero-based index of feature in the group
161   //! \param theAllowFolder take into account grouping feature by folders
162   MODEL_EXPORT virtual ObjectPtr object(const std::string& theGroupID,
163                                         const int theIndex,
164                                         const bool theAllowFolder = false);
165
166   //! Returns the number of features in the group
167   //! \param theGroupID group of objects
168   //! \param theAllowFolder take into account grouping feature by folders
169   MODEL_EXPORT virtual int size(const std::string& theGroupID, const bool theAllowFolder = false);
170
171   //! Returns the parent object of this child. This may be result or feature, parent of a
172   //! top result. Fast method, that uses internal data structure specifics.
173   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Object> parent(
174     const std::shared_ptr<ModelAPI_Object> theChild);
175
176   //! Returns the feature that is currently edited in this document, normally
177   //! this is the latest created feature
178   //! \param theVisible use visible features only: flag is true for Object Browser functionality
179   //! \returns null if next created feature must be the first
180   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Feature> currentFeature(const bool theVisible);
181
182   //! Sets the current feature: all features below will be disabled, new features
183   //! will be appended after this one.
184   //! \param theCurrent the selected feature as current: below it everything becomes disabled
185   //! \param theVisible use visible features only: flag is true for Object Browser functionality
186   MODEL_EXPORT virtual void setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
187     const bool theVisible);
188
189   //! Makes the current feature one feature upper
190   MODEL_EXPORT virtual void setCurrentFeatureUp();
191
192   //! Returns the number of all features: in the history or not
193   MODEL_EXPORT virtual int numInternalFeatures();
194   //! Returns the feature by zero-based index: features in the history or not
195   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Feature> internalFeature(const int theIndex);
196   //! Performs synchronization of transactions with the module document:
197   //! If some document is not active (by undo of activation) but in memory,
198   //! on activation the transactions must be synchronized because all redo-s performed
199   //! without this participation
200   MODEL_EXPORT virtual void synchronizeTransactions();
201
202   /// Creates construction results
203   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultConstruction> createConstruction(
204       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
205   /// Creates a body results
206   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultBody> createBody(
207       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
208   /// Creates a part results
209   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultPart> createPart(
210       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
211   //! Copies a part result, keeping the reference to origin
212   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultPart> copyPart(
213     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
214     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
215   /// Creates a group result
216   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultGroup> createGroup(
217       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
218   /// Creates a field result
219   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultField> createField(
220       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
221   /// Creates a parameter result
222   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultParameter> createParameter(
223       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
224
225   //! Returns a feature by result (owner of result)
226   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Feature>
227     feature(const std::shared_ptr<ModelAPI_Result>& theResult);
228
229   //! Creates a folder (group of the features in the object browser)
230   //! \param theAddBefore a feature, the folder is added before
231   //!                     (if empty, the folder is added after the last feature)
232   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Folder> addFolder(
233       std::shared_ptr<ModelAPI_Feature> theAddBefore = std::shared_ptr<ModelAPI_Feature>());
234   //! Removes the folder from the document (all features in the folder will be kept).
235   MODEL_EXPORT virtual void removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder);
236   //! Search a folder above the list of features applicable to store them
237   //! (it means the list of features stored in the folder should be consequential)
238   //! \return Empty pointer if there is no applicable folder
239   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Folder> findFolderAbove(
240       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures);
241   //! Search a folder below the list of features applicable to store them
242   //! (it means the list of features stored in the folder should be consequential)
243   //! \return Empty pointer if there is no applicable folder
244   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Folder> findFolderBelow(
245       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures);
246   //! Search a folder containing the given feature.
247   //! Additionally calculates a zero-based index of the feature in this folder.
248   //! \param theFeature feature to search
249   //! \param theIndexInFolder zero-based index in the folder or -1 if the feature is top-level.
250   //! \return the folder containing the feature or empty pointer if the feature is top-level.
251   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Folder> findContainingFolder(
252       const std::shared_ptr<ModelAPI_Feature>& theFeature,
253       int& theIndexInFolder);
254   //! Add a list of features to the folder. The correctness of the adding is not performed
255   //! (such checks have been done in corresponding find.. method).
256   //! \return \c true if the movement is successful
257   MODEL_EXPORT virtual bool moveToFolder(
258       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
259       const std::shared_ptr<ModelAPI_Folder>& theFolder);
260   //! Remove features from the folder
261   //! \param theFeatures list of features to be removed
262   //! \param theBefore   extract features before the folder (this parameter is applicable only
263   //!                    when all features in the folder are taking out,
264   //!                    in other cases the direction is taken automatically)
265   //! \return \c true if the features have been moved out
266   MODEL_EXPORT virtual bool removeFromFolder(
267       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
268       const bool theBefore = true);
269
270   ///! Returns true if parametric updater need to execute feature on recomputation
271   ///! On abort, undo or redo it is not necessary: results in document are updated automatically
272   bool executeFeatures() {return myExecuteFeatures;}
273
274   ///! On abort, undo or redo it is not necessary: results in document are updated automatically
275   void setExecuteFeatures(const bool theFlag);
276
277   //! Registers the name of the shape for the topological naming needs
278   void addNamingName(const TDF_Label theLabel, std::wstring theName);
279   //! Updates the name of some object
280   void changeNamingName(std::wstring theOldName, const std::wstring theNewName,
281     const TDF_Label& theLabel);
282   //! Returns the label, keeper of the name  for the topological naming needs
283   TDF_Label findNamingName(std::wstring theName, ResultPtr theContext);
284   //! Returns the number of the name in the history relatively to the given object (by label).
285   //! Start from 1 (this object).
286   int numberOfNameInHistory(const ObjectPtr& theNameObject, const TDF_Label& theStartFrom);
287   //! Returns the result by name of the result (names of results must be unique, used for naming
288   //! selection by name.
289   ResultPtr findByName(std::wstring& theName,
290                        std::wstring& theSubShapeName,
291                        bool& theUniqueContext);
292
293   ///! Returns all features of the document including the hidden features which are not in
294   ///! history. Not very fast method, for calling once, not in big cycles.
295   MODEL_EXPORT virtual std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures();
296
297   //! Returns all objects of the document including the hidden features which are not in
298   //! history. Not very fast method, for calling once, not in big cycles.
299   MODEL_EXPORT virtual std::list<std::shared_ptr<ModelAPI_Object> > allObjects();
300
301   /// Returns the global identifier of the current transaction (needed for the update algo)
302   MODEL_EXPORT virtual int transactionID();
303   /// Increases the transaction ID
304   MODEL_EXPORT virtual void incrementTransactionID();
305
306   /// Returns true if document is opened and valid
307   MODEL_EXPORT virtual bool isOpened();
308
309   /// Returns the last feature in the document (even not visible or disabled)
310   /// \returns null if there is no features
311   FeaturePtr lastFeature();
312
313   /// Returns the feature that produced the given face of the given result.
314   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Feature> producedByFeature(
315     std::shared_ptr<ModelAPI_Result> theResult,
316     const std::shared_ptr<GeomAPI_Shape>& theShape);
317
318   /// Returns true if theLater is in history of features creation later than theCurrent
319   MODEL_EXPORT virtual bool isLater(FeaturePtr theLater, FeaturePtr theCurrent) const;
320
321   /// Just removes all features without touching the document data (to be able undo)
322   MODEL_EXPORT virtual void eraseAllFeatures();
323
324   /// Returns the next (from the history point of view) feature, any: invisible or disabled
325   /// \param theCurrent previous to the resulting feature
326   /// \param theReverse if it is true, iterates in reversed order (next becomes previous)
327   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Feature> nextFeature(
328     std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theReverse = false) const;
329
330   //! Erases the document structure.
331   ~Model_Document();
332
333  protected:
334   //! Returns (creates if needed) the general label
335   TDF_Label generalLabel() const;
336
337   //! Creates new document with binary file format
338   Model_Document(const int theID, const std::string theKind);
339
340   //! Returns the internal OCCT document of this interface
341   Handle_TDocStd_Document document()
342   {
343     return myDoc;
344   }
345
346   //! performs compactification of all nested operations into one
347   //! \returns true if resulting transaction is not empty and can be undone
348   void compactNested();
349
350   //! Returns all loaded sub documents
351   const std::set<int> subDocuments() const;
352
353   //! The implementation of undo: with or without recursive calls in the sub-documents
354   void undoInternal(const bool theWithSubs, const bool theSynchronize);
355
356   //! Stores the Id of the current operation (normally is called for the root document)
357   void operationId(const std::string& theId);
358
359   //! Returns the list of Ids of the operations that can be undone (called for the root document)
360   std::list<std::string> undoList() const;
361
362   //! Returns the list of Ids of the operations that can be redone (called for the root document)
363   std::list<std::string> redoList() const;
364
365   //! Internally makes document know that feature was removed or added in history after creation
366   virtual void updateHistory(const std::shared_ptr<ModelAPI_Object> theObject);
367   //! Internally makes document know that feature was removed or added in history after creation
368   virtual void updateHistory(const std::string theGroup);
369
370   //! Returns true if the document is root module document
371   bool isRoot() const;
372
373   //! Sets shared pointer to this
374   void setThis(DocumentPtr theDoc);
375
376   //! Returns the objects manager
377   Model_Objects* objects() {return myObjs;}
378
379   ///! Informs the document that it becomes active and some actions must be performed
380   virtual void setActive(const bool theFlag);
381   //! Returns true if this document is currently active
382   virtual bool isActive() const;
383
384   //! Returns the selection attribute that is used
385   //! for calculation of selection externally from the document
386   std::shared_ptr<ModelAPI_AttributeSelectionList> selectionInPartFeature();
387
388   /// Stores in the document boolean flags: states of the nodes in the object browser.
389   /// Normally is called outside of the transaction, just before "save".
390   virtual void storeNodesState(const std::list<bool>& theStates);
391
392   /// Returns the stored nodes states. Normally it is called just after "open".
393   /// Appends the values to theStates list.
394   virtual void restoreNodesState(std::list<bool>& theStates) const;
395
396   /// Label that contains structures for selection of constructions of another document
397   TDF_Label extConstructionsLabel() const;
398
399   /// searches in this document feature that contains this label
400   FeaturePtr featureByLab(const TDF_Label& theLab);
401   /// searches in this document result that contains this label
402   ResultPtr resultByLab(const TDF_Label& theLab);
403
404   /// returns true if theThis is later in the features tree and dependencies than theOther
405   bool isLaterByDep(FeaturePtr theThis, FeaturePtr theOther);
406
407   /// appends the latest transaction to the previous one (used for AutoUpdate enabling transaction)
408   void appendTransactionToPrevious();
409
410   /// Sets the automatic recomputation flag: true means enabled
411   void setAutoRecomutationState(const bool theState);
412   /// Returns the current automatic recomputation flag: true means enabled
413   bool autoRecomutationState() const;
414
415   friend class Model_Application;
416   friend class Model_Session;
417   friend class Model_Update;
418   friend class Model_AttributeReference;
419   friend class Model_AttributeRefAttr;
420   friend class Model_AttributeRefList;
421   friend class Model_AttributeRefAttrList;
422   friend class Model_AttributeSelection;
423   friend class Model_AttributeSelectionList;
424   friend class Model_ResultPart;
425   friend class Model_ResultBody;
426   friend class Model_ResultConstruction;
427   friend class Model_SelectionNaming;
428   friend class Model_BodyBuilder;
429   friend class DFBrowser;
430
431  private:
432   int myID;  ///< identifier of the document in the application
433   std::string myKind;  ///< kind of the document in the application
434   Handle_TDocStd_Document myDoc;  ///< OCAF document
435
436   Model_Objects *myObjs; ///< data manager of this document
437
438   //! counter value of transaction on the last "save" call, used for "IsModified" method
439   int myTransactionSave;
440   //! number of nested transactions performed (list because may be nested inside of nested)
441   //! the list is empty if not nested transaction is performed
442   std::list<int> myNestedNum;
443
444   //! Information related to the every user-transaction
445   struct Transaction {
446     int myOCAFNum; ///< number of OCAF transactions related to each "this" transaction, may be 0
447     std::string myId; ///< user-identifier string of transaction
448     //! default constructor with default Id
449     Transaction(): myOCAFNum(0), myId("") {}
450   };
451
452   //! transaction indexes (related to myTransactionsAfterSave) and info about the real transactions
453   //! in myDocument connected to this operation (may be zero for empty transaction)
454   std::list<Transaction> myTransactions;
455   //! list of info about transactions undone (first is oldest undone)
456   std::list<Transaction> myRedos;
457
458   //! Optimization for finding the shape-label by topological naming names
459   //! The name -> list of labels where this name is appeared (the last created name is last here)
460   std::map<std::wstring, std::list<TDF_Label> > myNamingNames;
461   //! If it is true, features are not executed on update (on abort, undo, redo)
462   bool myExecuteFeatures;
463
464   bool myIsActive; ///< flag that stores the active/not active state
465
466   //! The selection feature, if needed
467   FeaturePtr mySelectionFeature;
468
469   bool myIsSetCurrentFeature; ///< flag that my current feature is changed right now (recursion)
470 };
471
472 #endif