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