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