Salome HOME
Refactoring: static constants are replaced by inline functions in:
[modules/shaper.git] / src / Model / Model_Document.cpp
1 // File:        Model_Document.cxx
2 // Created:     28 Feb 2014
3 // Author:      Mikhail PONIKAROV
4
5 #include <Model_Document.h>
6 #include <ModelAPI_Feature.h>
7 #include <Model_Data.h>
8 #include <Model_Object.h>
9 #include <Model_Application.h>
10 #include <Model_PluginManager.h>
11 #include <Model_Events.h>
12 #include <Events_Loop.h>
13 #include <Events_Error.h>
14
15 #include <TDataStd_Integer.hxx>
16 #include <TDataStd_Comment.hxx>
17 #include <TDF_ChildIDIterator.hxx>
18 #include <TDataStd_ReferenceArray.hxx>
19 #include <TDataStd_HLabelArray1.hxx>
20 #include <TDataStd_Name.hxx>
21
22 #include <climits>
23 #ifndef WIN32
24 #include <sys/stat.h>
25 #endif
26
27 #ifdef WIN32
28 # define _separator_ '\\'
29 #else
30 # define _separator_ '/'
31 #endif
32
33 static const int UNDO_LIMIT = 10; // number of possible undo operations
34
35 static const int TAG_GENERAL = 1; // general properties tag
36 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features)
37 static const int TAG_HISTORY = 3; // tag of the history sub-tree (python dump)
38
39 using namespace std;
40
41 /// Returns the file name of this document by the nameof directory and identifuer of a document
42 static TCollection_ExtendedString DocFileName(const char* theFileName, const string& theID)
43 {
44   TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
45   aPath += _separator_;
46   aPath += theID.c_str();
47   aPath += ".cbf"; // standard binary file extension
48   return aPath;
49 }
50
51 bool Model_Document::load(const char* theFileName)
52 {
53   Handle(Model_Application) anApp = Model_Application::getApplication();
54   if (this == Model_PluginManager::get()->rootDocument().get()) {
55     anApp->setLoadPath(theFileName);
56   }
57   TCollection_ExtendedString aPath (DocFileName(theFileName, myID));
58   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
59   try
60   {
61     aStatus = anApp->Open(aPath, myDoc);
62   }
63   catch (Standard_Failure)
64   {
65     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
66     Events_Error::send(string("Exception in opening of document: ") + aFail->GetMessageString());
67     return false;
68   }
69   bool isError = aStatus != PCDM_RS_OK;
70   if (isError)
71   {
72     switch (aStatus)
73     {
74     case PCDM_RS_UnknownDocument: 
75       Events_Error::send(string("Can not open document: PCDM_RS_UnknownDocument")); break;
76     case PCDM_RS_AlreadyRetrieved: 
77       Events_Error::send(string("Can not open document: PCDM_RS_AlreadyRetrieved")); break;
78     case PCDM_RS_AlreadyRetrievedAndModified:
79       Events_Error::send(string("Can not open document: PCDM_RS_AlreadyRetrievedAndModified")); break;
80     case PCDM_RS_NoDriver:
81       Events_Error::send(string("Can not open document: PCDM_RS_NoDriver")); break;
82     case PCDM_RS_UnknownFileDriver:
83       Events_Error::send(string("Can not open document: PCDM_RS_UnknownFileDriver")); break;
84     case PCDM_RS_OpenError:
85       Events_Error::send(string("Can not open document: PCDM_RS_OpenError")); break;
86     case PCDM_RS_NoVersion:
87       Events_Error::send(string("Can not open document: PCDM_RS_NoVersion")); break;
88     case PCDM_RS_NoModel:
89       Events_Error::send(string("Can not open document: PCDM_RS_NoModel")); break;
90     case PCDM_RS_NoDocument:
91       Events_Error::send(string("Can not open document: PCDM_RS_NoDocument")); break;
92     case PCDM_RS_FormatFailure:
93       Events_Error::send(string("Can not open document: PCDM_RS_FormatFailure")); break;
94     case PCDM_RS_TypeNotFoundInSchema:
95       Events_Error::send(string("Can not open document: PCDM_RS_TypeNotFoundInSchema")); break;
96     case PCDM_RS_UnrecognizedFileFormat:
97       Events_Error::send(string("Can not open document: PCDM_RS_UnrecognizedFileFormat")); break;
98     case PCDM_RS_MakeFailure:
99       Events_Error::send(string("Can not open document: PCDM_RS_MakeFailure")); break;
100     case PCDM_RS_PermissionDenied:
101       Events_Error::send(string("Can not open document: PCDM_RS_PermissionDenied")); break;
102     case PCDM_RS_DriverFailure:
103       Events_Error::send(string("Can not open document: PCDM_RS_DriverFailure")); break;
104     default:
105       Events_Error::send(string("Can not open document: unknown error")); break;
106     }
107   }
108   if (!isError) {
109     myDoc->SetUndoLimit(UNDO_LIMIT);
110     synchronizeFeatures();
111   }
112   return !isError;
113 }
114
115 bool Model_Document::save(const char* theFileName)
116 {
117   // create a directory in the root document if it is not yet exist
118   if (this == Model_PluginManager::get()->rootDocument().get()) {
119 #ifdef WIN32
120     CreateDirectory(theFileName, NULL);
121 #else
122     mkdir(theFileName, 0x1ff); 
123 #endif
124   }
125   // filename in the dir is id of document inside of the given directory
126   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
127   PCDM_StoreStatus aStatus;
128   try {
129     aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
130   }
131   catch (Standard_Failure) {
132     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
133     Events_Error::send(string("Exception in saving of document: ") + aFail->GetMessageString());
134     return false;
135   }
136   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
137   if (!isDone)
138   {
139     switch (aStatus)
140     {
141     case PCDM_SS_DriverFailure:
142       Events_Error::send(string("Can not save document: PCDM_SS_DriverFailure"));
143       break;
144     case PCDM_SS_WriteFailure:
145       Events_Error::send(string("Can not save document: PCDM_SS_WriteFailure"));
146       break;
147     case PCDM_SS_Failure:
148     default:
149       Events_Error::send(string("Can not save document: PCDM_SS_Failure"));
150       break;
151     }
152   }
153   myTransactionsAfterSave = 0;
154   if (isDone) { // save also sub-documents if any
155     set<string>::iterator aSubIter = mySubs.begin();
156     for(; aSubIter != mySubs.end() && isDone; aSubIter++)
157       isDone = subDocument(*aSubIter)->save(theFileName);
158   }
159   return isDone;
160 }
161
162 void Model_Document::close()
163 {
164   boost::shared_ptr<ModelAPI_PluginManager> aPM = Model_PluginManager::get();
165   if (this != aPM->rootDocument().get() && 
166       this == aPM->currentDocument().get()) {
167     aPM->setCurrentDocument(aPM->rootDocument());
168   }
169   // close all subs
170   set<string>::iterator aSubIter = mySubs.begin();
171   for(; aSubIter != mySubs.end(); aSubIter++)
172     subDocument(*aSubIter)->close();
173   mySubs.clear();
174   // close this
175   /* do not close because it can be undoed
176   if (myDoc->CanClose() == CDM_CCS_OK)
177     myDoc->Close();
178   Model_Application::getApplication()->deleteDocument(myID);
179   */
180 }
181
182 void Model_Document::startOperation()
183 {
184   if (myDoc->HasOpenCommand()) { // start of nested command
185     if (myNestedNum == -1) {
186       myNestedNum = 0;
187       myDoc->InitDeltaCompaction();
188     }
189     myIsEmptyTr[myTransactionsAfterSave] = false;
190     myTransactionsAfterSave++;
191     myDoc->NewCommand();
192   } else { // start of simple command
193     myDoc->NewCommand();
194   }
195   // new command for all subs
196   set<string>::iterator aSubIter = mySubs.begin();
197   for(; aSubIter != mySubs.end(); aSubIter++)
198     subDocument(*aSubIter)->startOperation();
199 }
200
201 void Model_Document::compactNested() {
202   while(myNestedNum != -1) {
203     myTransactionsAfterSave--;
204     myIsEmptyTr.erase(myTransactionsAfterSave);
205     myNestedNum--;
206   }
207   myIsEmptyTr[myTransactionsAfterSave] = false;
208   myTransactionsAfterSave++;
209   myDoc->PerformDeltaCompaction();
210 }
211
212 void Model_Document::finishOperation()
213 {
214   // just to be sure that everybody knows that changes were performed
215   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_CREATED));
216   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_UPDATED));
217   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_DELETED));
218
219   if (myNestedNum != -1) // this nested transaction is owervritten
220     myNestedNum++;
221   if (!myDoc->HasOpenCommand()) {
222     if (myNestedNum != -1) {
223       myNestedNum--;
224       compactNested();
225     }
226   } else {
227     // returns false if delta is empty and no transaction was made
228     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand() && (myNestedNum == -1);
229     myTransactionsAfterSave++;
230   }
231
232   // finish for all subs
233   set<string>::iterator aSubIter = mySubs.begin();
234   for(; aSubIter != mySubs.end(); aSubIter++)
235     subDocument(*aSubIter)->finishOperation();
236 }
237
238 void Model_Document::abortOperation()
239 {
240   if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
241     // first compact all nested
242     compactNested();
243     // for nested it is undo and clear redos
244     myDoc->Undo();
245     myDoc->ClearRedos();
246     myTransactionsAfterSave--;
247     myIsEmptyTr.erase(myTransactionsAfterSave);
248   } else {
249     if (myNestedNum == 0) // abort only high-level
250       myNestedNum = -1;
251     myDoc->AbortCommand();
252   }
253   synchronizeFeatures(true);
254   // abort for all subs
255   set<string>::iterator aSubIter = mySubs.begin();
256     for(; aSubIter != mySubs.end(); aSubIter++)
257     subDocument(*aSubIter)->abortOperation();
258 }
259
260 bool Model_Document::isOperation()
261 {
262   // operation is opened for all documents: no need to check subs
263   return myDoc->HasOpenCommand() == Standard_True;
264 }
265
266 bool Model_Document::isModified()
267 {
268   // is modified if at least one operation was commited and not undoed
269   return myTransactionsAfterSave > 0;
270 }
271
272 bool Model_Document::canUndo()
273 {
274   if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
275     return true;
276   // check other subs contains operation that can be undoed
277   set<string>::iterator aSubIter = mySubs.begin();
278   for(; aSubIter != mySubs.end(); aSubIter++)
279     if (subDocument(*aSubIter)->canUndo())
280       return true;
281   return false;
282 }
283
284 void Model_Document::undo()
285 {
286   myTransactionsAfterSave--;
287   if (myNestedNum > 0) myNestedNum--;
288   if (!myIsEmptyTr[myTransactionsAfterSave])
289     myDoc->Undo();
290   synchronizeFeatures(true);
291   // undo for all subs
292   set<string>::iterator aSubIter = mySubs.begin();
293   for(; aSubIter != mySubs.end(); aSubIter++)
294     subDocument(*aSubIter)->undo();
295 }
296
297 bool Model_Document::canRedo()
298 {
299   if (myDoc->GetAvailableRedos() > 0)
300     return true;
301   // check other subs contains operation that can be redoed
302   set<string>::iterator aSubIter = mySubs.begin();
303   for(; aSubIter != mySubs.end(); aSubIter++)
304     if (subDocument(*aSubIter)->canRedo())
305       return true;
306   return false;
307 }
308
309 void Model_Document::redo()
310 {
311   if (myNestedNum != -1) myNestedNum++;
312   if (!myIsEmptyTr[myTransactionsAfterSave])
313     myDoc->Redo();
314   myTransactionsAfterSave++;
315   synchronizeFeatures(true);
316   // redo for all subs
317   set<string>::iterator aSubIter = mySubs.begin();
318   for(; aSubIter != mySubs.end(); aSubIter++)
319     subDocument(*aSubIter)->redo();
320 }
321
322 FeaturePtr Model_Document::addFeature(string theID)
323 {
324   FeaturePtr aFeature = 
325     ModelAPI_PluginManager::get()->createFeature(theID);
326   if (aFeature) {
327     boost::dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
328   } else {
329     // TODO: generate error that feature is not created
330   }
331   return aFeature;
332 }
333
334 /// Appenad to the array of references a new referenced label
335 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced) {
336   Handle(TDataStd_ReferenceArray) aRefs;
337   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
338     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
339     aRefs->SetValue(0, theReferenced);
340   } else { // extend array by one more element
341     Handle(TDataStd_HLabelArray1) aNewArray = 
342       new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() + 1);
343     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
344       aNewArray->SetValue(a, aRefs->Value(a));
345     }
346     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
347     aRefs->SetInternalArray(aNewArray);
348   }
349 }
350
351 void Model_Document::addFeature(const FeaturePtr theFeature)
352 {
353   if (theFeature->isAction()) return; // do not add action to the data model
354
355   boost::shared_ptr<ModelAPI_Document> aThis = 
356     Model_Application::getApplication()->getDocument(myID);
357   TDF_Label aFeaturesLab = groupLabel(ModelAPI_Document::FEATURES_GROUP());
358   TDF_Label aFeatureLab = aFeaturesLab.NewChild();
359
360   // organize feature and data objects
361   boost::shared_ptr<Model_Data> aData(new Model_Data);
362   aData->setFeature(theFeature);
363   aData->setLabel(aFeatureLab);
364   theFeature->setDoc(aThis);
365   theFeature->setData(aData);
366   setUniqueName(theFeature);
367   theFeature->initAttributes();
368
369   // keep the feature ID to restore document later correctly
370   TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
371   myFeatures.push_back(theFeature);
372   // store feature in the history of features array
373   if (theFeature->isInHistory()) {
374     AddToRefArray(aFeaturesLab, aFeatureLab);
375   }
376   // add featue to the group
377   const std::string& aGroup = theFeature->getGroup();
378   TDF_Label aGroupLab = groupLabel(aGroup);
379   AddToRefArray(aGroupLab, aFeatureLab);
380   // new name of this feature object by default equal to name of feature
381   TDF_Label anObjLab = aGroupLab.NewChild();
382   TCollection_ExtendedString aName(theFeature->data()->getName().c_str());
383   TDataStd_Name::Set(anObjLab, aName);
384   TDF_Label aGrLabChild = aGroupLab.FindChild(1);
385   AddToRefArray(aGrLabChild, anObjLab); // reference to names is on the first sub
386
387   // event: feature is added
388   static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
389   ModelAPI_EventCreator::get()->sendUpdated(theFeature, anEvent);
390 }
391
392 /// Appenad to the array of references a new referenced label.
393 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
394 /// \returns the index of removed element
395 static int RemoveFromRefArray(
396   TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex = -1) {
397   int aResult = -1; // no returned
398   Handle(TDataStd_ReferenceArray) aRefs;
399   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
400     if (aRefs->Length() == 1) { // just erase an array
401       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
402         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
403       }
404       aResult = 0;
405     } else { // reduce the array
406       Handle(TDataStd_HLabelArray1) aNewArray = 
407         new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() - 1);
408       int aCount = aRefs->Lower();
409       for(int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
410         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
411           aCount--;
412           aResult = a;
413         } else {
414           aNewArray->SetValue(aCount, aRefs->Value(a));
415         }
416       }
417       aRefs->SetInternalArray(aNewArray);
418     }
419   }
420   return aResult;
421 }
422
423 void Model_Document::removeFeature(FeaturePtr theFeature)
424 {
425   boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
426   TDF_Label aFeatureLabel = aData->label();
427   // remove the object
428   TDF_Label aGroupLabel = groupLabel(theFeature->getGroup());
429   int aRemovedIndex = RemoveFromRefArray(aGroupLabel, aFeatureLabel);
430   RemoveFromRefArray(aGroupLabel.FindChild(1), TDF_Label(), aRemovedIndex);
431   // remove feature from the myFeatures list
432   std::vector<FeaturePtr >::iterator aFIter = myFeatures.begin();
433   while(aFIter != myFeatures.end()) {
434     if (*aFIter == theFeature) {
435       aFIter = myFeatures.erase(aFIter);
436     } else {
437       aFIter++;
438     }
439   }
440   // erase all attributes under the label of feature
441   aFeatureLabel.ForgetAllAttributes();
442   // remove it from the references array
443   RemoveFromRefArray(groupLabel(ModelAPI_Document::FEATURES_GROUP()), aData->label());
444
445   // event: feature is added
446   ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), theFeature->getGroup());
447 }
448
449 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
450 {
451   // iterate all features, may be optimized later by keeping labels-map
452   vector<FeaturePtr >::iterator aFIter = myFeatures.begin();
453   for(; aFIter != myFeatures.end(); aFIter++) {
454     boost::shared_ptr<Model_Data> aData = 
455       boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
456     if (aData->label().IsEqual(theLabel))
457       return *aFIter;
458   }
459   return FeaturePtr(); // not found
460 }
461
462 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
463 {
464   // just store sub-document identifier here to manage it later
465   if (mySubs.find(theDocID) == mySubs.end())
466     mySubs.insert(theDocID);
467   return Model_Application::getApplication()->getDocument(theDocID);
468 }
469
470 FeaturePtr Model_Document::feature(
471   const string& theGroupID, const int theIndex, const bool isOperation)
472 {
473   TDF_Label aGroupLab = groupLabel(theGroupID);
474   Handle(TDataStd_ReferenceArray) aRefs;
475   if (aGroupLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
476     if (aRefs->Lower() <= theIndex && aRefs->Upper() >= theIndex) {
477       TDF_Label aFeatureLab = aRefs->Value(theIndex);
478       FeaturePtr aFeature = feature(aFeatureLab);
479
480       if (theGroupID == ModelAPI_Document::FEATURES_GROUP() || isOperation) { // just returns the feature from the history
481         return aFeature;
482       } else { // create a new object from the group to return it
483         Handle(TDataStd_Name) aName; // name of the object
484         if (aGroupLab.FindChild(1).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
485           aRefs->Value(theIndex).FindAttribute(TDataStd_Name::GetID(), aName);
486         boost::shared_ptr<Model_Object> anObj(new Model_Object(aFeature, aName));
487         return anObj;
488       }
489     }
490   }
491
492   // not found
493   return FeaturePtr();
494 }
495
496 int Model_Document::size(const string& theGroupID) 
497 {
498   Handle(TDataStd_ReferenceArray) aRefs;
499   if (groupLabel(theGroupID).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
500     return aRefs->Length();
501   // group is not found
502   return 0;
503 }
504
505 Model_Document::Model_Document(const std::string theID)
506     : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
507 {
508   myDoc->SetUndoLimit(UNDO_LIMIT);
509   myTransactionsAfterSave = 0;
510   myNestedNum = -1;
511   //myDoc->SetNestedTransactionMode();
512   // to have something in the document and avoid empty doc open/save problem
513   // in transaction for nesting correct working
514   myDoc->NewCommand();
515   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
516   myDoc->CommitCommand();
517 }
518
519 TDF_Label Model_Document::groupLabel(const string theGroup)
520 {
521   // searching for existing
522   TCollection_ExtendedString aGroup(theGroup.c_str());
523   TDF_ChildIDIterator aGroupIter(myDoc->Main().FindChild(TAG_OBJECTS), TDataStd_Comment::GetID());
524   for(; aGroupIter.More(); aGroupIter.Next()) {
525     Handle(TDataStd_Comment) aName = Handle(TDataStd_Comment)::DownCast(aGroupIter.Value());
526     if (aName->Get() == aGroup)
527       return aGroupIter.Value()->Label();
528   }
529   // create a new
530   TDF_Label aNew = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
531   TDataStd_Comment::Set(aNew, aGroup);
532   return aNew;
533 }
534
535 void Model_Document::setUniqueName(FeaturePtr theFeature)
536 {
537   string aName; // result
538   // iterate all features but also iterate group of this feature if object is not in history
539   list<string> aGroups;
540   aGroups.push_back(ModelAPI_Document::FEATURES_GROUP());
541   if (!theFeature->isInHistory()) {
542     aGroups.push_back(theFeature->getGroup());
543   }
544   for(list<string>::iterator aGIter = aGroups.begin(); aGIter != aGroups.end(); aGIter++) {
545     // first count all objects of such kind to start with index = count + 1
546     int a, aNumObjects = 0;
547     int aSize = size(*aGIter);
548     for(a = 0; a < aSize; a++) {
549       if (feature(*aGIter, a)->getKind() == theFeature->getKind())
550         aNumObjects++;
551     }
552     // generate candidate name
553     stringstream aNameStream;
554     aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
555     aName = aNameStream.str();
556     // check this is unique, if not, increase index by 1
557     for(a = 0; a < aSize;) {
558       if (feature(*aGIter, a, true)->data()->getName() == aName) {
559         aNumObjects++;
560         stringstream aNameStream;
561         aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
562         aName = aNameStream.str();
563         // reinitialize iterator to make sure a new name is unique
564         a = 0;
565       } else a++;
566     }
567   }
568   theFeature->data()->setName(aName);
569 }
570
571 //! Returns the object by the feature
572 FeaturePtr Model_Document::objectByFeature(
573   const FeaturePtr theFeature)
574 {
575   for(int a = 0; a < size(theFeature->getGroup()); a++) {
576     boost::shared_ptr<Model_Object> anObj = 
577       boost::dynamic_pointer_cast<Model_Object>(feature(theFeature->getGroup(), a));
578     if (anObj && anObj->featureRef() == theFeature) {
579       return anObj;
580     }
581   }
582   return FeaturePtr(); // not found
583 }
584
585 void Model_Document::synchronizeFeatures(const bool theMarkUpdated)
586 {
587   boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
588   // update features
589   vector<FeaturePtr >::iterator aFIter = myFeatures.begin();
590   // and in parallel iterate labels of features
591   TDF_ChildIDIterator aFLabIter(groupLabel(ModelAPI_Document::FEATURES_GROUP()), TDataStd_Comment::GetID());
592   while(aFIter != myFeatures.end() || aFLabIter.More()) {
593     static const int INFINITE_TAG = INT_MAX; // no label means that it exists somwhere in infinite
594     int aFeatureTag = INFINITE_TAG; 
595     if (aFIter != myFeatures.end()) { // existing tag for feature
596       boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
597       aFeatureTag = aData->label().Tag();
598     }
599     int aDSTag = INFINITE_TAG; 
600     if (aFLabIter.More()) { // next label in DS is existing
601       aDSTag = aFLabIter.Value()->Label().Tag();
602     }
603     if (aDSTag > aFeatureTag) { // feature is removed
604       FeaturePtr aFeature = *aFIter;
605       aFIter = myFeatures.erase(aFIter);
606       // event: model is updated
607       if (aFeature->isInHistory()) {
608         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Document::FEATURES_GROUP());
609       }
610       ModelAPI_EventCreator::get()->sendDeleted(aThis, aFeature->getGroup());
611     } else if (aDSTag < aFeatureTag) { // a new feature is inserted
612       // create a feature
613       FeaturePtr aFeature = ModelAPI_PluginManager::get()->createFeature(
614         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
615         aFLabIter.Value())->Get()).ToCString());
616
617       if (aFIter == myFeatures.end()) { // must be before "setData" to redo the sketch line correctly
618         myFeatures.push_back(aFeature);
619         aFIter = myFeatures.end();
620       } else {
621         aFIter++;
622         myFeatures.insert(aFIter, aFeature);
623       }
624       boost::shared_ptr<Model_Data> aData(new Model_Data);
625       TDF_Label aLab = aFLabIter.Value()->Label();
626       aData->setLabel(aLab);
627       aData->setFeature(aFeature);
628       aFeature->setDoc(aThis);
629       aFeature->setData(aData);
630       aFeature->initAttributes();
631
632       // event: model is updated
633       static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
634       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
635       FeaturePtr anObj = objectByFeature(aFeature);
636       if (anObj) {
637         ModelAPI_EventCreator::get()->sendUpdated(anObj, anEvent);
638       }
639
640       // feature for this label is added, so go to the next label
641       aFLabIter.Next();
642     } else { // nothing is changed, both iterators are incremented
643       if (theMarkUpdated) {
644         static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_UPDATED);
645         ModelAPI_EventCreator::get()->sendUpdated(*aFIter, anEvent);
646       }
647       aFIter++;
648       aFLabIter.Next();
649     }
650   }
651   // after all updates, sends a message that groups of features were created or updated
652   boost::static_pointer_cast<Model_PluginManager>(Model_PluginManager::get())->
653     setCheckTransactions(false);
654   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_CREATED));
655   if (theMarkUpdated)
656     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_UPDATED));
657   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_DELETED));
658   boost::static_pointer_cast<Model_PluginManager>(Model_PluginManager::get())->
659     setCheckTransactions(true);
660 }