Salome HOME
Merge branch 'master' of newgeom:newgeom
[modules/shaper.git] / src / Model / Model_Document.cpp
1 // File:        Model_Document.cxx
2 // Created:     28 Feb 2014
3 // Author:      Mikhail PONIKAROV
4
5 #include <Model_Document.h>
6 #include <ModelAPI_Feature.h>
7 #include <Model_Data.h>
8 #include <Model_Application.h>
9 #include <Model_PluginManager.h>
10 #include <Model_Iterator.h>
11 #include <Model_Events.h>
12 #include <Event_Loop.h>
13
14 #include <TDataStd_Integer.hxx>
15 #include <TDataStd_Comment.hxx>
16 #include <TDF_ChildIDIterator.hxx>
17
18 #include <climits>
19
20 static const int UNDO_LIMIT = 10; // number of possible undo operations
21
22 static const int TAG_GENERAL = 1; // general properties tag
23 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (Root for Model_DatasMgr)
24 static const int TAG_HISTORY = 3; // tag of the history sub-tree (Root for Model_History)
25
26 using namespace std;
27
28 bool Model_Document::load(const char* theFileName)
29 {
30   bool myIsError = Standard_False;
31   /*
32    TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
33    PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
34    try
35    {
36    Handle(TDocStd_Document) aDoc = this;
37    aStatus = Model_Application::GetApplication()->Open(aPath, aDoc);
38    }
39    catch (Standard_Failure)
40    {}
41    myIsError = aStatus != PCDM_RS_OK;
42    if (myIsError)
43    {
44    switch (aStatus)
45    {
46    case PCDM_RS_UnknownDocument: cout<<"OCAFApp_Appl_RUnknownDocument"<<endl; break;
47    case PCDM_RS_AlreadyRetrieved: cout<<"OCAFApp_Appl_RAlreadyRetrieved"<<endl; break;
48    case PCDM_RS_AlreadyRetrievedAndModified: cout<<"OCAFApp_Appl_RAlreadyRetrievedAndModified"<<endl; break;
49    case PCDM_RS_NoDriver: cout<<"OCAFApp_Appl_RNoDriver"<<endl; break;
50    case PCDM_RS_UnknownFileDriver: cout<<"OCAFApp_Appl_RNoDriver"<<endl; break;
51    case PCDM_RS_OpenError: cout<<"OCAFApp_Appl_ROpenError"<<endl; break;
52    case PCDM_RS_NoVersion: cout<<"OCAFApp_Appl_RNoVersion"<<endl; break;
53    case PCDM_RS_NoModel: cout<<"OCAFApp_Appl_RNoModel"<<endl; break;
54    case PCDM_RS_NoDocument: cout<<"OCAFApp_Appl_RNoDocument"<<endl; break;
55    case PCDM_RS_FormatFailure: cout<<"OCAFApp_Appl_RFormatFailure"<<endl; break;
56    case PCDM_RS_TypeNotFoundInSchema: cout<<"OCAFApp_Appl_RTypeNotFound"<<endl; break;
57    case PCDM_RS_UnrecognizedFileFormat: cout<<"OCAFApp_Appl_RBadFileFormat"<<endl; break;
58    case PCDM_RS_MakeFailure: cout<<"OCAFApp_Appl_RMakeFailure"<<endl; break;
59    case PCDM_RS_PermissionDenied: cout<<"OCAFApp_Appl_RPermissionDenied"<<endl; break;
60    case PCDM_RS_DriverFailure: cout<<"OCAFApp_Appl_RDriverFailure"<<endl; break;
61    default: cout<<"OCAFApp_Appl_RUnknownFail"<<endl; break;
62    }
63    }
64    SetUndoLimit(UNDO_LIMIT);
65    */
66   return !myIsError;
67 }
68
69 bool Model_Document::save(const char* theFileName)
70 {
71   bool myIsError = true;
72   /*
73    TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
74    PCDM_StoreStatus aStatus;
75    try {
76    Handle(TDocStd_Document) aDoc = this;
77    aStatus = Model_Application::GetApplication()->SaveAs (aDoc, aPath);
78    }
79    catch (Standard_Failure) {
80    Handle(Standard_Failure) aFail = Standard_Failure::Caught();
81    cout<<"OCAFApp_Engine:save Error: "<<aFail->GetMessageString()<<endl;
82    return false;
83    }
84    myIsError = aStatus != PCDM_SS_OK;
85    if (myIsError)
86    {
87    switch (aStatus)
88    {
89    case PCDM_SS_DriverFailure:
90    cout<<"OCAFApp_Appl_SDriverFailure"<<endl;
91    break;
92    case PCDM_SS_WriteFailure:
93    cout<<"OCAFApp_Appl_SWriteFailure"<<endl;
94    break;
95    case PCDM_SS_Failure:
96    default:
97    cout<<"OCAFApp_Appl_SUnknownFailure"<<endl;
98    break;
99    }
100    }
101    myTransactionsAfterSave = 0;
102    Standard::Purge(); // Release free memory
103    */
104   return !myIsError;
105 }
106
107 void Model_Document::close()
108 {
109   // close all subs
110   set<string>::iterator aSubIter = mySubs.begin();
111   for(; aSubIter != mySubs.end(); aSubIter++)
112     subDocument(*aSubIter)->close();
113   mySubs.clear();
114   // close this
115   myDoc->Close();
116   Model_Application::getApplication()->deleteDocument(myID);
117 }
118
119 void Model_Document::startOperation()
120 {
121   // new command for this
122   myDoc->NewCommand();
123   // new command for all subs
124   set<string>::iterator aSubIter = mySubs.begin();
125   for(; aSubIter != mySubs.end(); aSubIter++)
126     subDocument(*aSubIter)->startOperation();
127 }
128
129 void Model_Document::finishOperation()
130 {
131   // returns false if delta is empty and no transaction was made
132   myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
133   myTransactionsAfterSave++;
134   // finish for all subs
135   set<string>::iterator aSubIter = mySubs.begin();
136   for(; aSubIter != mySubs.end(); aSubIter++)
137     subDocument(*aSubIter)->finishOperation();
138 }
139
140 void Model_Document::abortOperation()
141 {
142   myDoc->AbortCommand();
143   // abort for all subs
144   set<string>::iterator aSubIter = mySubs.begin();
145   for(; aSubIter != mySubs.end(); aSubIter++)
146     subDocument(*aSubIter)->abortOperation();
147 }
148
149 bool Model_Document::isOperation()
150 {
151   // operation is opened for all documents: no need to check subs
152   return myDoc->HasOpenCommand() == Standard_True ;
153 }
154
155 bool Model_Document::isModified()
156 {
157   // is modified if at least one operation was commited and not undoed
158   return myTransactionsAfterSave > 0;
159 }
160
161 bool Model_Document::canUndo()
162 {
163   if (myDoc->GetAvailableUndos() > 0)
164     return true;
165   // check other subs contains operation that can be undoed
166   set<string>::iterator aSubIter = mySubs.begin();
167   for(; aSubIter != mySubs.end(); aSubIter++)
168     if (subDocument(*aSubIter)->canUndo())
169       return true;
170   return false;
171 }
172
173 void Model_Document::undo()
174 {
175   myTransactionsAfterSave--;
176   if (!myIsEmptyTr[myTransactionsAfterSave])
177     myDoc->Undo();
178   synchronizeFeatures();
179   // undo for all subs
180   set<string>::iterator aSubIter = mySubs.begin();
181   for(; aSubIter != mySubs.end(); aSubIter++)
182     subDocument(*aSubIter)->undo();
183 }
184
185 bool Model_Document::canRedo()
186 {
187   if (myDoc->GetAvailableRedos() > 0)
188     return true;
189   // check other subs contains operation that can be redoed
190   set<string>::iterator aSubIter = mySubs.begin();
191   for(; aSubIter != mySubs.end(); aSubIter++)
192     if (subDocument(*aSubIter)->canRedo())
193       return true;
194   return false;
195 }
196
197 void Model_Document::redo()
198 {
199   if (!myIsEmptyTr[myTransactionsAfterSave])
200     myDoc->Redo();
201   myTransactionsAfterSave++;
202   synchronizeFeatures();
203   // redo for all subs
204   set<string>::iterator aSubIter = mySubs.begin();
205   for(; aSubIter != mySubs.end(); aSubIter++)
206     subDocument(*aSubIter)->redo();
207 }
208
209 boost::shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
210 {
211   boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(theID);
212   if (aFeature) {
213     boost::dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
214   } else {
215     // TODO: generate error that feature is not created
216   }
217   return aFeature;
218 }
219
220 void Model_Document::addFeature(const boost::shared_ptr<ModelAPI_Feature> theFeature)
221 {
222   const std::string& aGroup = theFeature->getGroup();
223   TDF_Label aGroupLab = groupLabel(aGroup);
224   TDF_Label anObjLab = aGroupLab.NewChild();
225   boost::shared_ptr<Model_Data> aData(new Model_Data);
226   aData->setLabel(anObjLab);
227   boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
228   aData->setDocument(aThis);
229   theFeature->setData(aData);
230   setUniqueName(theFeature);
231   theFeature->initAttributes();
232   // keep the feature ID to restore document later correctly
233   TDataStd_Comment::Set(anObjLab, theFeature->getKind().c_str());
234   // put index of the feature in the group in the tree
235   TDataStd_Integer::Set(anObjLab, myFeatures[aGroup].size());
236   myFeatures[aGroup].push_back(theFeature);
237
238   // event: feature is added
239   static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
240   ModelAPI_FeatureUpdatedMessage aMsg(aThis, theFeature, anEvent);
241   Event_Loop::loop()->send(aMsg);
242 }
243
244 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
245 {
246   Handle(TDataStd_Integer) aFeatureIndex;
247   if (theLabel.FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
248     Handle(TDataStd_Comment) aGroupID;
249     if (theLabel.Father().FindAttribute(TDataStd_Comment::GetID(), aGroupID)) {
250       string aGroup = TCollection_AsciiString(aGroupID->Get()).ToCString();
251       return myFeatures[aGroup][aFeatureIndex->Get()];
252     }
253   }
254   return boost::shared_ptr<ModelAPI_Feature>(); // not found
255 }
256
257 int Model_Document::featureIndex(boost::shared_ptr<ModelAPI_Feature> theFeature)
258 {
259   if (theFeature->data()->document().get() != this) {
260     return theFeature->data()->document()->featureIndex(theFeature);
261   }
262   boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theFeature->data());
263   Handle(TDataStd_Integer) aFeatureIndex;
264   if (aData->label().FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
265     return aFeatureIndex->Get();
266   }
267   return -1; // not found
268 }
269
270 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
271 {
272   // just store sub-document identifier here to manage it later
273   if (mySubs.find(theDocID) == mySubs.end())
274     mySubs.insert(theDocID);
275   return Model_Application::getApplication()->getDocument(theDocID);
276 }
277
278 boost::shared_ptr<ModelAPI_Iterator> Model_Document::featuresIterator(const string theGroup)
279 {
280   boost::shared_ptr<Model_Document> aThis(Model_Application::getApplication()->getDocument(myID));
281   // create an empty iterator for not existing group 
282   // (to avoidance of attributes management outside the transaction)
283   if (myGroups.find(theGroup) == myGroups.end())
284     return boost::shared_ptr<ModelAPI_Iterator>(new Model_Iterator());
285   return boost::shared_ptr<ModelAPI_Iterator>(new Model_Iterator(aThis, groupLabel(theGroup)));
286 }
287
288 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(const string& theGroupID, const int theIndex)
289 {
290   // TODO: optimize this method
291   boost::shared_ptr<ModelAPI_Iterator>  anIter = featuresIterator(theGroupID);
292   for(int a = 0; a != theIndex && anIter->more(); anIter->next()) a++;
293   return anIter->more() ? anIter->current() : boost::shared_ptr<ModelAPI_Feature>();
294 }
295
296 const vector<string>& Model_Document::getGroups() const
297 {
298   return myGroupsNames;
299 }
300
301 Model_Document::Model_Document(const std::string theID)
302     : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
303 {
304   myDoc->SetUndoLimit(UNDO_LIMIT);
305   myTransactionsAfterSave = 0;
306   // to avoid creation of tag outside of the transaction (by iterator, for example)
307   /*
308   if (!myDoc->Main().FindChild(TAG_OBJECTS).IsAttribute(TDF_TagSource::GetID()))
309     TDataStd_Comment::Set(myDoc->Main().FindChild(TAG_OBJECTS).NewChild(), "");
310     */
311 }
312
313 TDF_Label Model_Document::groupLabel(const string theGroup)
314 {
315   if (myGroups.find(theGroup) == myGroups.end()) {
316     myGroups[theGroup] = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
317     myGroupsNames.push_back(theGroup);
318     // set to the group label the group idntifier to restore on "open"
319     TDataStd_Comment::Set(myGroups[theGroup], theGroup.c_str());
320     myFeatures[theGroup] = vector<boost::shared_ptr<ModelAPI_Feature> >();
321   }
322   return myGroups[theGroup];
323 }
324
325 void Model_Document::setUniqueName(boost::shared_ptr<ModelAPI_Feature> theFeature)
326 {
327   // first count all objects of such kind to start with index = count + 1
328   int aNumObjects = 0;
329   boost::shared_ptr<ModelAPI_Iterator> anIter = featuresIterator(theFeature->getGroup());
330   for(; anIter->more(); anIter->next()) {
331     if (anIter->currentKind() == theFeature->getKind())
332       aNumObjects++;
333   }
334   // generate candidate name
335   stringstream aNameStream;
336   aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
337   string aName = aNameStream.str();
338   // check this is unique, if not, increase index by 1
339   for(anIter = featuresIterator(theFeature->getGroup()); anIter->more();) {
340     if (anIter->currentName() == aName) {
341       aNumObjects++;
342       stringstream aNameStream;
343       aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
344       // reinitialize iterator to make sure a new name is unique
345       anIter = featuresIterator(theFeature->getGroup());
346     } else anIter->next();
347   }
348
349   theFeature->data()->setName(aName);
350 }
351
352 void Model_Document::synchronizeFeatures()
353 {
354   boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
355   // iterate groups labels
356   TDF_ChildIDIterator aGroupsIter(myDoc->Main().FindChild(TAG_OBJECTS),
357     TDataStd_Comment::GetID(), Standard_False);
358   vector<string>::iterator aGroupNamesIter = myGroupsNames.begin();
359   for(; aGroupsIter.More() && aGroupNamesIter != myGroupsNames.end();
360         aGroupsIter.Next(), aGroupNamesIter++) {
361     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
362       aGroupsIter.Value())->Get()).ToCString();
363     if (*aGroupNamesIter != aGroupName) 
364       break; // all since there is a change this must be recreated from scratch
365   }
366   // delete all groups left after the data model groups iteration
367   while(aGroupNamesIter != myGroupsNames.end()) {
368     string aGroupName = *aGroupNamesIter;
369     myFeatures.erase(aGroupName);
370     myGroups.erase(aGroupName);
371     aGroupNamesIter = myGroupsNames.erase(aGroupNamesIter);
372     // say that features were deleted from group
373     ModelAPI_FeatureDeletedMessage aMsg(aThis, aGroupName);
374     Event_Loop::loop()->send(aMsg);
375   }
376   // create new groups basing on the following data model update
377   for(; aGroupsIter.More(); aGroupsIter.Next()) {
378     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
379       aGroupsIter.Value())->Get()).ToCString();
380     myGroupsNames.push_back(aGroupName);
381     myGroups[aGroupName] = aGroupsIter.Value()->Label();
382     myFeatures[aGroupName] = vector<boost::shared_ptr<ModelAPI_Feature> >();
383   }
384   // update features group by group
385   aGroupsIter.Initialize(myDoc->Main().FindChild(TAG_OBJECTS),
386     TDataStd_Comment::GetID(), Standard_False);
387   for(; aGroupsIter.More(); aGroupsIter.Next()) {
388     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
389       aGroupsIter.Value())->Get()).ToCString();
390     // iterate features in internal container
391     vector<boost::shared_ptr<ModelAPI_Feature> >& aFeatures = myFeatures[aGroupName];
392     vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = aFeatures.begin();
393     // and in parallel iterate labels of features
394     TDF_ChildIDIterator aFLabIter(
395       aGroupsIter.Value()->Label(), TDataStd_Comment::GetID(), Standard_False);
396     while(aFIter != aFeatures.end() || aFLabIter.More()) {
397       static const int INFINITE_TAG = INT_MAX; // no label means that it exists somwhere in infinite
398       int aFeatureTag = INFINITE_TAG; 
399       if (aFIter != aFeatures.end()) { // existing tag for feature
400         boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
401         aFeatureTag = aData->label().Tag();
402       }
403       int aDSTag = INFINITE_TAG; 
404       if (aFLabIter.More()) { // next label in DS is existing
405         aDSTag = aFLabIter.Value()->Label().Tag();
406       }
407       if (aDSTag > aFeatureTag) { // feature is removed
408         aFIter = aFeatures.erase(aFIter);
409         // event: model is updated
410         ModelAPI_FeatureDeletedMessage aMsg(aThis, aGroupName);
411         Event_Loop::loop()->send(aMsg);
412       } else if (aDSTag < aFeatureTag) { // a new feature is inserted
413         // create a feature
414         boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
415           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
416           aFLabIter.Value())->Get()).ToCString());
417
418         boost::shared_ptr<Model_Data> aData(new Model_Data);
419         TDF_Label aLab = aFLabIter.Value()->Label();
420         aData->setLabel(aLab);
421         aData->setDocument(Model_Application::getApplication()->getDocument(myID));
422         aFeature->setData(aData);
423         aFeature->initAttributes();
424         // event: model is updated
425         static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
426         ModelAPI_FeatureUpdatedMessage aMsg(aThis, aFeature, anEvent);
427         Event_Loop::loop()->send(aMsg);
428
429         if (aFIter == aFeatures.end()) {
430           aFeatures.push_back(aFeature);
431           aFIter = aFeatures.end();
432         } else {
433           aFIter++;
434           aFeatures.insert(aFIter, aFeature);
435         }
436         // feature for this label is added, so go to the next label
437         aFLabIter.Next();
438       } else { // nothing is changed, both iterators are incremented
439         aFIter++;
440         aFLabIter.Next();
441       }
442     }
443   }
444 }