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 aData->setDocument(Model_Application::getApplication()->getDocument(myID));
228 theFeature->setData(aData);
229 setUniqueName(theFeature);
230 theFeature->initAttributes();
231 // keep the feature ID to restore document later correctly
232 TDataStd_Comment::Set(anObjLab, theFeature->getKind().c_str());
233 // put index of the feature in the group in the tree
234 TDataStd_Integer::Set(anObjLab, myFeatures[aGroup].size());
235 myFeatures[aGroup].push_back(theFeature);
237 // event: feature is added
238 static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
239 ModelAPI_FeatureUpdatedMessage aMsg(theFeature, anEvent);
240 Event_Loop::loop()->send(aMsg);
243 shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
245 Handle(TDataStd_Integer) aFeatureIndex;
246 if (theLabel.FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
247 Handle(TDataStd_Comment) aGroupID;
248 if (theLabel.Father().FindAttribute(TDataStd_Comment::GetID(), aGroupID)) {
249 string aGroup = TCollection_AsciiString(aGroupID->Get()).ToCString();
250 return myFeatures[aGroup][aFeatureIndex->Get()];
253 return std::shared_ptr<ModelAPI_Feature>(); // not found
256 int Model_Document::featureIndex(shared_ptr<ModelAPI_Feature> theFeature)
258 if (theFeature->data()->document().get() != this) {
259 return theFeature->data()->document()->featureIndex(theFeature);
261 shared_ptr<Model_Data> aData = dynamic_pointer_cast<Model_Data>(theFeature->data());
262 Handle(TDataStd_Integer) aFeatureIndex;
263 if (aData->label().FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
264 return aFeatureIndex->Get();
266 return -1; // not found
269 shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
271 // just store sub-document identifier here to manage it later
272 if (mySubs.find(theDocID) == mySubs.end())
273 mySubs.insert(theDocID);
274 return Model_Application::getApplication()->getDocument(theDocID);
277 shared_ptr<ModelAPI_Iterator> Model_Document::featuresIterator(const string theGroup)
279 shared_ptr<Model_Document> aThis(Model_Application::getApplication()->getDocument(myID));
280 // create an empty iterator for not existing group
281 // (to avoidance of attributes management outside the transaction)
282 if (myGroups.find(theGroup) == myGroups.end())
283 return shared_ptr<ModelAPI_Iterator>(new Model_Iterator());
284 return shared_ptr<ModelAPI_Iterator>(new Model_Iterator(aThis, groupLabel(theGroup)));
287 shared_ptr<ModelAPI_Feature> Model_Document::feature(const string& theGroupID, const int theIndex)
289 // TODO: optimize this method
290 shared_ptr<ModelAPI_Iterator> anIter = featuresIterator(theGroupID);
291 for(int a = 0; a != theIndex && anIter->more(); anIter->next()) a++;
292 return anIter->more() ? anIter->current() : shared_ptr<ModelAPI_Feature>();
295 const vector<string>& Model_Document::getGroups() const
297 return myGroupsNames;
300 Model_Document::Model_Document(const std::string theID)
301 : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
303 myDoc->SetUndoLimit(UNDO_LIMIT);
304 myTransactionsAfterSave = 0;
305 // to avoid creation of tag outside of the transaction (by iterator, for example)
307 if (!myDoc->Main().FindChild(TAG_OBJECTS).IsAttribute(TDF_TagSource::GetID()))
308 TDataStd_Comment::Set(myDoc->Main().FindChild(TAG_OBJECTS).NewChild(), "");
312 TDF_Label Model_Document::groupLabel(const string theGroup)
314 if (myGroups.find(theGroup) == myGroups.end()) {
315 myGroups[theGroup] = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
316 myGroupsNames.push_back(theGroup);
317 // set to the group label the group idntifier to restore on "open"
318 TDataStd_Comment::Set(myGroups[theGroup], theGroup.c_str());
319 myFeatures[theGroup] = vector<shared_ptr<ModelAPI_Feature> >();
321 return myGroups[theGroup];
324 void Model_Document::setUniqueName(
325 shared_ptr<ModelAPI_Feature> theFeature)
327 // first count all objects of such kind to start with index = count + 1
329 shared_ptr<ModelAPI_Iterator> anIter = featuresIterator(theFeature->getGroup());
330 for(; anIter->more(); anIter->next()) {
331 if (anIter->currentKind() == theFeature->getKind())
334 // generate candidate name
335 stringstream aNameStream;
336 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
337 string aName = aNameStream.str();
338 // check this is unique, if not, increase index by 1
339 for(anIter = featuresIterator(theFeature->getGroup()); anIter->more();) {
340 if (anIter->currentName() == aName) {
342 stringstream aNameStream;
343 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
344 // reinitialize iterator to make sure a new name is unique
345 anIter = featuresIterator(theFeature->getGroup());
346 } else anIter->next();
349 theFeature->data()->setName(aName);
352 void Model_Document::synchronizeFeatures()
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 myFeatures.erase(*aGroupNamesIter);
368 myGroups.erase(*aGroupNamesIter);
369 aGroupNamesIter = myGroupsNames.erase(aGroupNamesIter);
371 // create new groups basing on the following data model update
372 for(; aGroupsIter.More(); aGroupsIter.Next()) {
373 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
374 aGroupsIter.Value())->Get()).ToCString();
375 myGroupsNames.push_back(aGroupName);
376 myGroups[aGroupName] = aGroupsIter.Value()->Label();
377 myFeatures[aGroupName] = vector<shared_ptr<ModelAPI_Feature> >();
379 // update features group by group
380 aGroupsIter.Initialize(myDoc->Main().FindChild(TAG_OBJECTS),
381 TDataStd_Comment::GetID(), Standard_False);
382 for(; aGroupsIter.More(); aGroupsIter.Next()) {
383 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
384 aGroupsIter.Value())->Get()).ToCString();
385 // iterate features in internal container
386 vector<shared_ptr<ModelAPI_Feature> >& aFeatures = myFeatures[aGroupName];
387 vector<shared_ptr<ModelAPI_Feature> >::iterator aFIter = aFeatures.begin();
388 // and in parallel iterate labels of features
389 TDF_ChildIDIterator aFLabIter(
390 aGroupsIter.Value()->Label(), TDataStd_Comment::GetID(), Standard_False);
391 while(aFIter != aFeatures.end() || aFLabIter.More()) {
392 static const int INFINITE_TAG = INT_MAX; // no label means that it exists somwhere in infinite
393 int aFeatureTag = INFINITE_TAG;
394 if (aFIter != aFeatures.end()) { // existing tag for feature
395 shared_ptr<Model_Data> aData = dynamic_pointer_cast<Model_Data>((*aFIter)->data());
396 aFeatureTag = aData->label().Tag();
398 int aDSTag = INFINITE_TAG;
399 if (aFLabIter.More()) { // next label in DS is existing
400 aDSTag = aFLabIter.Value()->Label().Tag();
402 if (aDSTag > aFeatureTag) { // feature is removed
403 aFIter = aFeatures.erase(aFIter);
404 // event: model is updated
405 ModelAPI_FeatureDeletedMessage aMsg(
406 Model_Application::getApplication()->getDocument(myID), aGroupName);
407 Event_Loop::loop()->send(aMsg);
408 } else if (aDSTag < aFeatureTag) { // a new feature is inserted
410 shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
411 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
412 aFLabIter.Value())->Get()).ToCString());
414 std::shared_ptr<Model_Data> aData(new Model_Data);
415 TDF_Label aLab = aFLabIter.Value()->Label();
416 aData->setLabel(aLab);
417 aData->setDocument(Model_Application::getApplication()->getDocument(myID));
418 aFeature->setData(aData);
419 aFeature->initAttributes();
420 // event: model is updated
421 static Event_ID anEvent = Event_Loop::eventByName(EVENT_FEATURE_CREATED);
422 ModelAPI_FeatureUpdatedMessage aMsg(aFeature, anEvent);
423 Event_Loop::loop()->send(aMsg);
425 if (aFIter == aFeatures.end()) {
426 aFeatures.push_back(aFeature);
427 aFIter = aFeatures.end();
430 aFeatures.insert(aFIter, aFeature);
432 // feature for this label is added, so go to the next label
434 } else { // nothing is changed, both iterators are incremented