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