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