]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Document.cpp
Salome HOME
COrrect management of nested transactions
[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     myDoc->NewCommand();
188   } else { // start of simple command
189     myDoc->NewCommand();
190   }
191   // new command for all subs
192   set<string>::iterator aSubIter = mySubs.begin();
193   for(; aSubIter != mySubs.end(); aSubIter++)
194     subDocument(*aSubIter)->startOperation();
195 }
196
197 void Model_Document::finishOperation()
198 {
199   if (myNestedNum != -1) // this nested transaction is owervritten
200     myNestedNum++;
201   if (!myDoc->HasOpenCommand()) {
202     if (myNestedNum != -1) {
203       myNestedNum -= 2; // one is just incremented before, one is left (and not empty!)
204       while(myNestedNum != -1) {
205         myIsEmptyTr.erase(myTransactionsAfterSave);
206         myTransactionsAfterSave--;
207         myNestedNum--;
208       }
209       myIsEmptyTr[myTransactionsAfterSave] = false;
210       myTransactionsAfterSave++;
211       myDoc->PerformDeltaCompaction();
212     }
213   } else {
214     // returns false if delta is empty and no transaction was made
215     myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand() && (myNestedNum == -1);
216     myTransactionsAfterSave++;
217   }
218
219   // finish for all subs
220   set<string>::iterator aSubIter = mySubs.begin();
221   for(; aSubIter != mySubs.end(); aSubIter++)
222     subDocument(*aSubIter)->finishOperation();
223 }
224
225 void Model_Document::abortOperation()
226 {
227   if (myNestedNum == 0)
228     myNestedNum = -1;
229   myDoc->AbortCommand();
230   synchronizeFeatures();
231   // abort for all subs
232   set<string>::iterator aSubIter = mySubs.begin();
233   for(; aSubIter != mySubs.end(); aSubIter++)
234     subDocument(*aSubIter)->abortOperation();
235 }
236
237 bool Model_Document::isOperation()
238 {
239   // operation is opened for all documents: no need to check subs
240   return myDoc->HasOpenCommand() == Standard_True;
241 }
242
243 bool Model_Document::isModified()
244 {
245   // is modified if at least one operation was commited and not undoed
246   return myTransactionsAfterSave > 0;
247 }
248
249 bool Model_Document::canUndo()
250 {
251   if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
252     return true;
253   // check other subs contains operation that can be undoed
254   set<string>::iterator aSubIter = mySubs.begin();
255   for(; aSubIter != mySubs.end(); aSubIter++)
256     if (subDocument(*aSubIter)->canUndo())
257       return true;
258   return false;
259 }
260
261 void Model_Document::undo()
262 {
263   myTransactionsAfterSave--;
264   if (myNestedNum > 0) myNestedNum--;
265   if (!myIsEmptyTr[myTransactionsAfterSave])
266     myDoc->Undo();
267   synchronizeFeatures();
268   // undo for all subs
269   set<string>::iterator aSubIter = mySubs.begin();
270   for(; aSubIter != mySubs.end(); aSubIter++)
271     subDocument(*aSubIter)->undo();
272 }
273
274 bool Model_Document::canRedo()
275 {
276   if (myDoc->GetAvailableRedos() > 0)
277     return true;
278   // check other subs contains operation that can be redoed
279   set<string>::iterator aSubIter = mySubs.begin();
280   for(; aSubIter != mySubs.end(); aSubIter++)
281     if (subDocument(*aSubIter)->canRedo())
282       return true;
283   return false;
284 }
285
286 void Model_Document::redo()
287 {
288   if (myNestedNum != -1) myNestedNum++;
289   if (!myIsEmptyTr[myTransactionsAfterSave])
290     myDoc->Redo();
291   myTransactionsAfterSave++;
292   synchronizeFeatures();
293   // redo for all subs
294   set<string>::iterator aSubIter = mySubs.begin();
295   for(; aSubIter != mySubs.end(); aSubIter++)
296     subDocument(*aSubIter)->redo();
297 }
298
299 boost::shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
300 {
301   boost::shared_ptr<ModelAPI_Feature> aFeature = 
302     ModelAPI_PluginManager::get()->createFeature(theID);
303   if (aFeature) {
304     boost::dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
305   } else {
306     // TODO: generate error that feature is not created
307   }
308   return aFeature;
309 }
310
311 /// Appenad to the array of references a new referenced label
312 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced) {
313   Handle(TDataStd_ReferenceArray) aRefs;
314   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
315     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
316     aRefs->SetValue(0, theReferenced);
317   } else { // extend array by one more element
318     Handle(TDataStd_HLabelArray1) aNewArray = 
319       new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() + 1);
320     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
321       aNewArray->SetValue(a, aRefs->Value(a));
322     }
323     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
324     aRefs->SetInternalArray(aNewArray);
325   }
326 }
327
328 void Model_Document::addFeature(const boost::shared_ptr<ModelAPI_Feature> theFeature)
329 {
330   if (theFeature->isAction()) return; // do not add action to the data model
331
332   boost::shared_ptr<ModelAPI_Document> aThis = 
333     Model_Application::getApplication()->getDocument(myID);
334   TDF_Label aFeaturesLab = groupLabel(FEATURES_GROUP);
335   TDF_Label aFeatureLab = aFeaturesLab.NewChild();
336
337   // organize feature and data objects
338   boost::shared_ptr<Model_Data> aData(new Model_Data);
339   aData->setFeature(theFeature);
340   aData->setLabel(aFeatureLab);
341   theFeature->setDoc(aThis);
342   theFeature->setData(aData);
343   setUniqueName(theFeature);
344   theFeature->initAttributes();
345
346   // keep the feature ID to restore document later correctly
347   TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
348   myFeatures.push_back(theFeature);
349   // store feature in the history of features array
350   if (theFeature->isInHistory()) {
351     AddToRefArray(aFeaturesLab, aFeatureLab);
352   }
353   // add featue to the group
354   const std::string& aGroup = theFeature->getGroup();
355   TDF_Label aGroupLab = groupLabel(aGroup);
356   AddToRefArray(aGroupLab, aFeatureLab);
357   // new name of this feature object by default equal to name of feature
358   TDF_Label anObjLab = aGroupLab.NewChild();
359   TCollection_ExtendedString aName(theFeature->data()->getName().c_str());
360   TDataStd_Name::Set(anObjLab, aName);
361   TDF_Label aGrLabChild = aGroupLab.FindChild(1);
362   AddToRefArray(aGrLabChild, anObjLab); // reference to names is on the first sub
363
364   // event: feature is added
365   static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
366   Model_FeatureUpdatedMessage aMsg(theFeature, anEvent);
367   Events_Loop::loop()->send(aMsg);
368 }
369
370 /// Appenad to the array of references a new referenced label.
371 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
372 /// \returns the index of removed element
373 static int RemoveFromRefArray(
374   TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex = -1) {
375   int aResult = -1; // no returned
376   Handle(TDataStd_ReferenceArray) aRefs;
377   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
378     if (aRefs->Length() == 1) { // just erase an array
379       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0)
380         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
381       aResult = 0;
382     } else { // reduce the array
383       Handle(TDataStd_HLabelArray1) aNewArray = 
384         new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() - 1);
385       int aCount = aRefs->Lower();
386       for(int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
387         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
388           aCount--;
389           aResult = a;
390         } else {
391           aNewArray->SetValue(aCount, aRefs->Value(a));
392         }
393       }
394     aRefs->SetInternalArray(aNewArray);
395     }
396   }
397   return aResult;
398 }
399
400 void Model_Document::removeFeature(boost::shared_ptr<ModelAPI_Feature> theFeature)
401 {
402   boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
403   TDF_Label aFeatureLabel = aData->label();
404   // remove the object
405   TDF_Label aGroupLabel = groupLabel(theFeature->getGroup());
406   int aRemovedIndex = RemoveFromRefArray(aGroupLabel, aFeatureLabel);
407   RemoveFromRefArray(aGroupLabel.FindChild(1), TDF_Label(), aRemovedIndex);
408   // remove feature from the myFeatures list
409   std::vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = myFeatures.begin();
410   while(aFIter != myFeatures.end()) {
411     if (*aFIter == theFeature) {
412       aFIter = myFeatures.erase(aFIter);
413     } else {
414       aFIter++;
415     }
416   }
417   // erase all attributes under the label of feature
418   aFeatureLabel.ForgetAllAttributes();
419   // remove it from the references array
420   RemoveFromRefArray(groupLabel(FEATURES_GROUP), aData->label());
421
422   // event: feature is added
423   Model_FeatureDeletedMessage aMsg(theFeature->document(), theFeature->getGroup());
424   Events_Loop::loop()->send(aMsg);
425 }
426
427 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
428 {
429   // iterate all features, may be optimized later by keeping labels-map
430   vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = myFeatures.begin();
431   for(; aFIter != myFeatures.end(); aFIter++) {
432     boost::shared_ptr<Model_Data> aData = 
433       boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
434     if (aData->label().IsEqual(theLabel))
435       return *aFIter;
436   }
437   return boost::shared_ptr<ModelAPI_Feature>(); // not found
438 }
439
440 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
441 {
442   // just store sub-document identifier here to manage it later
443   if (mySubs.find(theDocID) == mySubs.end())
444     mySubs.insert(theDocID);
445   return Model_Application::getApplication()->getDocument(theDocID);
446 }
447
448 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
449   const string& theGroupID, const int theIndex, const bool isOperation)
450 {
451   TDF_Label aGroupLab = groupLabel(theGroupID);
452   Handle(TDataStd_ReferenceArray) aRefs;
453   if (aGroupLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
454     if (aRefs->Lower() <= theIndex && aRefs->Upper() >= theIndex) {
455       TDF_Label aFeatureLab = aRefs->Value(theIndex);
456       boost::shared_ptr<ModelAPI_Feature> aFeature = feature(aFeatureLab);
457
458       if (theGroupID == FEATURES_GROUP || isOperation) { // just returns the feature from the history
459         return aFeature;
460       } else { // create a new object from the group to return it
461         Handle(TDataStd_Name) aName; // name of the object
462         if (aGroupLab.FindChild(1).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
463           aRefs->Value(theIndex).FindAttribute(TDataStd_Name::GetID(), aName);
464         boost::shared_ptr<Model_Object> anObj(new Model_Object(aFeature, aName));
465         return anObj;
466       }
467     }
468   }
469
470   // not found
471   return boost::shared_ptr<ModelAPI_Feature>();
472 }
473
474 int Model_Document::size(const string& theGroupID) 
475 {
476   Handle(TDataStd_ReferenceArray) aRefs;
477   if (groupLabel(theGroupID).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
478     return aRefs->Length();
479   // group is not found
480   return 0;
481 }
482
483 Model_Document::Model_Document(const std::string theID)
484     : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
485 {
486   myDoc->SetUndoLimit(UNDO_LIMIT);
487   myTransactionsAfterSave = 0;
488   myNestedNum = -1;
489   //myDoc->SetNestedTransactionMode();
490   // to have something in the document and avoid empty doc open/save problem
491   // in transaction for nesting correct working
492   myDoc->NewCommand();
493   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
494   myDoc->CommitCommand();
495 }
496
497 TDF_Label Model_Document::groupLabel(const string theGroup)
498 {
499   // searching for existing
500   TCollection_ExtendedString aGroup(theGroup.c_str());
501   TDF_ChildIDIterator aGroupIter(myDoc->Main().FindChild(TAG_OBJECTS), TDataStd_Comment::GetID());
502   for(; aGroupIter.More(); aGroupIter.Next()) {
503     Handle(TDataStd_Comment) aName = Handle(TDataStd_Comment)::DownCast(aGroupIter.Value());
504     if (aName->Get() == aGroup)
505       return aGroupIter.Value()->Label();
506   }
507   // create a new
508   TDF_Label aNew = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
509   TDataStd_Comment::Set(aNew, aGroup);
510   return aNew;
511 }
512
513 void Model_Document::setUniqueName(boost::shared_ptr<ModelAPI_Feature> theFeature)
514 {
515   string aName; // result
516   // iterate all features but also iterate group of this feature if object is not in history
517   list<string> aGroups;
518   aGroups.push_back(FEATURES_GROUP);
519   if (!theFeature->isInHistory()) {
520     aGroups.push_back(theFeature->getGroup());
521   }
522   for(list<string>::iterator aGIter = aGroups.begin(); aGIter != aGroups.end(); aGIter++) {
523     // first count all objects of such kind to start with index = count + 1
524     int a, aNumObjects = 0;
525     int aSize = size(*aGIter);
526     for(a = 0; a < aSize; a++) {
527       if (feature(*aGIter, a)->getKind() == theFeature->getKind())
528         aNumObjects++;
529     }
530     // generate candidate name
531     stringstream aNameStream;
532     aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
533     aName = aNameStream.str();
534     // check this is unique, if not, increase index by 1
535     for(a = 0; a < aSize;) {
536       if (feature(*aGIter, a, true)->data()->getName() == aName) {
537         aNumObjects++;
538         stringstream aNameStream;
539         aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
540         aName = aNameStream.str();
541         // reinitialize iterator to make sure a new name is unique
542         a = 0;
543       } else a++;
544     }
545   }
546   theFeature->data()->setName(aName);
547 }
548
549 //! Returns the object by the feature
550 boost::shared_ptr<ModelAPI_Feature> Model_Document::objectByFeature(
551   const boost::shared_ptr<ModelAPI_Feature> theFeature)
552 {
553   for(int a = 0; a < size(theFeature->getGroup()); a++) {
554     boost::shared_ptr<Model_Object> anObj = 
555       boost::dynamic_pointer_cast<Model_Object>(feature(theFeature->getGroup(), a));
556     if (anObj) {
557       return anObj;
558     }
559   }
560   return boost::shared_ptr<ModelAPI_Feature>(); // not found
561 }
562
563 void Model_Document::synchronizeFeatures()
564 {
565   boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
566   // update features
567   vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = myFeatures.begin();
568   // and in parallel iterate labels of features
569   TDF_ChildIDIterator aFLabIter(groupLabel(FEATURES_GROUP), TDataStd_Comment::GetID());
570   while(aFIter != myFeatures.end() || aFLabIter.More()) {
571     static const int INFINITE_TAG = INT_MAX; // no label means that it exists somwhere in infinite
572     int aFeatureTag = INFINITE_TAG; 
573     if (aFIter != myFeatures.end()) { // existing tag for feature
574       boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
575       aFeatureTag = aData->label().Tag();
576     }
577     int aDSTag = INFINITE_TAG; 
578     if (aFLabIter.More()) { // next label in DS is existing
579       aDSTag = aFLabIter.Value()->Label().Tag();
580     }
581     if (aDSTag > aFeatureTag) { // feature is removed
582       Model_FeatureDeletedMessage aMsg1(aThis, FEATURES_GROUP);
583       Model_FeatureDeletedMessage aMsg2(aThis, (*aFIter)->getGroup());
584       aFIter = myFeatures.erase(aFIter);
585       // event: model is updated
586       Events_Loop::loop()->send(aMsg1);
587       Events_Loop::loop()->send(aMsg2);
588     } else if (aDSTag < aFeatureTag) { // a new feature is inserted
589       // create a feature
590       boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
591         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
592         aFLabIter.Value())->Get()).ToCString());
593
594       if (aFIter == myFeatures.end()) { // must be before "setData" to redo the sketch line correctly
595         myFeatures.push_back(aFeature);
596         aFIter = myFeatures.end();
597       } else {
598         aFIter++;
599         myFeatures.insert(aFIter, aFeature);
600       }
601       boost::shared_ptr<Model_Data> aData(new Model_Data);
602       TDF_Label aLab = aFLabIter.Value()->Label();
603       aData->setLabel(aLab);
604       aData->setFeature(aFeature);
605       aFeature->setDoc(aThis);
606       aFeature->setData(aData);
607       aFeature->initAttributes();
608
609       // event: model is updated
610       static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
611       Model_FeatureUpdatedMessage aMsg1(aFeature, anEvent);
612       Events_Loop::loop()->send(aMsg1);
613       boost::shared_ptr<ModelAPI_Feature> anObj = objectByFeature(aFeature);
614       if (anObj) {
615         Model_FeatureUpdatedMessage aMsg2(anObj, anEvent);
616         Events_Loop::loop()->send(aMsg2);
617       }
618
619       // feature for this label is added, so go to the next label
620       aFLabIter.Next();
621     } else { // nothing is changed, both iterators are incremented
622       aFIter++;
623       aFLabIter.Next();
624     }
625   }
626   // after all updates, sends a message that groups of features were created or updated
627   boost::static_pointer_cast<Model_PluginManager>(Model_PluginManager::get())->
628     setCheckTransactions(false);
629   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_CREATED));
630   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_DELETED));
631   boost::static_pointer_cast<Model_PluginManager>(Model_PluginManager::get())->
632     setCheckTransactions(true);
633 }