Salome HOME
87ad7e0b1b9ff76537be65847e04afdd0436717d
[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   if (myDoc->CanClose() == CDM_CCS_OK)
176     myDoc->Close();
177   Model_Application::getApplication()->deleteDocument(myID);
178 }
179
180 void Model_Document::startOperation()
181 {
182   if (myDoc->HasOpenCommand()) { // start of nested command
183     if (myNestedNum == -1) {
184       myNestedNum = 0;
185       myDoc->InitDeltaCompaction();
186     }
187     myIsEmptyTr[myTransactionsAfterSave] = false;
188     myTransactionsAfterSave++;
189     myDoc->NewCommand();
190   } else { // start of simple command
191     myDoc->NewCommand();
192   }
193   // new command for all subs
194   set<string>::iterator aSubIter = mySubs.begin();
195   for(; aSubIter != mySubs.end(); aSubIter++)
196     subDocument(*aSubIter)->startOperation();
197 }
198
199 void Model_Document::compactNested() {
200   while(myNestedNum != -1) {
201     myTransactionsAfterSave--;
202     myIsEmptyTr.erase(myTransactionsAfterSave);
203     myNestedNum--;
204   }
205   myIsEmptyTr[myTransactionsAfterSave] = false;
206   myTransactionsAfterSave++;
207   myDoc->PerformDeltaCompaction();
208 }
209
210 void Model_Document::finishOperation()
211 {
212   // just to be sure that everybody knows that changes were performed
213   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_CREATED));
214   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_UPDATED));
215   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_DELETED));
216
217   if (myNestedNum != -1) // this nested transaction is owervritten
218     myNestedNum++;
219   if (!myDoc->HasOpenCommand()) {
220     if (myNestedNum != -1) {
221       myNestedNum--;
222       compactNested();
223     }
224   } else {
225     // returns false if delta is empty and no transaction was made
226     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand() && (myNestedNum == -1);
227     myTransactionsAfterSave++;
228   }
229
230   // finish for all subs
231   set<string>::iterator aSubIter = mySubs.begin();
232   for(; aSubIter != mySubs.end(); aSubIter++)
233     subDocument(*aSubIter)->finishOperation();
234 }
235
236 void Model_Document::abortOperation()
237 {
238   if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
239     // first compact all nested
240     compactNested();
241     // for nested it is undo and clear redos
242     myDoc->Undo();
243     myDoc->ClearRedos();
244     myTransactionsAfterSave--;
245     myIsEmptyTr.erase(myTransactionsAfterSave);
246   } else {
247     if (myNestedNum == 0) // abort only high-level
248       myNestedNum = -1;
249     myDoc->AbortCommand();
250   }
251   synchronizeFeatures(true);
252   // abort for all subs
253   set<string>::iterator aSubIter = mySubs.begin();
254     for(; aSubIter != mySubs.end(); aSubIter++)
255     subDocument(*aSubIter)->abortOperation();
256 }
257
258 bool Model_Document::isOperation()
259 {
260   // operation is opened for all documents: no need to check subs
261   return myDoc->HasOpenCommand() == Standard_True;
262 }
263
264 bool Model_Document::isModified()
265 {
266   // is modified if at least one operation was commited and not undoed
267   return myTransactionsAfterSave > 0;
268 }
269
270 bool Model_Document::canUndo()
271 {
272   if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
273     return true;
274   // check other subs contains operation that can be undoed
275   set<string>::iterator aSubIter = mySubs.begin();
276   for(; aSubIter != mySubs.end(); aSubIter++)
277     if (subDocument(*aSubIter)->canUndo())
278       return true;
279   return false;
280 }
281
282 void Model_Document::undo()
283 {
284   myTransactionsAfterSave--;
285   if (myNestedNum > 0) myNestedNum--;
286   if (!myIsEmptyTr[myTransactionsAfterSave])
287     myDoc->Undo();
288   synchronizeFeatures(true);
289   // undo for all subs
290   set<string>::iterator aSubIter = mySubs.begin();
291   for(; aSubIter != mySubs.end(); aSubIter++)
292     subDocument(*aSubIter)->undo();
293 }
294
295 bool Model_Document::canRedo()
296 {
297   if (myDoc->GetAvailableRedos() > 0)
298     return true;
299   // check other subs contains operation that can be redoed
300   set<string>::iterator aSubIter = mySubs.begin();
301   for(; aSubIter != mySubs.end(); aSubIter++)
302     if (subDocument(*aSubIter)->canRedo())
303       return true;
304   return false;
305 }
306
307 void Model_Document::redo()
308 {
309   if (myNestedNum != -1) myNestedNum++;
310   if (!myIsEmptyTr[myTransactionsAfterSave])
311     myDoc->Redo();
312   myTransactionsAfterSave++;
313   synchronizeFeatures(true);
314   // redo for all subs
315   set<string>::iterator aSubIter = mySubs.begin();
316   for(; aSubIter != mySubs.end(); aSubIter++)
317     subDocument(*aSubIter)->redo();
318 }
319
320 boost::shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
321 {
322   boost::shared_ptr<ModelAPI_Feature> aFeature = 
323     ModelAPI_PluginManager::get()->createFeature(theID);
324   if (aFeature) {
325     boost::dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
326   } else {
327     // TODO: generate error that feature is not created
328   }
329   return aFeature;
330 }
331
332 /// Appenad to the array of references a new referenced label
333 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced) {
334   Handle(TDataStd_ReferenceArray) aRefs;
335   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
336     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
337     aRefs->SetValue(0, theReferenced);
338   } else { // extend array by one more element
339     Handle(TDataStd_HLabelArray1) aNewArray = 
340       new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() + 1);
341     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
342       aNewArray->SetValue(a, aRefs->Value(a));
343     }
344     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
345     aRefs->SetInternalArray(aNewArray);
346   }
347 }
348
349 void Model_Document::addFeature(const boost::shared_ptr<ModelAPI_Feature> theFeature)
350 {
351   if (theFeature->isAction()) return; // do not add action to the data model
352
353   boost::shared_ptr<ModelAPI_Document> aThis = 
354     Model_Application::getApplication()->getDocument(myID);
355   TDF_Label aFeaturesLab = groupLabel(FEATURES_GROUP);
356   TDF_Label aFeatureLab = aFeaturesLab.NewChild();
357
358   // organize feature and data objects
359   boost::shared_ptr<Model_Data> aData(new Model_Data);
360   aData->setFeature(theFeature);
361   aData->setLabel(aFeatureLab);
362   theFeature->setDoc(aThis);
363   theFeature->setData(aData);
364   setUniqueName(theFeature);
365   theFeature->initAttributes();
366
367   // keep the feature ID to restore document later correctly
368   TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
369   myFeatures.push_back(theFeature);
370   // store feature in the history of features array
371   if (theFeature->isInHistory()) {
372     AddToRefArray(aFeaturesLab, aFeatureLab);
373   }
374   // add featue to the group
375   const std::string& aGroup = theFeature->getGroup();
376   TDF_Label aGroupLab = groupLabel(aGroup);
377   AddToRefArray(aGroupLab, aFeatureLab);
378   // new name of this feature object by default equal to name of feature
379   TDF_Label anObjLab = aGroupLab.NewChild();
380   TCollection_ExtendedString aName(theFeature->data()->getName().c_str());
381   TDataStd_Name::Set(anObjLab, aName);
382   TDF_Label aGrLabChild = aGroupLab.FindChild(1);
383   AddToRefArray(aGrLabChild, anObjLab); // reference to names is on the first sub
384
385   // event: feature is added
386   static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
387   Model_FeatureUpdatedMessage aMsg(theFeature, anEvent);
388   Events_Loop::loop()->send(aMsg);
389 }
390
391 /// Appenad to the array of references a new referenced label.
392 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
393 /// \returns the index of removed element
394 static int RemoveFromRefArray(
395   TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex = -1) {
396   int aResult = -1; // no returned
397   Handle(TDataStd_ReferenceArray) aRefs;
398   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
399     if (aRefs->Length() == 1) { // just erase an array
400       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
401         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
402       }
403       aResult = 0;
404     } else { // reduce the array
405       Handle(TDataStd_HLabelArray1) aNewArray = 
406         new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() - 1);
407       int aCount = aRefs->Lower();
408       for(int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
409         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
410           aCount--;
411           aResult = a;
412         } else {
413           aNewArray->SetValue(aCount, aRefs->Value(a));
414         }
415       }
416       aRefs->SetInternalArray(aNewArray);
417     }
418   }
419   return aResult;
420 }
421
422 void Model_Document::removeFeature(boost::shared_ptr<ModelAPI_Feature> theFeature)
423 {
424   boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
425   TDF_Label aFeatureLabel = aData->label();
426   // remove the object
427   TDF_Label aGroupLabel = groupLabel(theFeature->getGroup());
428   int aRemovedIndex = RemoveFromRefArray(aGroupLabel, aFeatureLabel);
429   RemoveFromRefArray(aGroupLabel.FindChild(1), TDF_Label(), aRemovedIndex);
430   // remove feature from the myFeatures list
431   std::vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = myFeatures.begin();
432   while(aFIter != myFeatures.end()) {
433     if (*aFIter == theFeature) {
434       aFIter = myFeatures.erase(aFIter);
435     } else {
436       aFIter++;
437     }
438   }
439   // erase all attributes under the label of feature
440   aFeatureLabel.ForgetAllAttributes();
441   // remove it from the references array
442   RemoveFromRefArray(groupLabel(FEATURES_GROUP), aData->label());
443
444   // event: feature is added
445   Model_FeatureDeletedMessage aMsg(theFeature->document(), theFeature->getGroup());
446   Events_Loop::loop()->send(aMsg);
447 }
448
449 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
450 {
451   // iterate all features, may be optimized later by keeping labels-map
452   vector<boost::shared_ptr<ModelAPI_Feature> >::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 boost::shared_ptr<ModelAPI_Feature>(); // 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 boost::shared_ptr<ModelAPI_Feature> 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       boost::shared_ptr<ModelAPI_Feature> aFeature = feature(aFeatureLab);
479
480       if (theGroupID == 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 boost::shared_ptr<ModelAPI_Feature>();
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(boost::shared_ptr<ModelAPI_Feature> 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(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 boost::shared_ptr<ModelAPI_Feature> Model_Document::objectByFeature(
573   const boost::shared_ptr<ModelAPI_Feature> 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) {
579       return anObj;
580     }
581   }
582   return boost::shared_ptr<ModelAPI_Feature>(); // 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<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = myFeatures.begin();
590   // and in parallel iterate labels of features
591   TDF_ChildIDIterator aFLabIter(groupLabel(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         Model_FeatureDeletedMessage aMsg1(aThis, FEATURES_GROUP);
609         Events_Loop::loop()->send(aMsg1);
610       }
611       Model_FeatureDeletedMessage aMsg2(aThis, aFeature->getGroup());
612       Events_Loop::loop()->send(aMsg2);
613     } else if (aDSTag < aFeatureTag) { // a new feature is inserted
614       // create a feature
615       boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
616         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
617         aFLabIter.Value())->Get()).ToCString());
618
619       if (aFIter == myFeatures.end()) { // must be before "setData" to redo the sketch line correctly
620         myFeatures.push_back(aFeature);
621         aFIter = myFeatures.end();
622       } else {
623         aFIter++;
624         myFeatures.insert(aFIter, aFeature);
625       }
626       boost::shared_ptr<Model_Data> aData(new Model_Data);
627       TDF_Label aLab = aFLabIter.Value()->Label();
628       aData->setLabel(aLab);
629       aData->setFeature(aFeature);
630       aFeature->setDoc(aThis);
631       aFeature->setData(aData);
632       aFeature->initAttributes();
633
634       // event: model is updated
635       static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
636       Model_FeatureUpdatedMessage aMsg1(aFeature, anEvent);
637       Events_Loop::loop()->send(aMsg1);
638       boost::shared_ptr<ModelAPI_Feature> anObj = objectByFeature(aFeature);
639       if (anObj) {
640         Model_FeatureUpdatedMessage aMsg2(anObj, anEvent);
641         Events_Loop::loop()->send(aMsg2);
642       }
643
644       // feature for this label is added, so go to the next label
645       aFLabIter.Next();
646     } else { // nothing is changed, both iterators are incremented
647       if (theMarkUpdated) {
648         static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_UPDATED);
649         Model_FeatureUpdatedMessage aMsg(*aFIter, anEvent);
650         Events_Loop::loop()->send(aMsg);
651       }
652       aFIter++;
653       aFLabIter.Next();
654     }
655   }
656   // after all updates, sends a message that groups of features were created or updated
657   boost::static_pointer_cast<Model_PluginManager>(Model_PluginManager::get())->
658     setCheckTransactions(false);
659   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_CREATED));
660   if (theMarkUpdated)
661     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_UPDATED));
662   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_DELETED));
663   boost::static_pointer_cast<Model_PluginManager>(Model_PluginManager::get())->
664     setCheckTransactions(true);
665 }