1 // File: Model_Document.cxx
2 // Created: 28 Feb 2014
3 // Author: Mikhail PONIKAROV
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>
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>
21 static const int UNDO_LIMIT = 10; // number of possible undo operations
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)
29 bool Model_Document::load(const char* theFileName)
31 bool myIsError = Standard_False;
33 TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
34 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
37 Handle(TDocStd_Document) aDoc = this;
38 aStatus = Model_Application::GetApplication()->Open(aPath, aDoc);
40 catch (Standard_Failure)
42 myIsError = aStatus != PCDM_RS_OK;
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;
65 SetUndoLimit(UNDO_LIMIT);
70 bool Model_Document::save(const char* theFileName)
72 bool myIsError = true;
74 TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
75 PCDM_StoreStatus aStatus;
77 Handle(TDocStd_Document) aDoc = this;
78 aStatus = Model_Application::GetApplication()->SaveAs (aDoc, aPath);
80 catch (Standard_Failure) {
81 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
82 cout<<"OCAFApp_Engine:save Error: "<<aFail->GetMessageString()<<endl;
85 myIsError = aStatus != PCDM_SS_OK;
90 case PCDM_SS_DriverFailure:
91 cout<<"OCAFApp_Appl_SDriverFailure"<<endl;
93 case PCDM_SS_WriteFailure:
94 cout<<"OCAFApp_Appl_SWriteFailure"<<endl;
98 cout<<"OCAFApp_Appl_SUnknownFailure"<<endl;
102 myTransactionsAfterSave = 0;
103 Standard::Purge(); // Release free memory
108 void Model_Document::close()
111 set<string>::iterator aSubIter = mySubs.begin();
112 for(; aSubIter != mySubs.end(); aSubIter++)
113 subDocument(*aSubIter)->close();
117 Model_Application::getApplication()->deleteDocument(myID);
120 void Model_Document::startOperation()
122 // new command for this
124 // new command for all subs
125 set<string>::iterator aSubIter = mySubs.begin();
126 for(; aSubIter != mySubs.end(); aSubIter++)
127 subDocument(*aSubIter)->startOperation();
130 void Model_Document::finishOperation()
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();
141 void Model_Document::abortOperation()
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();
150 bool Model_Document::isOperation()
152 // operation is opened for all documents: no need to check subs
153 return myDoc->HasOpenCommand() == Standard_True ;
156 bool Model_Document::isModified()
158 // is modified if at least one operation was commited and not undoed
159 return myTransactionsAfterSave > 0;
162 bool Model_Document::canUndo()
164 if (myDoc->GetAvailableUndos() > 0)
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())
174 void Model_Document::undo()
176 myTransactionsAfterSave--;
177 if (!myIsEmptyTr[myTransactionsAfterSave])
179 synchronizeFeatures();
181 set<string>::iterator aSubIter = mySubs.begin();
182 for(; aSubIter != mySubs.end(); aSubIter++)
183 subDocument(*aSubIter)->undo();
186 bool Model_Document::canRedo()
188 if (myDoc->GetAvailableRedos() > 0)
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())
198 void Model_Document::redo()
200 if (!myIsEmptyTr[myTransactionsAfterSave])
202 myTransactionsAfterSave++;
203 synchronizeFeatures();
205 set<string>::iterator aSubIter = mySubs.begin();
206 for(; aSubIter != mySubs.end(); aSubIter++)
207 subDocument(*aSubIter)->redo();
210 boost::shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
212 boost::shared_ptr<ModelAPI_Feature> aFeature =
213 ModelAPI_PluginManager::get()->createFeature(theID);
215 boost::dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
217 // TODO: generate error that feature is not created
222 void Model_Document::addFeature(const boost::shared_ptr<ModelAPI_Feature> theFeature)
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));
253 aNewArray->SetValue(aRefs->Upper() + 1, anObjLab);
254 aRefs->SetInternalArray(aNewArray);
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);
264 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
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()];
274 return boost::shared_ptr<ModelAPI_Feature>(); // not found
277 int Model_Document::featureIndex(boost::shared_ptr<ModelAPI_Feature> theFeature)
279 if (theFeature->document().get() != this) {
280 return theFeature->document()->featureIndex(theFeature);
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();
288 return -1; // not found
291 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
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);
299 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
300 const string& theGroupID, const int theIndex)
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);
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];
318 return boost::shared_ptr<ModelAPI_Feature>();
321 int Model_Document::size(const string& theGroupID)
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();
333 // group is not found
337 const vector<string>& Model_Document::getGroups() const
339 return myGroupsNames;
342 Model_Document::Model_Document(const std::string theID)
343 : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
345 myDoc->SetUndoLimit(UNDO_LIMIT);
346 myTransactionsAfterSave = 0;
349 TDF_Label Model_Document::groupLabel(const string theGroup)
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> >();
358 return myGroups[theGroup];
361 void Model_Document::setUniqueName(boost::shared_ptr<ModelAPI_Feature> theFeature)
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())
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) {
378 stringstream aNameStream;
379 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
380 // reinitialize iterator to make sure a new name is unique
385 theFeature->data()->setName(aName);
388 void Model_Document::synchronizeFeatures()
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
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);
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> >();
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();
439 int aDSTag = INFINITE_TAG;
440 if (aFLabIter.More()) { // next label in DS is existing
441 aDSTag = aFLabIter.Value()->Label().Tag();
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
450 boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
451 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
452 aFLabIter.Value())->Get()).ToCString());
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);
466 if (aFIter == aFeatures.end()) {
467 aFeatures.push_back(aFeature);
468 aFIter = aFeatures.end();
471 aFeatures.insert(aFIter, aFeature);
473 // feature for this label is added, so go to the next label
475 } else { // nothing is changed, both iterators are incremented