Salome HOME
Changes in source code within porting on CentOS 6.3
[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 #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 shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
210 {
211   shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(theID);
212   if (aFeature) {
213     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 std::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   std::shared_ptr<Model_Data> aData(new Model_Data);
226   aData->setLabel(anObjLab);
227   aData->setDocument(Model_Application::getApplication()->getDocument(myID));
228   theFeature->setData(aData);
229   setUniqueName(theFeature);
230   theFeature->initAttributes();
231   // keep the feature ID to restore document later correctly
232   TDataStd_Comment::Set(anObjLab, theFeature->getKind().c_str());
233   // put index of the feature in the group in the tree
234   TDataStd_Integer::Set(anObjLab, myFeatures[aGroup].size());
235   myFeatures[aGroup].push_back(theFeature);
236
237   // event: feature is added
238   static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
239   ModelAPI_FeatureUpdatedMessage aMsg(theFeature, anEvent);
240   Event_Loop::loop()->send(aMsg);
241 }
242
243 shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
244 {
245   Handle(TDataStd_Integer) aFeatureIndex;
246   if (theLabel.FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
247     Handle(TDataStd_Comment) aGroupID;
248     if (theLabel.Father().FindAttribute(TDataStd_Comment::GetID(), aGroupID)) {
249       string aGroup = TCollection_AsciiString(aGroupID->Get()).ToCString();
250       return myFeatures[aGroup][aFeatureIndex->Get()];
251     }
252   }
253   return std::shared_ptr<ModelAPI_Feature>(); // not found
254 }
255
256 int Model_Document::featureIndex(shared_ptr<ModelAPI_Feature> theFeature)
257 {
258   if (theFeature->data()->document().get() != this) {
259     return theFeature->data()->document()->featureIndex(theFeature);
260   }
261   shared_ptr<Model_Data> aData = dynamic_pointer_cast<Model_Data>(theFeature->data());
262   Handle(TDataStd_Integer) aFeatureIndex;
263   if (aData->label().FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
264     return aFeatureIndex->Get();
265   }
266   return -1; // not found
267 }
268
269 shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
270 {
271   // just store sub-document identifier here to manage it later
272   if (mySubs.find(theDocID) == mySubs.end())
273     mySubs.insert(theDocID);
274   return Model_Application::getApplication()->getDocument(theDocID);
275 }
276
277 shared_ptr<ModelAPI_Iterator> Model_Document::featuresIterator(const string theGroup)
278 {
279   shared_ptr<Model_Document> aThis(Model_Application::getApplication()->getDocument(myID));
280   // create an empty iterator for not existing group 
281   // (to avoidance of attributes management outside the transaction)
282   if (myGroups.find(theGroup) == myGroups.end())
283     return shared_ptr<ModelAPI_Iterator>(new Model_Iterator());
284   return shared_ptr<ModelAPI_Iterator>(new Model_Iterator(aThis, groupLabel(theGroup)));
285 }
286
287 shared_ptr<ModelAPI_Feature> Model_Document::feature(const string& theGroupID, const int theIndex)
288 {
289   // TODO: optimize this method
290   shared_ptr<ModelAPI_Iterator>  anIter = featuresIterator(theGroupID);
291   for(int a = 0; a != theIndex && anIter->more(); anIter->next()) a++;
292   return anIter->more() ? anIter->current() : shared_ptr<ModelAPI_Feature>();
293 }
294
295 const vector<string>& Model_Document::getGroups() const
296 {
297   return myGroupsNames;
298 }
299
300 Model_Document::Model_Document(const std::string theID)
301     : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
302 {
303   myDoc->SetUndoLimit(UNDO_LIMIT);
304   myTransactionsAfterSave = 0;
305   // to avoid creation of tag outside of the transaction (by iterator, for example)
306   /*
307   if (!myDoc->Main().FindChild(TAG_OBJECTS).IsAttribute(TDF_TagSource::GetID()))
308     TDataStd_Comment::Set(myDoc->Main().FindChild(TAG_OBJECTS).NewChild(), "");
309     */
310 }
311
312 TDF_Label Model_Document::groupLabel(const string theGroup)
313 {
314   if (myGroups.find(theGroup) == myGroups.end()) {
315     myGroups[theGroup] = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
316     myGroupsNames.push_back(theGroup);
317     // set to the group label the group idntifier to restore on "open"
318     TDataStd_Comment::Set(myGroups[theGroup], theGroup.c_str());
319     myFeatures[theGroup] = vector<shared_ptr<ModelAPI_Feature> >();
320   }
321   return myGroups[theGroup];
322 }
323
324 void Model_Document::setUniqueName(
325   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   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   // 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 = INT_MAX; // 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(
406           Model_Application::getApplication()->getDocument(myID), aGroupName);
407         Event_Loop::loop()->send(aMsg);
408       } else if (aDSTag < aFeatureTag) { // a new feature is inserted
409         // create a feature
410         shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
411           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
412           aFLabIter.Value())->Get()).ToCString());
413
414         std::shared_ptr<Model_Data> aData(new Model_Data);
415         TDF_Label aLab = aFLabIter.Value()->Label();
416         aData->setLabel(aLab);
417         aData->setDocument(Model_Application::getApplication()->getDocument(myID));
418         aFeature->setData(aData);
419         aFeature->initAttributes();
420         // event: model is updated
421         static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
422         ModelAPI_FeatureUpdatedMessage aMsg(aFeature, anEvent);
423         Event_Loop::loop()->send(aMsg);
424
425         if (aFIter == aFeatures.end()) {
426           aFeatures.push_back(aFeature);
427           aFIter = aFeatures.end();
428         } else {
429           aFIter++;
430           aFeatures.insert(aFIter, aFeature);
431         }
432         // feature for this label is added, so go to the next label
433         aFLabIter.Next();
434       } else { // nothing is changed, both iterators are incremented
435         aFIter++;
436         aFLabIter.Next();
437       }
438     }
439   }
440 }