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_Iterator.h>
11 #include <Model_Events.h>
12 #include <Event_Loop.h>
14 #include <TDataStd_Integer.hxx>
15 #include <TDataStd_Comment.hxx>
16 #include <TDF_ChildIDIterator.hxx>
18 static const int UNDO_LIMIT = 10; // number of possible undo operations
20 static const int TAG_GENERAL = 1; // general properties tag
21 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (Root for Model_DatasMgr)
22 static const int TAG_HISTORY = 3; // tag of the history sub-tree (Root for Model_History)
26 bool Model_Document::load(const char* theFileName)
28 bool myIsError = Standard_False;
30 TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
31 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
34 Handle(TDocStd_Document) aDoc = this;
35 aStatus = Model_Application::GetApplication()->Open(aPath, aDoc);
37 catch (Standard_Failure)
39 myIsError = aStatus != PCDM_RS_OK;
44 case PCDM_RS_UnknownDocument: cout<<"OCAFApp_Appl_RUnknownDocument"<<endl; break;
45 case PCDM_RS_AlreadyRetrieved: cout<<"OCAFApp_Appl_RAlreadyRetrieved"<<endl; break;
46 case PCDM_RS_AlreadyRetrievedAndModified: cout<<"OCAFApp_Appl_RAlreadyRetrievedAndModified"<<endl; break;
47 case PCDM_RS_NoDriver: cout<<"OCAFApp_Appl_RNoDriver"<<endl; break;
48 case PCDM_RS_UnknownFileDriver: cout<<"OCAFApp_Appl_RNoDriver"<<endl; break;
49 case PCDM_RS_OpenError: cout<<"OCAFApp_Appl_ROpenError"<<endl; break;
50 case PCDM_RS_NoVersion: cout<<"OCAFApp_Appl_RNoVersion"<<endl; break;
51 case PCDM_RS_NoModel: cout<<"OCAFApp_Appl_RNoModel"<<endl; break;
52 case PCDM_RS_NoDocument: cout<<"OCAFApp_Appl_RNoDocument"<<endl; break;
53 case PCDM_RS_FormatFailure: cout<<"OCAFApp_Appl_RFormatFailure"<<endl; break;
54 case PCDM_RS_TypeNotFoundInSchema: cout<<"OCAFApp_Appl_RTypeNotFound"<<endl; break;
55 case PCDM_RS_UnrecognizedFileFormat: cout<<"OCAFApp_Appl_RBadFileFormat"<<endl; break;
56 case PCDM_RS_MakeFailure: cout<<"OCAFApp_Appl_RMakeFailure"<<endl; break;
57 case PCDM_RS_PermissionDenied: cout<<"OCAFApp_Appl_RPermissionDenied"<<endl; break;
58 case PCDM_RS_DriverFailure: cout<<"OCAFApp_Appl_RDriverFailure"<<endl; break;
59 default: cout<<"OCAFApp_Appl_RUnknownFail"<<endl; break;
62 SetUndoLimit(UNDO_LIMIT);
67 bool Model_Document::save(const char* theFileName)
69 bool myIsError = true;
71 TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
72 PCDM_StoreStatus aStatus;
74 Handle(TDocStd_Document) aDoc = this;
75 aStatus = Model_Application::GetApplication()->SaveAs (aDoc, aPath);
77 catch (Standard_Failure) {
78 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
79 cout<<"OCAFApp_Engine:save Error: "<<aFail->GetMessageString()<<endl;
82 myIsError = aStatus != PCDM_SS_OK;
87 case PCDM_SS_DriverFailure:
88 cout<<"OCAFApp_Appl_SDriverFailure"<<endl;
90 case PCDM_SS_WriteFailure:
91 cout<<"OCAFApp_Appl_SWriteFailure"<<endl;
95 cout<<"OCAFApp_Appl_SUnknownFailure"<<endl;
99 myTransactionsAfterSave = 0;
100 Standard::Purge(); // Release free memory
105 void Model_Document::close()
108 set<string>::iterator aSubIter = mySubs.begin();
109 for(; aSubIter != mySubs.end(); aSubIter++)
110 subDocument(*aSubIter)->close();
114 Model_Application::getApplication()->deleteDocument(myID);
117 void Model_Document::startOperation()
119 // new command for this
121 // new command for all subs
122 set<string>::iterator aSubIter = mySubs.begin();
123 for(; aSubIter != mySubs.end(); aSubIter++)
124 subDocument(*aSubIter)->startOperation();
127 void Model_Document::finishOperation()
129 // returns false if delta is empty and no transaction was made
130 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
131 myTransactionsAfterSave++;
132 // finish for all subs
133 set<string>::iterator aSubIter = mySubs.begin();
134 for(; aSubIter != mySubs.end(); aSubIter++)
135 subDocument(*aSubIter)->finishOperation();
138 void Model_Document::abortOperation()
140 myDoc->AbortCommand();
141 // abort for all subs
142 set<string>::iterator aSubIter = mySubs.begin();
143 for(; aSubIter != mySubs.end(); aSubIter++)
144 subDocument(*aSubIter)->abortOperation();
147 bool Model_Document::isOperation()
149 // operation is opened for all documents: no need to check subs
150 return myDoc->HasOpenCommand() == Standard_True ;
153 bool Model_Document::isModified()
155 // is modified if at least one operation was commited and not undoed
156 return myTransactionsAfterSave > 0;
159 bool Model_Document::canUndo()
161 if (myDoc->GetAvailableUndos() > 0)
163 // check other subs contains operation that can be undoed
164 set<string>::iterator aSubIter = mySubs.begin();
165 for(; aSubIter != mySubs.end(); aSubIter++)
166 if (subDocument(*aSubIter)->canUndo())
171 void Model_Document::undo()
173 myTransactionsAfterSave--;
174 if (!myIsEmptyTr[myTransactionsAfterSave])
176 synchronizeFeatures();
178 set<string>::iterator aSubIter = mySubs.begin();
179 for(; aSubIter != mySubs.end(); aSubIter++)
180 subDocument(*aSubIter)->undo();
183 bool Model_Document::canRedo()
185 if (myDoc->GetAvailableRedos() > 0)
187 // check other subs contains operation that can be redoed
188 set<string>::iterator aSubIter = mySubs.begin();
189 for(; aSubIter != mySubs.end(); aSubIter++)
190 if (subDocument(*aSubIter)->canRedo())
195 void Model_Document::redo()
197 if (!myIsEmptyTr[myTransactionsAfterSave])
199 myTransactionsAfterSave++;
200 synchronizeFeatures();
202 set<string>::iterator aSubIter = mySubs.begin();
203 for(; aSubIter != mySubs.end(); aSubIter++)
204 subDocument(*aSubIter)->redo();
207 shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
209 shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(theID);
211 dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
213 // TODO: generate error that feature is not created
218 void Model_Document::addFeature(const std::shared_ptr<ModelAPI_Feature> theFeature)
220 const std::string& aGroup = theFeature->getGroup();
221 TDF_Label aGroupLab = groupLabel(aGroup);
222 TDF_Label anObjLab = aGroupLab.NewChild();
223 std::shared_ptr<Model_Data> aData(new Model_Data);
224 aData->setLabel(anObjLab);
225 shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
226 aData->setDocument(aThis);
227 theFeature->setData(aData);
228 setUniqueName(theFeature);
229 theFeature->initAttributes();
230 // keep the feature ID to restore document later correctly
231 TDataStd_Comment::Set(anObjLab, theFeature->getKind().c_str());
232 // put index of the feature in the group in the tree
233 TDataStd_Integer::Set(anObjLab, myFeatures[aGroup].size());
234 myFeatures[aGroup].push_back(theFeature);
236 // event: feature is added
237 static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
238 ModelAPI_FeatureUpdatedMessage aMsg(aThis, theFeature, anEvent);
239 Event_Loop::loop()->send(aMsg);
242 shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
244 Handle(TDataStd_Integer) aFeatureIndex;
245 if (theLabel.FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
246 Handle(TDataStd_Comment) aGroupID;
247 if (theLabel.Father().FindAttribute(TDataStd_Comment::GetID(), aGroupID)) {
248 string aGroup = TCollection_AsciiString(aGroupID->Get()).ToCString();
249 return myFeatures[aGroup][aFeatureIndex->Get()];
252 return std::shared_ptr<ModelAPI_Feature>(); // not found
255 int Model_Document::featureIndex(shared_ptr<ModelAPI_Feature> theFeature)
257 if (theFeature->data()->document().get() != this) {
258 return theFeature->data()->document()->featureIndex(theFeature);
260 shared_ptr<Model_Data> aData = dynamic_pointer_cast<Model_Data>(theFeature->data());
261 Handle(TDataStd_Integer) aFeatureIndex;
262 if (aData->label().FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
263 return aFeatureIndex->Get();
265 return -1; // not found
268 shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
270 // just store sub-document identifier here to manage it later
271 if (mySubs.find(theDocID) == mySubs.end())
272 mySubs.insert(theDocID);
273 return Model_Application::getApplication()->getDocument(theDocID);
276 shared_ptr<ModelAPI_Iterator> Model_Document::featuresIterator(const string theGroup)
278 shared_ptr<Model_Document> aThis(Model_Application::getApplication()->getDocument(myID));
279 // create an empty iterator for not existing group
280 // (to avoidance of attributes management outside the transaction)
281 if (myGroups.find(theGroup) == myGroups.end())
282 return shared_ptr<ModelAPI_Iterator>(new Model_Iterator());
283 return shared_ptr<ModelAPI_Iterator>(new Model_Iterator(aThis, groupLabel(theGroup)));
286 shared_ptr<ModelAPI_Feature> Model_Document::feature(const string& theGroupID, const int theIndex)
288 // TODO: optimize this method
289 shared_ptr<ModelAPI_Iterator> anIter = featuresIterator(theGroupID);
290 for(int a = 0; a != theIndex && anIter->more(); anIter->next()) a++;
291 return anIter->more() ? anIter->current() : shared_ptr<ModelAPI_Feature>();
294 const vector<string>& Model_Document::getGroups() const
296 return myGroupsNames;
299 Model_Document::Model_Document(const std::string theID)
300 : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
302 myDoc->SetUndoLimit(UNDO_LIMIT);
303 myTransactionsAfterSave = 0;
304 // to avoid creation of tag outside of the transaction (by iterator, for example)
306 if (!myDoc->Main().FindChild(TAG_OBJECTS).IsAttribute(TDF_TagSource::GetID()))
307 TDataStd_Comment::Set(myDoc->Main().FindChild(TAG_OBJECTS).NewChild(), "");
311 TDF_Label Model_Document::groupLabel(const string theGroup)
313 if (myGroups.find(theGroup) == myGroups.end()) {
314 myGroups[theGroup] = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
315 myGroupsNames.push_back(theGroup);
316 // set to the group label the group idntifier to restore on "open"
317 TDataStd_Comment::Set(myGroups[theGroup], theGroup.c_str());
318 myFeatures[theGroup] = vector<shared_ptr<ModelAPI_Feature> >();
320 return myGroups[theGroup];
323 void Model_Document::setUniqueName(
324 shared_ptr<ModelAPI_Feature> theFeature)
326 // first count all objects of such kind to start with index = count + 1
328 shared_ptr<ModelAPI_Iterator> anIter = featuresIterator(theFeature->getGroup());
329 for(; anIter->more(); anIter->next()) {
330 if (anIter->currentKind() == theFeature->getKind())
333 // generate candidate name
334 stringstream aNameStream;
335 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
336 string aName = aNameStream.str();
337 // check this is unique, if not, increase index by 1
338 for(anIter = featuresIterator(theFeature->getGroup()); anIter->more();) {
339 if (anIter->currentName() == aName) {
341 stringstream aNameStream;
342 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
343 // reinitialize iterator to make sure a new name is unique
344 anIter = featuresIterator(theFeature->getGroup());
345 } else anIter->next();
348 theFeature->data()->setName(aName);
351 void Model_Document::synchronizeFeatures()
353 shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
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
365 // delete all groups left after the data model groups iteration
366 while(aGroupNamesIter != myGroupsNames.end()) {
367 string aGroupName = *aGroupNamesIter;
368 myFeatures.erase(aGroupName);
369 myGroups.erase(aGroupName);
370 aGroupNamesIter = myGroupsNames.erase(aGroupNamesIter);
371 // say that features were deleted from group
372 ModelAPI_FeatureDeletedMessage aMsg(aThis, aGroupName);
373 Event_Loop::loop()->send(aMsg);
375 // create new groups basing on the following data model update
376 for(; aGroupsIter.More(); aGroupsIter.Next()) {
377 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
378 aGroupsIter.Value())->Get()).ToCString();
379 myGroupsNames.push_back(aGroupName);
380 myGroups[aGroupName] = aGroupsIter.Value()->Label();
381 myFeatures[aGroupName] = vector<shared_ptr<ModelAPI_Feature> >();
383 // update features group by group
384 aGroupsIter.Initialize(myDoc->Main().FindChild(TAG_OBJECTS),
385 TDataStd_Comment::GetID(), Standard_False);
386 for(; aGroupsIter.More(); aGroupsIter.Next()) {
387 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
388 aGroupsIter.Value())->Get()).ToCString();
389 // iterate features in internal container
390 vector<shared_ptr<ModelAPI_Feature> >& aFeatures = myFeatures[aGroupName];
391 vector<shared_ptr<ModelAPI_Feature> >::iterator aFIter = aFeatures.begin();
392 // and in parallel iterate labels of features
393 TDF_ChildIDIterator aFLabIter(
394 aGroupsIter.Value()->Label(), TDataStd_Comment::GetID(), Standard_False);
395 while(aFIter != aFeatures.end() || aFLabIter.More()) {
396 static const int INFINITE_TAG = MAXINT; // no label means that it exists somwhere in infinite
397 int aFeatureTag = INFINITE_TAG;
398 if (aFIter != aFeatures.end()) { // existing tag for feature
399 shared_ptr<Model_Data> aData = dynamic_pointer_cast<Model_Data>((*aFIter)->data());
400 aFeatureTag = aData->label().Tag();
402 int aDSTag = INFINITE_TAG;
403 if (aFLabIter.More()) { // next label in DS is existing
404 aDSTag = aFLabIter.Value()->Label().Tag();
406 if (aDSTag > aFeatureTag) { // feature is removed
407 aFIter = aFeatures.erase(aFIter);
408 // event: model is updated
409 ModelAPI_FeatureDeletedMessage aMsg(aThis, aGroupName);
410 Event_Loop::loop()->send(aMsg);
411 } else if (aDSTag < aFeatureTag) { // a new feature is inserted
413 shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
414 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
415 aFLabIter.Value())->Get()).ToCString());
417 std::shared_ptr<Model_Data> aData(new Model_Data);
418 TDF_Label aLab = aFLabIter.Value()->Label();
419 aData->setLabel(aLab);
420 aData->setDocument(Model_Application::getApplication()->getDocument(myID));
421 aFeature->setData(aData);
422 aFeature->initAttributes();
423 // event: model is updated
424 static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
425 ModelAPI_FeatureUpdatedMessage aMsg(aThis, aFeature, anEvent);
426 Event_Loop::loop()->send(aMsg);
428 if (aFIter == aFeatures.end()) {
429 aFeatures.push_back(aFeature);
430 aFIter = aFeatures.end();
433 aFeatures.insert(aFIter, aFeature);
435 // feature for this label is added, so go to the next label
437 } else { // nothing is changed, both iterators are incremented