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