Salome HOME
023770a4d0864ea532abe78a84989b856fcca366
[modules/shaper.git] / src / Model / Model_Document.h
1 // Copyright (C) 2014-2019  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 theCheckBefore verify the document does not contain unappropriate features
64   //!                       (useful for import to PartSet)
65   //! \returns true if file was loaded successfully
66   MODEL_EXPORT virtual bool import(const char* theFileName,
67                                    std::list<std::shared_ptr<ModelAPI_Feature> >& theImported,
68                                    bool theCheckBefore = 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
110   //! Adds to the document the new feature of the given feature id
111   //! \param theID creates feature and puts it in the document
112   //! \param theMakeCurrent to make current this new feature in this document
113   MODEL_EXPORT virtual FeaturePtr addFeature(std::string theID, const bool theMakeCurrent = true);
114
115   //! Return a list of features, which refers to the feature
116   //! \param theFeature a feature
117   //! \param theRefs a list of reference features
118   //! \param isSendError a flag whether the error message should be send
119   MODEL_EXPORT virtual void refsToFeature(FeaturePtr theFeature,
120                                           std::set<FeaturePtr>& theRefs,
121                                           const bool isSendError = true);
122
123   //! Removes the feature from the document (with result)
124   //! It is necessary to flush REDISPLAY signal manually after this method because
125   //! the method sends it, but for the performance purpose does not flush it
126   //! \param theFeature a removed feature
127   MODEL_EXPORT virtual void removeFeature(FeaturePtr theFeature);
128
129   //! Moves the feature to make it after the given one in the history.
130   MODEL_EXPORT virtual void moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis);
131
132   //! Returns the first found object in the group by the object name
133   //! \param theGroupID group that contains an object
134   //! \param theName name of the object to search
135   //! \returns null if such object is not found
136   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Object> objectByName(
137     const std::string& theGroupID, const std::string& theName);
138
139   //! Returns the object index in the group. Object must be visible. Otherwise returns -1.
140   //! \param theObject object of this document
141   //! \param theAllowFolder take into account grouping feature by folders
142   //! \returns index started from zero, or -1 if object is invisible or belongs to another document
143   MODEL_EXPORT virtual const int index(std::shared_ptr<ModelAPI_Object> theObject,
144                                        const bool theAllowFolder = false);
145
146   //! Internal sub-document by ID
147   MODEL_EXPORT virtual std::shared_ptr<Model_Document> subDoc(int theDocID);
148
149   ///! Returns the id of the document
150   MODEL_EXPORT virtual const int id() const
151   {
152     return myID;
153   }
154
155   //! Returns the feature in the group by the index (started from zero)
156   //! \param theGroupID group that contains a feature
157   //! \param theIndex zero-based index of feature in the group
158   //! \param theAllowFolder take into account grouping feature by folders
159   MODEL_EXPORT virtual ObjectPtr object(const std::string& theGroupID,
160                                         const int theIndex,
161                                         const bool theAllowFolder = false);
162
163   //! Returns the number of features in the group
164   //! \param theGroupID group of objects
165   //! \param theAllowFolder take into account grouping feature by folders
166   MODEL_EXPORT virtual int size(const std::string& theGroupID, const bool theAllowFolder = false);
167
168   //! Returns the parent object of this child. This may be result or feature, parent of a
169   //! top result. Fast method, that uses internal data structure specifics.
170   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Object> parent(
171     const std::shared_ptr<ModelAPI_Object> theChild);
172
173   //! Returns the feature that is currently edited in this document, normally
174   //! this is the latest created feature
175   //! \param theVisible use visible features only: flag is true for Object Browser functionality
176   //! \returns null if next created feature must be the first
177   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Feature> currentFeature(const bool theVisible);
178
179   //! Sets the current feature: all features below will be disabled, new features
180   //! will be appended after this one.
181   //! \param theCurrent the selected feature as current: below it everything becomes disabled
182   //! \param theVisible use visible features only: flag is true for Object Browser functionality
183   MODEL_EXPORT virtual void setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
184     const bool theVisible);
185
186   //! Makes the current feature one feature upper
187   MODEL_EXPORT virtual void setCurrentFeatureUp();
188
189   //! Returns the number of all features: in the history or not
190   MODEL_EXPORT virtual int numInternalFeatures();
191   //! Returns the feature by zero-based index: features in the history or not
192   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Feature> internalFeature(const int theIndex);
193   //! Performs synchronization of transactions with the module document:
194   //! If some document is not active (by undo of activation) but in memory,
195   //! on activation the transactions must be synchronized because all redo-s performed
196   //! without this participation
197   MODEL_EXPORT virtual void synchronizeTransactions();
198
199   /// Creates construction results
200   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultConstruction> createConstruction(
201       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
202   /// Creates a body results
203   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultBody> createBody(
204       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
205   /// Creates a part results
206   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultPart> createPart(
207       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
208   //! Copies a part result, keeping the reference to origin
209   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultPart> copyPart(
210     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
211     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
212   /// Creates a group result
213   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultGroup> createGroup(
214       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
215   /// Creates a field result
216   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultField> createField(
217       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
218   /// Creates a parameter result
219   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_ResultParameter> createParameter(
220       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex = 0);
221
222   //! Returns a feature by result (owner of result)
223   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Feature>
224     feature(const std::shared_ptr<ModelAPI_Result>& theResult);
225
226   //! Creates a folder (group of the features in the object browser)
227   //! \param theAddBefore a feature, the folder is added before
228   //!                     (if empty, the folder is added after the last feature)
229   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Folder> addFolder(
230       std::shared_ptr<ModelAPI_Feature> theAddBefore = std::shared_ptr<ModelAPI_Feature>());
231   //! Removes the folder from the document (all features in the folder will be kept).
232   MODEL_EXPORT virtual void removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder);
233   //! Search a folder above the list of features applicable to store them
234   //! (it means the list of features stored in the folder should be consequential)
235   //! \return Empty pointer if there is no applicable folder
236   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Folder> findFolderAbove(
237       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures);
238   //! Search a folder below the list of features applicable to store them
239   //! (it means the list of features stored in the folder should be consequential)
240   //! \return Empty pointer if there is no applicable folder
241   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Folder> findFolderBelow(
242       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures);
243   //! Search a folder containing the given feature.
244   //! Additionally calculates a zero-based index of the feature in this folder.
245   //! \param theFeature feature to search
246   //! \param theIndexInFolder zero-based index in the folder or -1 if the feature is top-level.
247   //! \return the folder containing the feature or empty pointer if the feature is top-level.
248   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Folder> findContainingFolder(
249       const std::shared_ptr<ModelAPI_Feature>& theFeature,
250       int& theIndexInFolder);
251   //! Add a list of features to the folder. The correctness of the adding is not performed
252   //! (such checks have been done in corresponding find.. method).
253   //! \return \c true if the movement is successful
254   MODEL_EXPORT virtual bool moveToFolder(
255       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
256       const std::shared_ptr<ModelAPI_Folder>& theFolder);
257   //! Remove features from the folder
258   //! \param theFeatures list of features to be removed
259   //! \param theBefore   extract features before the folder (this parameter is applicable only
260   //!                    when all features in the folder are taking out,
261   //!                    in other cases the direction is taken automatically)
262   //! \return \c true if the features have been moved out
263   MODEL_EXPORT virtual bool removeFromFolder(
264       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
265       const bool theBefore = true);
266
267   ///! Returns true if parametric updater need to execute feature on recomputation
268   ///! On abort, undo or redo it is not necessary: results in document are updated automatically
269   bool executeFeatures() {return myExecuteFeatures;}
270
271   ///! On abort, undo or redo it is not necessary: results in document are updated automatically
272   void setExecuteFeatures(const bool theFlag);
273
274   //! Registers the name of the shape for the topological naming needs
275   void addNamingName(const TDF_Label theLabel, std::string theName);
276   //! Updates the name of some object
277   void changeNamingName(std::string theOldName, const std::string theNewName,
278     const TDF_Label& theLabel);
279   //! Returns the label, keeper of the name  for the topological naming needs
280   TDF_Label findNamingName(std::string theName, ResultPtr theContext);
281   //! Returns the number of the name in the history relatively to the given object (by label).
282   //! Start from 1 (this object).
283   int numberOfNameInHistory(const ObjectPtr& theNameObject, const TDF_Label& theStartFrom);
284   //! Returns the result by name of the result (names of results must be unique, used for naming
285   //! selection by name.
286   ResultPtr findByName(std::string& theName, std::string& theSubShapeName, bool& theUniqueContext);
287
288   ///! Returns all features of the document including the hidden features which are not in
289   ///! history. Not very fast method, for calling once, not in big cycles.
290   MODEL_EXPORT virtual std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures();
291
292   //! Returns all objects of the document including the hidden features which are not in
293   //! history. Not very fast method, for calling once, not in big cycles.
294   MODEL_EXPORT virtual std::list<std::shared_ptr<ModelAPI_Object> > allObjects();
295
296   /// Returns the global identifier of the current transaction (needed for the update algo)
297   MODEL_EXPORT virtual int transactionID();
298   /// Increases the transaction ID
299   MODEL_EXPORT virtual void incrementTransactionID();
300
301   /// Returns true if document is opened and valid
302   MODEL_EXPORT virtual bool isOpened();
303
304   /// Returns the last feature in the document (even not visible or disabled)
305   /// \returns null if there is no features
306   FeaturePtr lastFeature();
307
308   /// Returns the feature that produced the given face of the given result.
309   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Feature> producedByFeature(
310     std::shared_ptr<ModelAPI_Result> theResult,
311     const std::shared_ptr<GeomAPI_Shape>& theShape);
312
313   /// Returns true if theLater is in history of features creation later than theCurrent
314   MODEL_EXPORT virtual bool isLater(FeaturePtr theLater, FeaturePtr theCurrent) const;
315
316   /// Just removes all features without touching the document data (to be able undo)
317   MODEL_EXPORT virtual void eraseAllFeatures();
318
319   /// Returns the next (from the history point of view) feature, any: invisible or disabled
320   /// \param theCurrent previous to the resulting feature
321   /// \param theReverse if it is true, iterates in reversed order (next becomes previous)
322   MODEL_EXPORT virtual std::shared_ptr<ModelAPI_Feature> nextFeature(
323     std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theReverse = false) const;
324
325  protected:
326   //! Returns (creates if needed) the general label
327   TDF_Label generalLabel() const;
328
329   //! Creates new document with binary file format
330   Model_Document(const int theID, const std::string theKind);
331
332   //! Returns the internal OCCT document of this interface
333   Handle_TDocStd_Document document()
334   {
335     return myDoc;
336   }
337
338   //! performs compactification of all nested operations into one
339   //! \returns true if resulting transaction is not empty and can be undone
340   void compactNested();
341
342   //! Returns all loaded sub documents
343   const std::set<int> subDocuments() const;
344
345   //! The implementation of undo: with or without recursive calls in the sub-documents
346   void undoInternal(const bool theWithSubs, const bool theSynchronize);
347
348   //! Stores the Id of the current operation (normally is called for the root document)
349   void operationId(const std::string& theId);
350
351   //! Returns the list of Ids of the operations that can be undone (called for the root document)
352   std::list<std::string> undoList() const;
353
354   //! Returns the list of Ids of the operations that can be redone (called for the root document)
355   std::list<std::string> redoList() const;
356
357   //! Internally makes document know that feature was removed or added in history after creation
358   virtual void updateHistory(const std::shared_ptr<ModelAPI_Object> theObject);
359   //! Internally makes document know that feature was removed or added in history after creation
360   virtual void updateHistory(const std::string theGroup);
361
362   //! Returns true if the document is root module document
363   bool isRoot() const;
364
365   //! Sets shared pointer to this
366   void setThis(DocumentPtr theDoc);
367
368   //! Returns the objects manager
369   Model_Objects* objects() {return myObjs;}
370
371   ///! Informs the document that it becomes active and some actions must be performed
372   virtual void setActive(const bool theFlag);
373   //! Returns true if this document is currently active
374   virtual bool isActive() const;
375
376   //! Returns the selection attribute that is used
377   //! for calculation of selection externally from the document
378   std::shared_ptr<ModelAPI_AttributeSelectionList> selectionInPartFeature();
379
380   /// Stores in the document boolean flags: states of the nodes in the object browser.
381   /// Normally is called outside of the transaction, just before "save".
382   virtual void storeNodesState(const std::list<bool>& theStates);
383
384   /// Returns the stored nodes states. Normally it is called just after "open".
385   /// Appends the values to theStates list.
386   virtual void restoreNodesState(std::list<bool>& theStates) const;
387
388   /// Label that contains structures for selection of constructions of another document
389   TDF_Label extConstructionsLabel() const;
390
391   /// searches in this document feature that contains this label
392   FeaturePtr featureByLab(const TDF_Label& theLab);
393   /// searches in this document result that contains this label
394   ResultPtr resultByLab(const TDF_Label& theLab);
395
396   /// returns true if theThis is later in the features tree and dependencies than theOther
397   bool isLaterByDep(FeaturePtr theThis, FeaturePtr theOther);
398
399   /// appends the latest transaction to the previous one (used for AutoUpdate enabling transaction)
400   void appendTransactionToPrevious();
401
402   /// Sets the automatic recomputation flag: true means enabled
403   void setAutoRecomutationState(const bool theState);
404   /// Returns the current automatic recomputation flag: true means enabled
405   bool autoRecomutationState() const;
406
407   friend class Model_Application;
408   friend class Model_Session;
409   friend class Model_Update;
410   friend class Model_AttributeReference;
411   friend class Model_AttributeRefAttr;
412   friend class Model_AttributeRefList;
413   friend class Model_AttributeRefAttrList;
414   friend class Model_AttributeSelection;
415   friend class Model_AttributeSelectionList;
416   friend class Model_ResultPart;
417   friend class Model_ResultBody;
418   friend class Model_ResultConstruction;
419   friend class Model_SelectionNaming;
420   friend class Model_BodyBuilder;
421   friend class DFBrowser;
422
423  private:
424   int myID;  ///< identifier of the document in the application
425   std::string myKind;  ///< kind of the document in the application
426   Handle_TDocStd_Document myDoc;  ///< OCAF document
427
428   Model_Objects *myObjs; ///< data manager of this document
429
430   //! counter value of transaction on the last "save" call, used for "IsModified" method
431   int myTransactionSave;
432   //! number of nested transactions performed (list because may be nested inside of nested)
433   //! the list is empty if not nested transaction is performed
434   std::list<int> myNestedNum;
435
436   //! Information related to the every user-transaction
437   struct Transaction {
438     int myOCAFNum; ///< number of OCAF transactions related to each "this" transaction, may be 0
439     std::string myId; ///< user-identifier string of transaction
440     //! default constructor with default Id
441     Transaction(): myOCAFNum(0), myId("") {}
442   };
443
444   //! transaction indexes (related to myTransactionsAfterSave) and info about the real transactions
445   //! in myDocument connected to this operation (may be zero for empty transaction)
446   std::list<Transaction> myTransactions;
447   //! list of info about transactions undone (first is oldest undone)
448   std::list<Transaction> myRedos;
449
450   //! Optimization for finding the shape-label by topological naming names
451   //! The name -> list of labels where this name is appeared (the last created name is last here)
452   std::map<std::string, std::list<TDF_Label> > myNamingNames;
453   //! If it is true, features are not executed on update (on abort, undo, redo)
454   bool myExecuteFeatures;
455
456   bool myIsActive; ///< flag that stores the active/not active state
457
458   //! The selection feature, if needed
459   FeaturePtr mySelectionFeature;
460
461   bool myIsSetCurrentFeature; ///< flag that my current feature is changed right now (recursion)
462 };
463
464 #endif