]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Document.cpp
Salome HOME
Fixed crash on the second item creation
[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   Handle(TDataStd_ReferenceArray) aRefs;
243   if (!groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
244     aRefs = TDataStd_ReferenceArray::Set(groupLabel(FEATURES_GROUP), 0, 0);
245     aRefs->SetValue(0, anObjLab);
246   } else { // extend array by one more element
247     Handle(TDataStd_HLabelArray1) aNewArray = 
248       new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() + 1);
249     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
250       aNewArray->SetValue(a, aRefs->Value(a));
251     }
252     aNewArray->SetValue(aRefs->Upper() + 1, anObjLab);
253     aRefs->SetInternalArray(aNewArray);
254   }
255
256   // event: feature is added
257   static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
258   Model_FeatureUpdatedMessage aMsg(theFeature, anEvent);
259   Events_Loop::loop()->send(aMsg);
260 }
261
262 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
263 {
264   Handle(TDataStd_Integer) aFeatureIndex;
265   if (theLabel.FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
266     Handle(TDataStd_Comment) aGroupID;
267     if (theLabel.Father().FindAttribute(TDataStd_Comment::GetID(), aGroupID)) {
268       string aGroup = TCollection_AsciiString(aGroupID->Get()).ToCString();
269       return myFeatures[aGroup][aFeatureIndex->Get()];
270     }
271   }
272   return boost::shared_ptr<ModelAPI_Feature>(); // not found
273 }
274
275 int Model_Document::featureIndex(boost::shared_ptr<ModelAPI_Feature> theFeature)
276 {
277   if (theFeature->document().get() != this) {
278     return theFeature->document()->featureIndex(theFeature);
279   }
280   boost::shared_ptr<Model_Data> aData =
281     boost::dynamic_pointer_cast<Model_Data>(theFeature->data());
282   Handle(TDataStd_Integer) aFeatureIndex;
283   if (aData->label().FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
284     return aFeatureIndex->Get();
285   }
286   return -1; // not found
287 }
288
289 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
290 {
291   // just store sub-document identifier here to manage it later
292   if (mySubs.find(theDocID) == mySubs.end())
293     mySubs.insert(theDocID);
294   return Model_Application::getApplication()->getDocument(theDocID);
295 }
296
297 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
298   const string& theGroupID, const int theIndex)
299 {
300   if (theGroupID == FEATURES_GROUP) { // history is just a references array
301     Handle(TDataStd_ReferenceArray) aRefs;
302     if (groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
303       if (aRefs->Lower() <= theIndex && aRefs->Upper() >= theIndex) {
304         TDF_Label aFeatureLab = aRefs->Value(theIndex);
305         return feature(aFeatureLab);
306       }
307     }
308   } else { // one of the group
309     map<string, vector<boost::shared_ptr<ModelAPI_Feature> > >::iterator aGroup = 
310       myFeatures.find(theGroupID);
311     if (aGroup != myFeatures.end() && (int)(aGroup->second.size()) > theIndex) {
312       return aGroup->second[theIndex];
313     }
314   }
315   // not found
316   return boost::shared_ptr<ModelAPI_Feature>();
317 }
318
319 int Model_Document::size(const string& theGroupID) 
320 {
321   if (theGroupID == FEATURES_GROUP) { // history is just a references array
322     Handle(TDataStd_ReferenceArray) aRefs;
323     if (groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
324       return aRefs->Length();
325   } else { // one of the group
326     map<string, vector<boost::shared_ptr<ModelAPI_Feature> > >::iterator aGroup = 
327       myFeatures.find(theGroupID);
328     if (aGroup != myFeatures.end())
329       return aGroup->second.size();
330   }
331   // group is not found
332   return 0;
333 }
334
335 const vector<string>& Model_Document::getGroups() const
336 {
337   return myGroupsNames;
338 }
339
340 Model_Document::Model_Document(const std::string theID)
341     : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
342 {
343   myDoc->SetUndoLimit(UNDO_LIMIT);
344   myTransactionsAfterSave = 0;
345 }
346
347 TDF_Label Model_Document::groupLabel(const string theGroup)
348 {
349   if (myGroups.find(theGroup) == myGroups.end()) {
350     myGroups[theGroup] = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
351     myGroupsNames.push_back(theGroup);
352     // set to the group label the group idntifier to restore on "open"
353     TDataStd_Comment::Set(myGroups[theGroup], theGroup.c_str());
354     myFeatures[theGroup] = vector<boost::shared_ptr<ModelAPI_Feature> >();
355   }
356   return myGroups[theGroup];
357 }
358
359 void Model_Document::setUniqueName(boost::shared_ptr<ModelAPI_Feature> theFeature)
360 {
361   // first count all objects of such kind to start with index = count + 1
362   int a, aNumObjects = 0;
363   int aSize = size(theFeature->getGroup());
364   for(a = 0; a < aSize; a++) {
365     if (feature(theFeature->getGroup(), a)->getKind() == theFeature->getKind())
366       aNumObjects++;
367   }
368   // generate candidate name
369   stringstream aNameStream;
370   aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
371   string aName = aNameStream.str();
372   // check this is unique, if not, increase index by 1
373   for(a = 0; a < aSize;) {
374     if (feature(theFeature->getGroup(), a)->data()->getName() == aName) {
375       aNumObjects++;
376       stringstream aNameStream;
377       aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
378       // reinitialize iterator to make sure a new name is unique
379       a = 0;
380     } else a++;
381   }
382
383   theFeature->data()->setName(aName);
384 }
385
386 void Model_Document::synchronizeFeatures()
387 {
388   boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
389   // iterate groups labels
390   TDF_ChildIDIterator aGroupsIter(myDoc->Main().FindChild(TAG_OBJECTS),
391     TDataStd_Comment::GetID(), Standard_False);
392   vector<string>::iterator aGroupNamesIter = myGroupsNames.begin();
393   for(; aGroupsIter.More() && aGroupNamesIter != myGroupsNames.end();
394         aGroupsIter.Next(), aGroupNamesIter++) {
395     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
396       aGroupsIter.Value())->Get()).ToCString();
397     if (*aGroupNamesIter != aGroupName) 
398       break; // all since there is a change this must be recreated from scratch
399   }
400   // delete all groups left after the data model groups iteration
401   while(aGroupNamesIter != myGroupsNames.end()) {
402     string aGroupName = *aGroupNamesIter;
403     myFeatures.erase(aGroupName);
404     myGroups.erase(aGroupName);
405     aGroupNamesIter = myGroupsNames.erase(aGroupNamesIter);
406     // say that features were deleted from group
407     Model_FeatureDeletedMessage aMsg(aThis, aGroupName);
408     Events_Loop::loop()->send(aMsg);
409   }
410   // create new groups basing on the following data model update
411   for(; aGroupsIter.More(); aGroupsIter.Next()) {
412     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
413       aGroupsIter.Value())->Get()).ToCString();
414     myGroupsNames.push_back(aGroupName);
415     myGroups[aGroupName] = aGroupsIter.Value()->Label();
416     myFeatures[aGroupName] = vector<boost::shared_ptr<ModelAPI_Feature> >();
417   }
418   // update features group by group
419   aGroupsIter.Initialize(myDoc->Main().FindChild(TAG_OBJECTS),
420     TDataStd_Comment::GetID(), Standard_False);
421   for(; aGroupsIter.More(); aGroupsIter.Next()) {
422     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
423       aGroupsIter.Value())->Get()).ToCString();
424     // iterate features in internal container
425     vector<boost::shared_ptr<ModelAPI_Feature> >& aFeatures = myFeatures[aGroupName];
426     vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = aFeatures.begin();
427     // and in parallel iterate labels of features
428     TDF_ChildIDIterator aFLabIter(
429       aGroupsIter.Value()->Label(), TDataStd_Comment::GetID(), Standard_False);
430     while(aFIter != aFeatures.end() || aFLabIter.More()) {
431       static const int INFINITE_TAG = INT_MAX; // no label means that it exists somwhere in infinite
432       int aFeatureTag = INFINITE_TAG; 
433       if (aFIter != aFeatures.end()) { // existing tag for feature
434         boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
435         aFeatureTag = aData->label().Tag();
436       }
437       int aDSTag = INFINITE_TAG; 
438       if (aFLabIter.More()) { // next label in DS is existing
439         aDSTag = aFLabIter.Value()->Label().Tag();
440       }
441       if (aDSTag > aFeatureTag) { // feature is removed
442         aFIter = aFeatures.erase(aFIter);
443         // event: model is updated
444         Model_FeatureDeletedMessage aMsg(aThis, aGroupName);
445         Events_Loop::loop()->send(aMsg);
446       } else if (aDSTag < aFeatureTag) { // a new feature is inserted
447         // create a feature
448         boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
449           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
450           aFLabIter.Value())->Get()).ToCString());
451
452         boost::shared_ptr<Model_Data> aData(new Model_Data);
453         TDF_Label aLab = aFLabIter.Value()->Label();
454         aData->setLabel(aLab);
455         aData->setFeature(aFeature);
456         aFeature->setDoc(aThis);
457         aFeature->setData(aData);
458         aFeature->initAttributes();
459         // event: model is updated
460         static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
461         Model_FeatureUpdatedMessage aMsg(aFeature, anEvent);
462         Events_Loop::loop()->send(aMsg);
463
464         if (aFIter == aFeatures.end()) {
465           aFeatures.push_back(aFeature);
466           aFIter = aFeatures.end();
467         } else {
468           aFIter++;
469           aFeatures.insert(aFIter, aFeature);
470         }
471         // feature for this label is added, so go to the next label
472         aFLabIter.Next();
473       } else { // nothing is changed, both iterators are incremented
474         aFIter++;
475         aFLabIter.Next();
476       }
477     }
478   }
479 }