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