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>
20 static const int UNDO_LIMIT = 10; // number of possible undo operations
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)
28 bool Model_Document::load(const char* theFileName)
30 bool myIsError = Standard_False;
32 TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
33 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
36 Handle(TDocStd_Document) aDoc = this;
37 aStatus = Model_Application::GetApplication()->Open(aPath, aDoc);
39 catch (Standard_Failure)
41 myIsError = aStatus != PCDM_RS_OK;
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;
64 SetUndoLimit(UNDO_LIMIT);
69 bool Model_Document::save(const char* theFileName)
71 bool myIsError = true;
73 TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
74 PCDM_StoreStatus aStatus;
76 Handle(TDocStd_Document) aDoc = this;
77 aStatus = Model_Application::GetApplication()->SaveAs (aDoc, aPath);
79 catch (Standard_Failure) {
80 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
81 cout<<"OCAFApp_Engine:save Error: "<<aFail->GetMessageString()<<endl;
84 myIsError = aStatus != PCDM_SS_OK;
89 case PCDM_SS_DriverFailure:
90 cout<<"OCAFApp_Appl_SDriverFailure"<<endl;
92 case PCDM_SS_WriteFailure:
93 cout<<"OCAFApp_Appl_SWriteFailure"<<endl;
97 cout<<"OCAFApp_Appl_SUnknownFailure"<<endl;
101 myTransactionsAfterSave = 0;
102 Standard::Purge(); // Release free memory
107 void Model_Document::close()
110 set<string>::iterator aSubIter = mySubs.begin();
111 for(; aSubIter != mySubs.end(); aSubIter++)
112 subDocument(*aSubIter)->close();
116 Model_Application::getApplication()->deleteDocument(myID);
119 void Model_Document::startOperation()
121 // new command for this
123 // new command for all subs
124 set<string>::iterator aSubIter = mySubs.begin();
125 for(; aSubIter != mySubs.end(); aSubIter++)
126 subDocument(*aSubIter)->startOperation();
129 void Model_Document::finishOperation()
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();
140 void Model_Document::abortOperation()
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();
149 bool Model_Document::isOperation()
151 // operation is opened for all documents: no need to check subs
152 return myDoc->HasOpenCommand() == Standard_True ;
155 bool Model_Document::isModified()
157 // is modified if at least one operation was commited and not undoed
158 return myTransactionsAfterSave > 0;
161 bool Model_Document::canUndo()
163 if (myDoc->GetAvailableUndos() > 0)
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())
173 void Model_Document::undo()
175 myTransactionsAfterSave--;
176 if (!myIsEmptyTr[myTransactionsAfterSave])
178 synchronizeFeatures();
180 set<string>::iterator aSubIter = mySubs.begin();
181 for(; aSubIter != mySubs.end(); aSubIter++)
182 subDocument(*aSubIter)->undo();
185 bool Model_Document::canRedo()
187 if (myDoc->GetAvailableRedos() > 0)
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())
197 void Model_Document::redo()
199 if (!myIsEmptyTr[myTransactionsAfterSave])
201 myTransactionsAfterSave++;
202 synchronizeFeatures();
204 set<string>::iterator aSubIter = mySubs.begin();
205 for(; aSubIter != mySubs.end(); aSubIter++)
206 subDocument(*aSubIter)->redo();
209 shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
211 shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(theID);
213 dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
215 // TODO: generate error that feature is not created
220 void Model_Document::addFeature(const std::shared_ptr<ModelAPI_Feature> theFeature)
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 shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
228 aData->setDocument(aThis);
229 theFeature->setData(aData);
230 setUniqueName(theFeature);
231 theFeature->initAttributes();
232 // keep the feature ID to restore document later correctly
233 TDataStd_Comment::Set(anObjLab, theFeature->getKind().c_str());
234 // put index of the feature in the group in the tree
235 TDataStd_Integer::Set(anObjLab, myFeatures[aGroup].size());
236 myFeatures[aGroup].push_back(theFeature);
238 // event: feature is added
239 static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
240 ModelAPI_FeatureUpdatedMessage aMsg(aThis, theFeature, anEvent);
241 Event_Loop::loop()->send(aMsg);
244 shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
246 Handle(TDataStd_Integer) aFeatureIndex;
247 if (theLabel.FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
248 Handle(TDataStd_Comment) aGroupID;
249 if (theLabel.Father().FindAttribute(TDataStd_Comment::GetID(), aGroupID)) {
250 string aGroup = TCollection_AsciiString(aGroupID->Get()).ToCString();
251 return myFeatures[aGroup][aFeatureIndex->Get()];
254 return std::shared_ptr<ModelAPI_Feature>(); // not found
257 int Model_Document::featureIndex(shared_ptr<ModelAPI_Feature> theFeature)
259 if (theFeature->data()->document().get() != this) {
260 return theFeature->data()->document()->featureIndex(theFeature);
262 shared_ptr<Model_Data> aData = dynamic_pointer_cast<Model_Data>(theFeature->data());
263 Handle(TDataStd_Integer) aFeatureIndex;
264 if (aData->label().FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
265 return aFeatureIndex->Get();
267 return -1; // not found
270 shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
272 // just store sub-document identifier here to manage it later
273 if (mySubs.find(theDocID) == mySubs.end())
274 mySubs.insert(theDocID);
275 return Model_Application::getApplication()->getDocument(theDocID);
278 shared_ptr<ModelAPI_Iterator> Model_Document::featuresIterator(const string theGroup)
280 shared_ptr<Model_Document> aThis(Model_Application::getApplication()->getDocument(myID));
281 // create an empty iterator for not existing group
282 // (to avoidance of attributes management outside the transaction)
283 if (myGroups.find(theGroup) == myGroups.end())
284 return shared_ptr<ModelAPI_Iterator>(new Model_Iterator());
285 return shared_ptr<ModelAPI_Iterator>(new Model_Iterator(aThis, groupLabel(theGroup)));
288 shared_ptr<ModelAPI_Feature> Model_Document::feature(const string& theGroupID, const int theIndex)
290 // TODO: optimize this method
291 shared_ptr<ModelAPI_Iterator> anIter = featuresIterator(theGroupID);
292 for(int a = 0; a != theIndex && anIter->more(); anIter->next()) a++;
293 return anIter->more() ? anIter->current() : shared_ptr<ModelAPI_Feature>();
296 const vector<string>& Model_Document::getGroups() const
298 return myGroupsNames;
301 Model_Document::Model_Document(const std::string theID)
302 : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
304 myDoc->SetUndoLimit(UNDO_LIMIT);
305 myTransactionsAfterSave = 0;
306 // to avoid creation of tag outside of the transaction (by iterator, for example)
308 if (!myDoc->Main().FindChild(TAG_OBJECTS).IsAttribute(TDF_TagSource::GetID()))
309 TDataStd_Comment::Set(myDoc->Main().FindChild(TAG_OBJECTS).NewChild(), "");
313 TDF_Label Model_Document::groupLabel(const string theGroup)
315 if (myGroups.find(theGroup) == myGroups.end()) {
316 myGroups[theGroup] = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
317 myGroupsNames.push_back(theGroup);
318 // set to the group label the group idntifier to restore on "open"
319 TDataStd_Comment::Set(myGroups[theGroup], theGroup.c_str());
320 myFeatures[theGroup] = vector<shared_ptr<ModelAPI_Feature> >();
322 return myGroups[theGroup];
325 void Model_Document::setUniqueName(
326 shared_ptr<ModelAPI_Feature> theFeature)
328 // first count all objects of such kind to start with index = count + 1
330 shared_ptr<ModelAPI_Iterator> anIter = featuresIterator(theFeature->getGroup());
331 for(; anIter->more(); anIter->next()) {
332 if (anIter->currentKind() == theFeature->getKind())
335 // generate candidate name
336 stringstream aNameStream;
337 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
338 string aName = aNameStream.str();
339 // check this is unique, if not, increase index by 1
340 for(anIter = featuresIterator(theFeature->getGroup()); anIter->more();) {
341 if (anIter->currentName() == aName) {
343 stringstream aNameStream;
344 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
345 // reinitialize iterator to make sure a new name is unique
346 anIter = featuresIterator(theFeature->getGroup());
347 } else anIter->next();
350 theFeature->data()->setName(aName);
353 void Model_Document::synchronizeFeatures()
355 shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
356 // iterate groups labels
357 TDF_ChildIDIterator aGroupsIter(myDoc->Main().FindChild(TAG_OBJECTS),
358 TDataStd_Comment::GetID(), Standard_False);
359 vector<string>::iterator aGroupNamesIter = myGroupsNames.begin();
360 for(; aGroupsIter.More() && aGroupNamesIter != myGroupsNames.end();
361 aGroupsIter.Next(), aGroupNamesIter++) {
362 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
363 aGroupsIter.Value())->Get()).ToCString();
364 if (*aGroupNamesIter != aGroupName)
365 break; // all since there is a change this must be recreated from scratch
367 // delete all groups left after the data model groups iteration
368 while(aGroupNamesIter != myGroupsNames.end()) {
369 string aGroupName = *aGroupNamesIter;
370 myFeatures.erase(aGroupName);
371 myGroups.erase(aGroupName);
372 aGroupNamesIter = myGroupsNames.erase(aGroupNamesIter);
373 // say that features were deleted from group
374 ModelAPI_FeatureDeletedMessage aMsg(aThis, aGroupName);
375 Event_Loop::loop()->send(aMsg);
377 // create new groups basing on the following data model update
378 for(; aGroupsIter.More(); aGroupsIter.Next()) {
379 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
380 aGroupsIter.Value())->Get()).ToCString();
381 myGroupsNames.push_back(aGroupName);
382 myGroups[aGroupName] = aGroupsIter.Value()->Label();
383 myFeatures[aGroupName] = vector<shared_ptr<ModelAPI_Feature> >();
385 // update features group by group
386 aGroupsIter.Initialize(myDoc->Main().FindChild(TAG_OBJECTS),
387 TDataStd_Comment::GetID(), Standard_False);
388 for(; aGroupsIter.More(); aGroupsIter.Next()) {
389 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
390 aGroupsIter.Value())->Get()).ToCString();
391 // iterate features in internal container
392 vector<shared_ptr<ModelAPI_Feature> >& aFeatures = myFeatures[aGroupName];
393 vector<shared_ptr<ModelAPI_Feature> >::iterator aFIter = aFeatures.begin();
394 // and in parallel iterate labels of features
395 TDF_ChildIDIterator aFLabIter(
396 aGroupsIter.Value()->Label(), TDataStd_Comment::GetID(), Standard_False);
397 while(aFIter != aFeatures.end() || aFLabIter.More()) {
398 static const int INFINITE_TAG = INT_MAX; // no label means that it exists somwhere in infinite
399 int aFeatureTag = INFINITE_TAG;
400 if (aFIter != aFeatures.end()) { // existing tag for feature
401 shared_ptr<Model_Data> aData = dynamic_pointer_cast<Model_Data>((*aFIter)->data());
402 aFeatureTag = aData->label().Tag();
404 int aDSTag = INFINITE_TAG;
405 if (aFLabIter.More()) { // next label in DS is existing
406 aDSTag = aFLabIter.Value()->Label().Tag();
408 if (aDSTag > aFeatureTag) { // feature is removed
409 aFIter = aFeatures.erase(aFIter);
410 // event: model is updated
411 ModelAPI_FeatureDeletedMessage aMsg(aThis, aGroupName);
412 Event_Loop::loop()->send(aMsg);
413 } else if (aDSTag < aFeatureTag) { // a new feature is inserted
415 shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
416 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
417 aFLabIter.Value())->Get()).ToCString());
419 std::shared_ptr<Model_Data> aData(new Model_Data);
420 TDF_Label aLab = aFLabIter.Value()->Label();
421 aData->setLabel(aLab);
422 aData->setDocument(Model_Application::getApplication()->getDocument(myID));
423 aFeature->setData(aData);
424 aFeature->initAttributes();
425 // event: model is updated
426 static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
427 ModelAPI_FeatureUpdatedMessage aMsg(aThis, aFeature, anEvent);
428 Event_Loop::loop()->send(aMsg);
430 if (aFIter == aFeatures.end()) {
431 aFeatures.push_back(aFeature);
432 aFIter = aFeatures.end();
435 aFeatures.insert(aFIter, aFeature);
437 // feature for this label is added, so go to the next label
439 } else { // nothing is changed, both iterators are incremented