Salome HOME
Updated events for Model and minor other changes
[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   aData->setDocument(Model_Application::getApplication()->getDocument(myID));
226   theFeature->setData(aData);
227   setUniqueName(theFeature);
228   theFeature->initAttributes();
229   // keep the feature ID to restore document later correctly
230   TDataStd_Comment::Set(anObjLab, theFeature->getKind().c_str());
231   // put index of the feature in the group in the tree
232   TDataStd_Integer::Set(anObjLab, myFeatures[aGroup].size());
233   myFeatures[aGroup].push_back(theFeature);
234
235   // event: feature is added
236   static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
237   ModelAPI_FeatureUpdatedMessage aMsg(theFeature, anEvent);
238   Event_Loop::loop()->send(aMsg);
239 }
240
241 shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
242 {
243   Handle(TDataStd_Integer) aFeatureIndex;
244   if (theLabel.FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
245     Handle(TDataStd_Comment) aGroupID;
246     if (theLabel.Father().FindAttribute(TDataStd_Comment::GetID(), aGroupID)) {
247       string aGroup = TCollection_AsciiString(aGroupID->Get()).ToCString();
248       return myFeatures[aGroup][aFeatureIndex->Get()];
249     }
250   }
251   return std::shared_ptr<ModelAPI_Feature>(); // not found
252 }
253
254 int Model_Document::featureIndex(shared_ptr<ModelAPI_Feature> theFeature)
255 {
256   if (theFeature->data()->document().get() != this) {
257     return theFeature->data()->document()->featureIndex(theFeature);
258   }
259   shared_ptr<Model_Data> aData = dynamic_pointer_cast<Model_Data>(theFeature->data());
260   Handle(TDataStd_Integer) aFeatureIndex;
261   if (aData->label().FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
262     return aFeatureIndex->Get();
263   }
264   return -1; // not found
265 }
266
267 shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
268 {
269   // just store sub-document identifier here to manage it later
270   if (mySubs.find(theDocID) == mySubs.end())
271     mySubs.insert(theDocID);
272   return Model_Application::getApplication()->getDocument(theDocID);
273 }
274
275 shared_ptr<ModelAPI_Iterator> Model_Document::featuresIterator(const string theGroup)
276 {
277   shared_ptr<Model_Document> aThis(Model_Application::getApplication()->getDocument(myID));
278   // create an empty iterator for not existing group 
279   // (to avoidance of attributes management outside the transaction)
280   if (myGroups.find(theGroup) == myGroups.end())
281     return shared_ptr<ModelAPI_Iterator>(new Model_Iterator());
282   return shared_ptr<ModelAPI_Iterator>(new Model_Iterator(aThis, groupLabel(theGroup)));
283 }
284
285 shared_ptr<ModelAPI_Feature> Model_Document::feature(const string& theGroupID, const int theIndex)
286 {
287   // TODO: optimize this method
288   shared_ptr<ModelAPI_Iterator>  anIter = featuresIterator(theGroupID);
289   for(int a = 0; a != theIndex && anIter->more(); anIter->next()) a++;
290   return anIter->more() ? anIter->current() : shared_ptr<ModelAPI_Feature>();
291 }
292
293 const vector<string>& Model_Document::getGroups() const
294 {
295   return myGroupsNames;
296 }
297
298 Model_Document::Model_Document(const std::string theID)
299     : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
300 {
301   myDoc->SetUndoLimit(UNDO_LIMIT);
302   myTransactionsAfterSave = 0;
303   // to avoid creation of tag outside of the transaction (by iterator, for example)
304   /*
305   if (!myDoc->Main().FindChild(TAG_OBJECTS).IsAttribute(TDF_TagSource::GetID()))
306     TDataStd_Comment::Set(myDoc->Main().FindChild(TAG_OBJECTS).NewChild(), "");
307     */
308 }
309
310 TDF_Label Model_Document::groupLabel(const string theGroup)
311 {
312   if (myGroups.find(theGroup) == myGroups.end()) {
313     myGroups[theGroup] = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
314     myGroupsNames.push_back(theGroup);
315     // set to the group label the group idntifier to restore on "open"
316     TDataStd_Comment::Set(myGroups[theGroup], theGroup.c_str());
317     myFeatures[theGroup] = vector<shared_ptr<ModelAPI_Feature> >();
318   }
319   return myGroups[theGroup];
320 }
321
322 void Model_Document::setUniqueName(
323   shared_ptr<ModelAPI_Feature> theFeature)
324 {
325   // first count all objects of such kind to start with index = count + 1
326   int aNumObjects = 0;
327   shared_ptr<ModelAPI_Iterator> anIter = featuresIterator(theFeature->getGroup());
328   for(; anIter->more(); anIter->next()) {
329     if (anIter->currentKind() == theFeature->getKind())
330       aNumObjects++;
331   }
332   // generate candidate name
333   stringstream aNameStream;
334   aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
335   string aName = aNameStream.str();
336   // check this is unique, if not, increase index by 1
337   for(anIter = featuresIterator(theFeature->getGroup()); anIter->more();) {
338     if (anIter->currentName() == aName) {
339       aNumObjects++;
340       stringstream aNameStream;
341       aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
342       // reinitialize iterator to make sure a new name is unique
343       anIter = featuresIterator(theFeature->getGroup());
344     } else anIter->next();
345   }
346
347   theFeature->data()->setName(aName);
348 }
349
350 void Model_Document::synchronizeFeatures()
351 {
352   // iterate groups labels
353   TDF_ChildIDIterator aGroupsIter(myDoc->Main().FindChild(TAG_OBJECTS),
354     TDataStd_Comment::GetID(), Standard_False);
355   vector<string>::iterator aGroupNamesIter = myGroupsNames.begin();
356   for(; aGroupsIter.More() && aGroupNamesIter != myGroupsNames.end();
357         aGroupsIter.Next(), aGroupNamesIter++) {
358     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
359       aGroupsIter.Value())->Get()).ToCString();
360     if (*aGroupNamesIter != aGroupName) 
361       break; // all since there is a change this must be recreated from scratch
362   }
363   // delete all groups left after the data model groups iteration
364   while(aGroupNamesIter != myGroupsNames.end()) {
365     myFeatures.erase(*aGroupNamesIter);
366     myGroups.erase(*aGroupNamesIter);
367     aGroupNamesIter = myGroupsNames.erase(aGroupNamesIter);
368   }
369   // create new groups basing on the following data model update
370   for(; aGroupsIter.More(); aGroupsIter.Next()) {
371     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
372       aGroupsIter.Value())->Get()).ToCString();
373     myGroupsNames.push_back(aGroupName);
374     myGroups[aGroupName] = aGroupsIter.Value()->Label();
375     myFeatures[aGroupName] = vector<shared_ptr<ModelAPI_Feature> >();
376   }
377   // update features group by group
378   aGroupsIter.Initialize(myDoc->Main().FindChild(TAG_OBJECTS),
379     TDataStd_Comment::GetID(), Standard_False);
380   for(; aGroupsIter.More(); aGroupsIter.Next()) {
381     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
382       aGroupsIter.Value())->Get()).ToCString();
383     // iterate features in internal container
384     vector<shared_ptr<ModelAPI_Feature> >& aFeatures = myFeatures[aGroupName];
385     vector<shared_ptr<ModelAPI_Feature> >::iterator aFIter = aFeatures.begin();
386     // and in parallel iterate labels of features
387     TDF_ChildIDIterator aFLabIter(
388       aGroupsIter.Value()->Label(), TDataStd_Comment::GetID(), Standard_False);
389     while(aFIter != aFeatures.end() || aFLabIter.More()) {
390       static const int INFINITE_TAG = MAXINT; // no label means that it exists somwhere in infinite
391       int aFeatureTag = INFINITE_TAG; 
392       if (aFIter != aFeatures.end()) { // existing tag for feature
393         shared_ptr<Model_Data> aData = dynamic_pointer_cast<Model_Data>((*aFIter)->data());
394         aFeatureTag = aData->label().Tag();
395       }
396       int aDSTag = INFINITE_TAG; 
397       if (aFLabIter.More()) { // next label in DS is existing
398         aDSTag = aFLabIter.Value()->Label().Tag();
399       }
400       if (aDSTag > aFeatureTag) { // feature is removed
401         aFIter = aFeatures.erase(aFIter);
402         // event: model is updated
403         ModelAPI_FeatureDeletedMessage aMsg(
404           Model_Application::getApplication()->getDocument(myID), aGroupName);
405         Event_Loop::loop()->send(aMsg);
406       } else if (aDSTag < aFeatureTag) { // a new feature is inserted
407         // create a feature
408         shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
409           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
410           aFLabIter.Value())->Get()).ToCString());
411
412         std::shared_ptr<Model_Data> aData(new Model_Data);
413         TDF_Label aLab = aFLabIter.Value()->Label();
414         aData->setLabel(aLab);
415         aData->setDocument(Model_Application::getApplication()->getDocument(myID));
416         aFeature->setData(aData);
417         aFeature->initAttributes();
418         // event: model is updated
419         static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
420         ModelAPI_FeatureUpdatedMessage aMsg(aFeature, anEvent);
421         Event_Loop::loop()->send(aMsg);
422
423         if (aFIter == aFeatures.end()) {
424           aFeatures.push_back(aFeature);
425           aFIter = aFeatures.end();
426         } else {
427           aFIter++;
428           aFeatures.insert(aFIter, aFeature);
429         }
430         // feature for this label is added, so go to the next label
431         aFLabIter.Next();
432       } else { // nothing is changed, both iterators are incremented
433         aFIter++;
434         aFLabIter.Next();
435       }
436     }
437   }
438 }