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 aData->setDocument(Model_Application::getApplication()->getDocument(myID));
226 theFeature->setData(aData);
227 setUniqueName(theFeature);
228 theFeature->initAttributes();
229 // keep the feature ID to restore document later correctly
230 TDataStd_Comment::Set(anObjLab, theFeature->getKind().c_str());
231 // put index of the feature in the group in the tree
232 TDataStd_Integer::Set(anObjLab, myFeatures[aGroup].size());
233 myFeatures[aGroup].push_back(theFeature);
235 // event: feature is added
236 static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
237 ModelAPI_FeatureUpdatedMessage aMsg(theFeature, anEvent);
238 Event_Loop::loop()->send(aMsg);
241 shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
243 Handle(TDataStd_Integer) aFeatureIndex;
244 if (theLabel.FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
245 Handle(TDataStd_Comment) aGroupID;
246 if (theLabel.Father().FindAttribute(TDataStd_Comment::GetID(), aGroupID)) {
247 string aGroup = TCollection_AsciiString(aGroupID->Get()).ToCString();
248 return myFeatures[aGroup][aFeatureIndex->Get()];
251 return std::shared_ptr<ModelAPI_Feature>(); // not found
254 int Model_Document::featureIndex(shared_ptr<ModelAPI_Feature> theFeature)
256 if (theFeature->data()->document().get() != this) {
257 return theFeature->data()->document()->featureIndex(theFeature);
259 shared_ptr<Model_Data> aData = dynamic_pointer_cast<Model_Data>(theFeature->data());
260 Handle(TDataStd_Integer) aFeatureIndex;
261 if (aData->label().FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
262 return aFeatureIndex->Get();
264 return -1; // not found
267 shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
269 // just store sub-document identifier here to manage it later
270 if (mySubs.find(theDocID) == mySubs.end())
271 mySubs.insert(theDocID);
272 return Model_Application::getApplication()->getDocument(theDocID);
275 shared_ptr<ModelAPI_Iterator> Model_Document::featuresIterator(const string theGroup)
277 shared_ptr<Model_Document> aThis(Model_Application::getApplication()->getDocument(myID));
278 // create an empty iterator for not existing group
279 // (to avoidance of attributes management outside the transaction)
280 if (myGroups.find(theGroup) == myGroups.end())
281 return shared_ptr<ModelAPI_Iterator>(new Model_Iterator());
282 return shared_ptr<ModelAPI_Iterator>(new Model_Iterator(aThis, groupLabel(theGroup)));
285 shared_ptr<ModelAPI_Feature> Model_Document::feature(const string& theGroupID, const int theIndex)
287 // TODO: optimize this method
288 shared_ptr<ModelAPI_Iterator> anIter = featuresIterator(theGroupID);
289 for(int a = 0; a != theIndex && anIter->more(); anIter->next()) a++;
290 return anIter->more() ? anIter->current() : shared_ptr<ModelAPI_Feature>();
293 const vector<string>& Model_Document::getGroups() const
295 return myGroupsNames;
298 Model_Document::Model_Document(const std::string theID)
299 : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
301 myDoc->SetUndoLimit(UNDO_LIMIT);
302 myTransactionsAfterSave = 0;
303 // to avoid creation of tag outside of the transaction (by iterator, for example)
305 if (!myDoc->Main().FindChild(TAG_OBJECTS).IsAttribute(TDF_TagSource::GetID()))
306 TDataStd_Comment::Set(myDoc->Main().FindChild(TAG_OBJECTS).NewChild(), "");
310 TDF_Label Model_Document::groupLabel(const string theGroup)
312 if (myGroups.find(theGroup) == myGroups.end()) {
313 myGroups[theGroup] = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
314 myGroupsNames.push_back(theGroup);
315 // set to the group label the group idntifier to restore on "open"
316 TDataStd_Comment::Set(myGroups[theGroup], theGroup.c_str());
317 myFeatures[theGroup] = vector<shared_ptr<ModelAPI_Feature> >();
319 return myGroups[theGroup];
322 void Model_Document::setUniqueName(
323 shared_ptr<ModelAPI_Feature> theFeature)
325 // first count all objects of such kind to start with index = count + 1
327 shared_ptr<ModelAPI_Iterator> anIter = featuresIterator(theFeature->getGroup());
328 for(; anIter->more(); anIter->next()) {
329 if (anIter->currentKind() == theFeature->getKind())
332 // generate candidate name
333 stringstream aNameStream;
334 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
335 string aName = aNameStream.str();
336 // check this is unique, if not, increase index by 1
337 for(anIter = featuresIterator(theFeature->getGroup()); anIter->more();) {
338 if (anIter->currentName() == aName) {
340 stringstream aNameStream;
341 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
342 // reinitialize iterator to make sure a new name is unique
343 anIter = featuresIterator(theFeature->getGroup());
344 } else anIter->next();
347 theFeature->data()->setName(aName);
350 void Model_Document::synchronizeFeatures()
352 // iterate groups labels
353 TDF_ChildIDIterator aGroupsIter(myDoc->Main().FindChild(TAG_OBJECTS),
354 TDataStd_Comment::GetID(), Standard_False);
355 vector<string>::iterator aGroupNamesIter = myGroupsNames.begin();
356 for(; aGroupsIter.More() && aGroupNamesIter != myGroupsNames.end();
357 aGroupsIter.Next(), aGroupNamesIter++) {
358 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
359 aGroupsIter.Value())->Get()).ToCString();
360 if (*aGroupNamesIter != aGroupName)
361 break; // all since there is a change this must be recreated from scratch
363 // delete all groups left after the data model groups iteration
364 while(aGroupNamesIter != myGroupsNames.end()) {
365 myFeatures.erase(*aGroupNamesIter);
366 myGroups.erase(*aGroupNamesIter);
367 aGroupNamesIter = myGroupsNames.erase(aGroupNamesIter);
369 // create new groups basing on the following data model update
370 for(; aGroupsIter.More(); aGroupsIter.Next()) {
371 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
372 aGroupsIter.Value())->Get()).ToCString();
373 myGroupsNames.push_back(aGroupName);
374 myGroups[aGroupName] = aGroupsIter.Value()->Label();
375 myFeatures[aGroupName] = vector<shared_ptr<ModelAPI_Feature> >();
377 // update features group by group
378 aGroupsIter.Initialize(myDoc->Main().FindChild(TAG_OBJECTS),
379 TDataStd_Comment::GetID(), Standard_False);
380 for(; aGroupsIter.More(); aGroupsIter.Next()) {
381 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
382 aGroupsIter.Value())->Get()).ToCString();
383 // iterate features in internal container
384 vector<shared_ptr<ModelAPI_Feature> >& aFeatures = myFeatures[aGroupName];
385 vector<shared_ptr<ModelAPI_Feature> >::iterator aFIter = aFeatures.begin();
386 // and in parallel iterate labels of features
387 TDF_ChildIDIterator aFLabIter(
388 aGroupsIter.Value()->Label(), TDataStd_Comment::GetID(), Standard_False);
389 while(aFIter != aFeatures.end() || aFLabIter.More()) {
390 static const int INFINITE_TAG = MAXINT; // no label means that it exists somwhere in infinite
391 int aFeatureTag = INFINITE_TAG;
392 if (aFIter != aFeatures.end()) { // existing tag for feature
393 shared_ptr<Model_Data> aData = dynamic_pointer_cast<Model_Data>((*aFIter)->data());
394 aFeatureTag = aData->label().Tag();
396 int aDSTag = INFINITE_TAG;
397 if (aFLabIter.More()) { // next label in DS is existing
398 aDSTag = aFLabIter.Value()->Label().Tag();
400 if (aDSTag > aFeatureTag) { // feature is removed
401 aFIter = aFeatures.erase(aFIter);
402 // event: model is updated
403 ModelAPI_FeatureDeletedMessage aMsg(
404 Model_Application::getApplication()->getDocument(myID), aGroupName);
405 Event_Loop::loop()->send(aMsg);
406 } else if (aDSTag < aFeatureTag) { // a new feature is inserted
408 shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
409 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
410 aFLabIter.Value())->Get()).ToCString());
412 std::shared_ptr<Model_Data> aData(new Model_Data);
413 TDF_Label aLab = aFLabIter.Value()->Label();
414 aData->setLabel(aLab);
415 aData->setDocument(Model_Application::getApplication()->getDocument(myID));
416 aFeature->setData(aData);
417 aFeature->initAttributes();
418 // event: model is updated
419 static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
420 ModelAPI_FeatureUpdatedMessage aMsg(aFeature, anEvent);
421 Event_Loop::loop()->send(aMsg);
423 if (aFIter == aFeatures.end()) {
424 aFeatures.push_back(aFeature);
425 aFIter = aFeatures.end();
428 aFeatures.insert(aFIter, aFeature);
430 // feature for this label is added, so go to the next label
432 } else { // nothing is changed, both iterators are incremented