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 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));
252 aNewArray->SetValue(aRefs->Upper() + 1, anObjLab);
253 aRefs->SetInternalArray(aNewArray);
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);
262 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
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()];
272 return boost::shared_ptr<ModelAPI_Feature>(); // not found
275 int Model_Document::featureIndex(boost::shared_ptr<ModelAPI_Feature> theFeature)
277 if (theFeature->document().get() != this) {
278 return theFeature->document()->featureIndex(theFeature);
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();
286 return -1; // not found
289 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
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);
297 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
298 const string& theGroupID, const int theIndex)
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);
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];
316 return boost::shared_ptr<ModelAPI_Feature>();
319 int Model_Document::size(const string& theGroupID)
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();
331 // group is not found
335 const vector<string>& Model_Document::getGroups() const
337 return myGroupsNames;
340 Model_Document::Model_Document(const std::string theID)
341 : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
343 myDoc->SetUndoLimit(UNDO_LIMIT);
344 myTransactionsAfterSave = 0;
347 TDF_Label Model_Document::groupLabel(const string theGroup)
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> >();
356 return myGroups[theGroup];
359 void Model_Document::setUniqueName(boost::shared_ptr<ModelAPI_Feature> theFeature)
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())
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) {
376 stringstream aNameStream;
377 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
378 // reinitialize iterator to make sure a new name is unique
383 theFeature->data()->setName(aName);
386 void Model_Document::synchronizeFeatures()
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
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);
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> >();
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();
437 int aDSTag = INFINITE_TAG;
438 if (aFLabIter.More()) { // next label in DS is existing
439 aDSTag = aFLabIter.Value()->Label().Tag();
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
448 boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
449 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
450 aFLabIter.Value())->Get()).ToCString());
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);
464 if (aFIter == aFeatures.end()) {
465 aFeatures.push_back(aFeature);
466 aFIter = aFeatures.end();
469 aFeatures.insert(aFIter, aFeature);
471 // feature for this label is added, so go to the next label
473 } else { // nothing is changed, both iterators are incremented