Salome HOME
ModelDocument test corrected to avoid SWIG/Python crash
[modules/shaper.git] / src / Model / Model_Document.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_Document.cxx
4 // Created:     28 Feb 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include <Model_Document.h>
8 #include <Model_Data.h>
9 #include <Model_Application.h>
10 #include <Model_Session.h>
11 #include <Model_Events.h>
12 #include <Model_ResultPart.h>
13 #include <Model_ResultConstruction.h>
14 #include <Model_ResultBody.h>
15 #include <Model_ResultGroup.h>
16 #include <ModelAPI_Validator.h>
17 #include <Events_Loop.h>
18 #include <Events_Error.h>
19
20 #include <TDataStd_Integer.hxx>
21 #include <TDataStd_Comment.hxx>
22 #include <TDF_ChildIDIterator.hxx>
23 #include <TDataStd_ReferenceArray.hxx>
24 #include <TDataStd_HLabelArray1.hxx>
25 #include <TDataStd_Name.hxx>
26 #include <TDF_Reference.hxx>
27 #include <TDF_ChildIDIterator.hxx>
28 #include <TDF_LabelMapHasher.hxx>
29 #include <OSD_File.hxx>
30 #include <OSD_Path.hxx>
31
32 #include <climits>
33 #ifndef WIN32
34 #include <sys/stat.h>
35 #endif
36
37 #ifdef WIN32
38 # define _separator_ '\\'
39 #else
40 # define _separator_ '/'
41 #endif
42
43 static const int UNDO_LIMIT = 1000;  // number of possible undo operations (big for sketcher)
44
45 static const int TAG_GENERAL = 1;  // general properties tag
46 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
47 static const int TAG_HISTORY = 3;  // tag of the history sub-tree (python dump)
48
49 // feature sub-labels
50 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
51 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
52
53 ///
54 /// 0:1:2 - where features are located
55 /// 0:1:2:N:1 - data of the feature N
56 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
57
58 Model_Document::Model_Document(const std::string theID, const std::string theKind)
59     : myID(theID), myKind(theKind),
60       myDoc(new TDocStd_Document("BinOcaf"))  // binary OCAF format
61 {
62   myDoc->SetUndoLimit(UNDO_LIMIT);  
63   myTransactionsCounter = 0;
64   myTransactionSave = 0;
65   myNestedNum = -1;
66   myExecuteFeatures = true;
67   // to have something in the document and avoid empty doc open/save problem
68   // in transaction for nesting correct working
69   myDoc->NewCommand();
70   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
71   myDoc->CommitCommand();
72 }
73
74 /// Returns the file name of this document by the nameof directory and identifuer of a document
75 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
76 {
77   TCollection_ExtendedString aPath((const Standard_CString) theFileName);
78   // remove end-separators
79   while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
80     aPath.Remove(aPath.Length());
81   aPath += _separator_;
82   aPath += theID.c_str();
83   aPath += ".cbf";  // standard binary file extension
84   return aPath;
85 }
86
87 bool Model_Document::load(const char* theFileName)
88 {
89   Handle(Model_Application) anApp = Model_Application::getApplication();
90   if (this == Model_Session::get()->moduleDocument().get()) {
91     anApp->setLoadPath(theFileName);
92   }
93   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
94   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
95   try {
96     aStatus = anApp->Open(aPath, myDoc);
97   } catch (Standard_Failure) {
98     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
99     Events_Error::send(
100         std::string("Exception in opening of document: ") + aFail->GetMessageString());
101     return false;
102   }
103   bool isError = aStatus != PCDM_RS_OK;
104   if (isError) {
105     switch (aStatus) {
106       case PCDM_RS_UnknownDocument:
107         Events_Error::send(std::string("Can not open document"));
108         break;
109       case PCDM_RS_AlreadyRetrieved:
110         Events_Error::send(std::string("Can not open document: already opened"));
111         break;
112       case PCDM_RS_AlreadyRetrievedAndModified:
113         Events_Error::send(
114             std::string("Can not open document: already opened and modified"));
115         break;
116       case PCDM_RS_NoDriver:
117         Events_Error::send(std::string("Can not open document: driver library is not found"));
118         break;
119       case PCDM_RS_UnknownFileDriver:
120         Events_Error::send(std::string("Can not open document: unknown driver for opening"));
121         break;
122       case PCDM_RS_OpenError:
123         Events_Error::send(std::string("Can not open document: file open error"));
124         break;
125       case PCDM_RS_NoVersion:
126         Events_Error::send(std::string("Can not open document: invalid version"));
127         break;
128       case PCDM_RS_NoModel:
129         Events_Error::send(std::string("Can not open document: no data model"));
130         break;
131       case PCDM_RS_NoDocument:
132         Events_Error::send(std::string("Can not open document: no document inside"));
133         break;
134       case PCDM_RS_FormatFailure:
135         Events_Error::send(std::string("Can not open document: format failure"));
136         break;
137       case PCDM_RS_TypeNotFoundInSchema:
138         Events_Error::send(std::string("Can not open document: invalid object"));
139         break;
140       case PCDM_RS_UnrecognizedFileFormat:
141         Events_Error::send(std::string("Can not open document: unrecognized file format"));
142         break;
143       case PCDM_RS_MakeFailure:
144         Events_Error::send(std::string("Can not open document: make failure"));
145         break;
146       case PCDM_RS_PermissionDenied:
147         Events_Error::send(std::string("Can not open document: permission denied"));
148         break;
149       case PCDM_RS_DriverFailure:
150         Events_Error::send(std::string("Can not open document: driver failure"));
151         break;
152       default:
153         Events_Error::send(std::string("Can not open document: unknown error"));
154         break;
155     }
156   }
157   if (!isError) {
158     myDoc->SetUndoLimit(UNDO_LIMIT);
159     // to avoid the problem that feature is created in the current, not this, document
160     Model_Session::get()->setActiveDocument(anApp->getDocument(myID), false);
161     synchronizeFeatures(false, true);
162     Model_Session::get()->setActiveDocument(Model_Session::get()->moduleDocument(), false);
163     Model_Session::get()->setActiveDocument(anApp->getDocument(myID), true);
164   }
165   return !isError;
166 }
167
168 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
169 {
170   // create a directory in the root document if it is not yet exist
171   Handle(Model_Application) anApp = Model_Application::getApplication();
172   if (this == Model_Session::get()->moduleDocument().get()) {
173 #ifdef WIN32
174     CreateDirectory(theFileName, NULL);
175 #else
176     mkdir(theFileName, 0x1ff);
177 #endif
178   }
179   // filename in the dir is id of document inside of the given directory
180   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
181   PCDM_StoreStatus aStatus;
182   try {
183     aStatus = anApp->SaveAs(myDoc, aPath);
184   } catch (Standard_Failure) {
185     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
186     Events_Error::send(
187         std::string("Exception in saving of document: ") + aFail->GetMessageString());
188     return false;
189   }
190   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
191   if (!isDone) {
192     switch (aStatus) {
193       case PCDM_SS_DriverFailure:
194         Events_Error::send(std::string("Can not save document: save driver-library failure"));
195         break;
196       case PCDM_SS_WriteFailure:
197         Events_Error::send(std::string("Can not save document: file writing failure"));
198         break;
199       case PCDM_SS_Failure:
200       default:
201         Events_Error::send(std::string("Can not save document"));
202         break;
203     }
204   }
205   myTransactionSave = myTransactionsCounter;
206   if (isDone) {  // save also sub-documents if any
207     theResults.push_back(TCollection_AsciiString(aPath).ToCString());
208     const std::set<std::string> aSubs = subDocuments(false);
209     std::set<std::string>::iterator aSubIter = aSubs.begin();
210     for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
211       if (anApp->isLoadByDemand(*aSubIter)) { 
212         // copy not-activated document that is not in the memory
213         std::string aDocName = *aSubIter;
214         if (!aDocName.empty()) {
215           // just copy file
216           TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
217           OSD_Path aPath(aSubPath);
218           OSD_File aFile(aPath);
219           if (aFile.Exists()) {
220             TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
221             OSD_Path aDestination(aDestinationDir);
222             aFile.Copy(aDestination);
223             theResults.push_back(aDestinationDir.ToCString());
224           } else {
225             Events_Error::send(
226               std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
227           }
228         }
229       } else { // simply save opened document
230         isDone = subDoc(*aSubIter)->save(theFileName, theResults);
231       }
232     }
233   }
234   return isDone;
235 }
236
237 void Model_Document::close(const bool theForever)
238 {
239   std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
240   if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
241     aPM->setActiveDocument(aPM->moduleDocument());
242   }
243   // close all subs
244   const std::set<std::string> aSubs = subDocuments(true);
245   std::set<std::string>::iterator aSubIter = aSubs.begin();
246   for (; aSubIter != aSubs.end(); aSubIter++)
247     subDoc(*aSubIter)->close(theForever);
248
249   // close for thid document needs no transaction in this document
250   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
251
252   // delete all features of this document
253   std::shared_ptr<ModelAPI_Document> aThis = 
254     Model_Application::getApplication()->getDocument(myID);
255   Events_Loop* aLoop = Events_Loop::loop();
256   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myObjs);
257   for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
258     FeaturePtr aFeature = aFeaturesIter.Value();
259     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
260     ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
261     ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
262     aFeature->eraseResults();
263     aFeature->erase();
264   }
265   myObjs.Clear();
266   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
267   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
268
269   // close all only if it is really asked, otherwise it can be undoed/redoed
270   if (theForever) {
271     if (myDoc->CanClose() == CDM_CCS_OK)
272       myDoc->Close();
273   }
274
275   std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
276 }
277
278 void Model_Document::startOperation()
279 {
280   if (myDoc->HasOpenCommand()) {  // start of nested command
281     if (myNestedNum == -1) {
282       myNestedNum = 0;
283       myDoc->InitDeltaCompaction();
284     }
285     myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand();
286     myTransactionsCounter++;
287     myDoc->OpenCommand();
288   } else {  // start the simple command
289     myDoc->NewCommand();
290   }
291   // new command for all subs
292   const std::set<std::string> aSubs = subDocuments(true);
293   std::set<std::string>::iterator aSubIter = aSubs.begin();
294   for (; aSubIter != aSubs.end(); aSubIter++)
295     subDoc(*aSubIter)->startOperation();
296 }
297
298 bool Model_Document::compactNested()
299 {
300   bool allWasEmpty = true;
301   while (myNestedNum != -1) {
302     myTransactionsCounter--;
303     if (!myIsEmptyTr[myTransactionsCounter]) {
304       allWasEmpty = false;
305     }
306     myIsEmptyTr.erase(myTransactionsCounter);
307     myNestedNum--;
308   }
309   myIsEmptyTr[myTransactionsCounter] = allWasEmpty;
310   myTransactionsCounter++;
311   if (allWasEmpty) {
312     // Issue 151: if everything is empty, it is a problem for OCCT to work with it, 
313     // just commit the empty that returns nothing
314     myDoc->CommitCommand();
315   } else {
316     myDoc->PerformDeltaCompaction();
317   }
318   return !allWasEmpty;
319 }
320
321 void Model_Document::finishOperation()
322 {
323   // just to be sure that everybody knows that changes were performed
324   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
325     std::static_pointer_cast<Model_Session>(Model_Session::get())
326         ->setCheckTransactions(false);  // for nested transaction commit
327   synchronizeBackRefs();
328   Events_Loop* aLoop = Events_Loop::loop();
329   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
330   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
331   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
332   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
333   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
334   // this must be here just after everything is finished but before real transaction stop
335   // to avoid messages about modifications outside of the transaction
336   // and to rebuild everything after all updates and creates
337   if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
338     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
339     static std::shared_ptr<Events_Message> aFinishMsg
340       (new Events_Message(Events_Loop::eventByName("FinishOperation")));
341     Events_Loop::loop()->send(aFinishMsg);
342     Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
343   }
344   // to avoid "updated" message appearance by updater
345   //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
346
347   if (!myDoc->HasOpenCommand() && myNestedNum != -1)
348     std::static_pointer_cast<Model_Session>(Model_Session::get())
349         ->setCheckTransactions(true);  // for nested transaction commit
350
351   // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
352   const std::set<std::string> aSubs = subDocuments(true);
353   std::set<std::string>::iterator aSubIter = aSubs.begin();
354   for (; aSubIter != aSubs.end(); aSubIter++)
355     subDoc(*aSubIter)->finishOperation();
356
357   if (myNestedNum != -1)  // this nested transaction is owervritten
358     myNestedNum++;
359   if (!myDoc->HasOpenCommand()) {
360     if (myNestedNum != -1) {
361       myNestedNum--;
362       compactNested();
363     }
364   } else {
365     // returns false if delta is empty and no transaction was made
366     myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand();  // && (myNestedNum == -1);
367     myTransactionsCounter++;
368   }
369 }
370
371 void Model_Document::abortOperation()
372 {
373   if (myNestedNum > 0 && !myDoc->HasOpenCommand()) {  // abort all what was done in nested
374       // first compact all nested
375     if (compactNested()) {
376       myDoc->Undo(); // undo only compacted, if not: do not undo the empty transaction
377     }
378     myDoc->ClearRedos();
379     myTransactionsCounter--;
380     myIsEmptyTr.erase(myTransactionsCounter);
381   } else {
382     if (myNestedNum == 0)  // abort only high-level
383       myNestedNum = -1;
384     myDoc->AbortCommand();
385   }
386   synchronizeFeatures(true, false); // references were not changed since transaction start
387   // abort for all subs
388   const std::set<std::string> aSubs = subDocuments(true);
389   std::set<std::string>::iterator aSubIter = aSubs.begin();
390   for (; aSubIter != aSubs.end(); aSubIter++)
391     subDoc(*aSubIter)->abortOperation();
392 }
393
394 bool Model_Document::isOperation()
395 {
396   // operation is opened for all documents: no need to check subs
397   return myDoc->HasOpenCommand() == Standard_True ;
398 }
399
400 bool Model_Document::isModified()
401 {
402   // is modified if at least one operation was commited and not undoed
403   return myTransactionsCounter != myTransactionSave || isOperation();
404 }
405
406 bool Model_Document::canUndo()
407 {
408   if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
409       && myTransactionsCounter != 0 /* for omitting the first useless transaction */)
410     return true;
411   // check other subs contains operation that can be undoed
412   const std::set<std::string> aSubs = subDocuments(true);
413   std::set<std::string>::iterator aSubIter = aSubs.begin();
414   for (; aSubIter != aSubs.end(); aSubIter++)
415     if (subDoc(*aSubIter)->canUndo())
416       return true;
417   return false;
418 }
419
420 void Model_Document::undo()
421 {
422   myTransactionsCounter--;
423   if (myNestedNum > 0)
424     myNestedNum--;
425   if (!myIsEmptyTr[myTransactionsCounter])
426     myDoc->Undo();
427   synchronizeFeatures(true, true);
428   // undo for all subs
429   const std::set<std::string> aSubs = subDocuments(true);
430   std::set<std::string>::iterator aSubIter = aSubs.begin();
431   for (; aSubIter != aSubs.end(); aSubIter++)
432     subDoc(*aSubIter)->undo();
433 }
434
435 bool Model_Document::canRedo()
436 {
437   if (myDoc->GetAvailableRedos() > 0)
438     return true;
439   // check other subs contains operation that can be redoed
440   const std::set<std::string> aSubs = subDocuments(true);
441   std::set<std::string>::iterator aSubIter = aSubs.begin();
442   for (; aSubIter != aSubs.end(); aSubIter++)
443     if (subDoc(*aSubIter)->canRedo())
444       return true;
445   return false;
446 }
447
448 void Model_Document::redo()
449 {
450   if (myNestedNum != -1)
451     myNestedNum++;
452   if (!myIsEmptyTr[myTransactionsCounter])
453     myDoc->Redo();
454   myTransactionsCounter++;
455   synchronizeFeatures(true, true);
456   // redo for all subs
457   const std::set<std::string> aSubs = subDocuments(true);
458   std::set<std::string>::iterator aSubIter = aSubs.begin();
459   for (; aSubIter != aSubs.end(); aSubIter++)
460     subDoc(*aSubIter)->redo();
461 }
462
463 /// Appenad to the array of references a new referenced label
464 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
465 {
466   Handle(TDataStd_ReferenceArray) aRefs;
467   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
468     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
469     aRefs->SetValue(0, theReferenced);
470   } else {  // extend array by one more element
471     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
472                                                                         aRefs->Upper() + 1);
473     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
474       aNewArray->SetValue(a, aRefs->Value(a));
475     }
476     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
477     aRefs->SetInternalArray(aNewArray);
478   }
479 }
480
481 FeaturePtr Model_Document::addFeature(std::string theID)
482 {
483   TDF_Label anEmptyLab;
484   FeaturePtr anEmptyFeature;
485   FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
486   if (!aFeature)
487     return aFeature;
488   std::shared_ptr<Model_Document> aDocToAdd = std::dynamic_pointer_cast<Model_Document>(
489       aFeature->documentToAdd());
490   if (aFeature) {
491     TDF_Label aFeatureLab;
492     if (!aFeature->isAction()) {  // do not add action to the data model
493       TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
494       aFeatureLab = aFeaturesLab.NewChild();
495       aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
496       // keep the feature ID to restore document later correctly
497       TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
498       aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
499       // store feature in the history of features array
500       if (aFeature->isInHistory()) {
501         AddToRefArray(aFeaturesLab, aFeatureLab);
502       }
503     }
504     if (!aFeature->isAction()) {  // do not add action to the data model
505       // event: feature is added
506       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
507       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
508     } else { // feature must be executed
509        // no creation event => updater not working, problem with remove part
510       aFeature->execute();
511     }
512   }
513   return aFeature;
514 }
515
516 /// Appenad to the array of references a new referenced label.
517 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
518 /// \returns the index of removed element
519 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
520                                   -1)
521 {
522   int aResult = -1;  // no returned
523   Handle(TDataStd_ReferenceArray) aRefs;
524   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
525     if (aRefs->Length() == 1) {  // just erase an array
526       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
527         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
528       }
529       aResult = 0;
530     } else {  // reduce the array
531       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
532                                                                           aRefs->Upper() - 1);
533       int aCount = aRefs->Lower();
534       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
535         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
536           aCount--;
537           aResult = a;
538         } else {
539           aNewArray->SetValue(aCount, aRefs->Value(a));
540         }
541       }
542       aRefs->SetInternalArray(aNewArray);
543     }
544   }
545   return aResult;
546 }
547
548 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
549 {
550   if (theCheck) {
551     // check the feature: it must have no depended objects on it
552     std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
553     for(; aResIter != theFeature->results().cend(); aResIter++) {
554       std::shared_ptr<Model_Data> aData = 
555         std::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
556       if (aData && !aData->refsToMe().empty()) {
557         Events_Error::send(
558           "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
559         return;
560       }
561     }
562   }
563
564   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
565   if (aData) {
566     TDF_Label aFeatureLabel = aData->label().Father();
567     if (myObjs.IsBound(aFeatureLabel))
568       myObjs.UnBind(aFeatureLabel);
569     else
570       return;  // not found feature => do not remove
571     // erase fields
572     theFeature->erase();
573     // erase all attributes under the label of feature
574     aFeatureLabel.ForgetAllAttributes();
575     // remove it from the references array
576     if (theFeature->isInHistory()) {
577       RemoveFromRefArray(featuresLabel(), aFeatureLabel);
578     }
579   }
580   // event: feature is deleted
581   ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
582 }
583
584 FeaturePtr Model_Document::feature(TDF_Label& theLabel) const
585 {
586   if (myObjs.IsBound(theLabel))
587     return myObjs.Find(theLabel);
588   return FeaturePtr();  // not found
589 }
590
591 ObjectPtr Model_Document::object(TDF_Label theLabel)
592 {
593   // try feature by label
594   FeaturePtr aFeature = feature(theLabel);
595   if (aFeature)
596     return feature(theLabel);
597   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
598   aFeature = feature(aFeatureLabel);
599   if (aFeature) {
600     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
601     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
602     for (; aRIter != aResults.cend(); aRIter++) {
603       std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
604           (*aRIter)->data());
605       if (aResData->label().Father().IsEqual(theLabel))
606         return *aRIter;
607     }
608   }
609   return FeaturePtr();  // not found
610 }
611
612 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
613 {
614   return Model_Application::getApplication()->getDocument(theDocID);
615 }
616
617 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
618 {
619   std::set<std::string> aResult;
620   // comment must be in any feature: it is kind
621   int anIndex = 0;
622   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
623   for (; aLabIter.More(); aLabIter.Next()) {
624     TDF_Label aFLabel = aLabIter.Value()->Label();
625     FeaturePtr aFeature = feature(aFLabel);
626     if (aFeature.get()) { // if document is closed the feature may be not in myObjs map
627       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
628       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
629       for (; aRIter != aResults.cend(); aRIter++) {
630         if ((*aRIter)->groupName() != ModelAPI_ResultPart::group()) continue;
631         if ((*aRIter)->isInHistory()) {
632           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
633           if (aPart && (!theActivatedOnly || aPart->isActivated()))
634             aResult.insert(aPart->data()->name());
635         }
636       }
637     }
638   }
639   return aResult;
640 }
641
642 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
643 {
644   // just store sub-document identifier here to manage it later
645   return std::dynamic_pointer_cast<Model_Document>(
646     Model_Application::getApplication()->getDocument(theDocID));
647 }
648
649 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
650                                  const bool theHidden)
651 {
652   if (theGroupID == ModelAPI_Feature::group()) {
653     if (theHidden) {
654       int anIndex = 0;
655       TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
656       for (; aLabIter.More(); aLabIter.Next()) {
657         if (theIndex == anIndex) {
658           TDF_Label aFLabel = aLabIter.Value()->Label();
659           return feature(aFLabel);
660         }
661         anIndex++;
662       }
663     } else {
664       Handle(TDataStd_ReferenceArray) aRefs;
665       if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
666         return ObjectPtr();
667       if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
668         return ObjectPtr();
669       TDF_Label aFeatureLabel = aRefs->Value(theIndex);
670       return feature(aFeatureLabel);
671     }
672   } else {
673     // comment must be in any feature: it is kind
674     int anIndex = 0;
675     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
676     for (; aLabIter.More(); aLabIter.Next()) {
677       TDF_Label aFLabel = aLabIter.Value()->Label();
678       FeaturePtr aFeature = feature(aFLabel);
679       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
680       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
681       for (; aRIter != aResults.cend(); aRIter++) {
682         if ((*aRIter)->groupName() != theGroupID) continue;
683         bool isIn = theHidden && (*aRIter)->isInHistory();
684         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
685           isIn = !(*aRIter)->isConcealed();
686         }
687         if (isIn) {
688           if (anIndex == theIndex)
689             return *aRIter;
690           anIndex++;
691         }
692       }
693     }
694   }
695   // not found
696   return ObjectPtr();
697 }
698
699 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
700 {
701   int aResult = 0;
702   if (theGroupID == ModelAPI_Feature::group()) {
703     if (theHidden) {
704       return myObjs.Size();
705     } else {
706       Handle(TDataStd_ReferenceArray) aRefs;
707       if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
708         return aRefs->Length();
709     }
710   } else {
711     // comment must be in any feature: it is kind
712     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
713     for (; aLabIter.More(); aLabIter.Next()) {
714       TDF_Label aFLabel = aLabIter.Value()->Label();
715       FeaturePtr aFeature = feature(aFLabel);
716       if (!aFeature) // may be on close
717         continue;
718       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
719       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
720       for (; aRIter != aResults.cend(); aRIter++) {
721         if ((*aRIter)->groupName() != theGroupID) continue;
722         bool isIn = theHidden;
723         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
724           isIn = !(*aRIter)->isConcealed();
725         }
726         if (isIn)
727           aResult++;
728       }
729     }
730   }
731   // group is not found
732   return aResult;
733 }
734
735 TDF_Label Model_Document::featuresLabel() const
736 {
737   return myDoc->Main().FindChild(TAG_OBJECTS);
738 }
739
740 void Model_Document::setUniqueName(FeaturePtr theFeature)
741 {
742   if (!theFeature->data()->name().empty())
743     return;  // not needed, name is already defined
744   std::string aName;  // result
745   // first count all objects of such kind to start with index = count + 1
746   int aNumObjects = 0;
747   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
748   for (; aFIter.More(); aFIter.Next()) {
749     if (aFIter.Value()->getKind() == theFeature->getKind())
750       aNumObjects++;
751   }
752   // generate candidate name
753   std::stringstream aNameStream;
754   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
755   aName = aNameStream.str();
756   // check this is unique, if not, increase index by 1
757   for (aFIter.Initialize(myObjs); aFIter.More();) {
758     FeaturePtr aFeature = aFIter.Value();
759     bool isSameName = aFeature->data()->name() == aName;
760     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
761       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
762       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
763       for (; aRIter != aResults.cend(); aRIter++) {
764         isSameName = (*aRIter)->data()->name() == aName;
765       }
766     }
767     if (isSameName) {
768       aNumObjects++;
769       std::stringstream aNameStream;
770       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
771       aName = aNameStream.str();
772       // reinitialize iterator to make sure a new name is unique
773       aFIter.Initialize(myObjs);
774     } else
775       aFIter.Next();
776   }
777   theFeature->data()->setName(aName);
778 }
779
780 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
781 {
782   std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
783       myID);
784   std::shared_ptr<Model_Data> aData(new Model_Data);
785   aData->setLabel(theLab.FindChild(theTag));
786   aData->setObject(theObj);
787   theObj->setDoc(aThis);
788   theObj->setData(aData);
789   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
790   if (aFeature) {
791     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
792     aFeature->initAttributes();
793   }
794 }
795
796 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
797 {
798   std::shared_ptr<ModelAPI_Document> aThis = 
799     Model_Application::getApplication()->getDocument(myID);
800   // after all updates, sends a message that groups of features were created or updated
801   std::static_pointer_cast<Model_Session>(Model_Session::get())
802     ->setCheckTransactions(false);
803   Events_Loop* aLoop = Events_Loop::loop();
804   aLoop->activateFlushes(false);
805
806   // update all objects by checking are they of labels or not
807   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
808   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
809   for (; aLabIter.More(); aLabIter.Next()) {
810     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
811     FeaturePtr aFeature;
812     if (!myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
813       // create a feature
814       aFeature = ModelAPI_Session::get()->createFeature(
815           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
816               .ToCString());
817       if (!aFeature) {  // somethig is wrong, most probably, the opened document has invalid structure
818         Events_Error::send("Invalid type of object in the document");
819         aLabIter.Value()->Label().ForgetAllAttributes();
820         continue;
821       }
822       // this must be before "setData" to redo the sketch line correctly
823       myObjs.Bind(aFeatureLabel, aFeature);
824       aNewFeatures.insert(aFeature);
825       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
826
827       // event: model is updated
828       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
829       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
830     } else {  // nothing is changed, both iterators are incremented
831       aFeature = myObjs.Find(aFeatureLabel);
832       aKeptFeatures.insert(aFeature);
833       if (theMarkUpdated) {
834         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
835         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
836       }
837     }
838   }
839   // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
840   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
841   for (; aLabIter2.More(); aLabIter2.Next()) {
842     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
843     if (myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
844       FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
845       updateResults(aFeature);
846     }
847   }
848
849   // check all features are checked: if not => it was removed
850   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
851   while (aFIter.More()) {
852     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
853         && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
854       FeaturePtr aFeature = aFIter.Value();
855       // event: model is updated
856       //if (aFeature->isInHistory()) {
857         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
858       //}
859       // results of this feature must be redisplayed (hided)
860       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
861       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
862       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
863       // redisplay also removed feature (used for sketch and AISObject)
864       ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
865       aFeature->erase();
866       // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
867       TDF_Label aLab = aFIter.Key();
868       aFIter.Next();
869       myObjs.UnBind(aLab);
870     } else
871       aFIter.Next();
872   }
873
874   if (theUpdateReferences) {
875     synchronizeBackRefs();
876   }
877
878   myExecuteFeatures = false;
879   aLoop->activateFlushes(true);
880
881   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
882   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
883   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
884   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
885   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
886   std::static_pointer_cast<Model_Session>(Model_Session::get())
887     ->setCheckTransactions(true);
888   myExecuteFeatures = true;
889 }
890
891 void Model_Document::synchronizeBackRefs()
892 {
893   std::shared_ptr<ModelAPI_Document> aThis = 
894     Model_Application::getApplication()->getDocument(myID);
895   // keeps the concealed flags of result to catch the change and create created/deleted events
896   std::list<std::pair<ResultPtr, bool> > aConcealed;
897   // first cycle: erase all data about back-references
898   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
899   for(; aFeatures.More(); aFeatures.Next()) {
900     FeaturePtr aFeature = aFeatures.Value();
901     std::shared_ptr<Model_Data> aFData = 
902       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
903     if (aFData) {
904       aFData->eraseBackReferences();
905     }
906     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
907     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
908     for (; aRIter != aResults.cend(); aRIter++) {
909       std::shared_ptr<Model_Data> aResData = 
910         std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
911       if (aResData) {
912         aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
913         aResData->eraseBackReferences();
914       }
915     }
916   }
917
918   // second cycle: set new back-references: only features may have reference, iterate only them
919   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
920   for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
921     FeaturePtr aFeature = aFeatures.Value();
922     std::shared_ptr<Model_Data> aFData = 
923       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
924     if (aFData) {
925       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
926       aFData->referencesToObjects(aRefs);
927       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
928       for(; aRefsIter != aRefs.end(); aRefsIter++) {
929         std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
930         for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
931           if (*aRefTo) {
932             std::shared_ptr<Model_Data> aRefData = 
933               std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
934             aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
935           }
936         }
937       }
938     }
939   }
940   std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
941   for(; aCIter != aConcealed.end(); aCIter++) {
942     if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
943       if (aCIter->second) { // was concealed become not => creation event
944         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
945         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
946       } else { // was not concealed become concealed => delete event
947         ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
948         // redisplay for the viewer (it must be disappeared also)
949         static Events_ID EVENT_DISP = 
950           Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
951         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
952       }
953     }
954   }
955 }
956
957 TDF_Label Model_Document::resultLabel(
958   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
959 {
960   const std::shared_ptr<Model_Data>& aData = 
961     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
962   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
963 }
964
965 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
966                                  std::shared_ptr<ModelAPI_Result> theResult,
967                                  const int theResultIndex)
968 {
969   std::shared_ptr<ModelAPI_Document> aThis = 
970     Model_Application::getApplication()->getDocument(myID);
971   theResult->setDoc(aThis);
972   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
973   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
974     theResult->data()->setName(theFeatureData->name());
975   }
976 }
977
978 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
979     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
980 {
981   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
982   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
983   ObjectPtr anOldObject = object(aLab);
984   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
985   if (anOldObject) {
986     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
987   }
988   if (!aResult) {
989     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
990     storeResult(theFeatureData, aResult, theIndex);
991   }
992   return aResult;
993 }
994
995 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
996     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
997 {
998   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
999   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1000   ObjectPtr anOldObject = object(aLab);
1001   std::shared_ptr<ModelAPI_ResultBody> aResult;
1002   if (anOldObject) {
1003     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1004   }
1005   if (!aResult) {
1006     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1007     storeResult(theFeatureData, aResult, theIndex);
1008   }
1009   return aResult;
1010 }
1011
1012 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1013     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1014 {
1015   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1016   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1017   ObjectPtr anOldObject = object(aLab);
1018   std::shared_ptr<ModelAPI_ResultPart> aResult;
1019   if (anOldObject) {
1020     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1021   }
1022   if (!aResult) {
1023     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1024     storeResult(theFeatureData, aResult, theIndex);
1025   }
1026   return aResult;
1027 }
1028
1029 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1030     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1031 {
1032   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1033   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1034   ObjectPtr anOldObject = object(aLab);
1035   std::shared_ptr<ModelAPI_ResultGroup> aResult;
1036   if (anOldObject) {
1037     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1038   }
1039   if (!aResult) {
1040     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1041     storeResult(theFeatureData, aResult, theIndex);
1042   }
1043   return aResult;
1044 }
1045
1046 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1047     const std::shared_ptr<ModelAPI_Result>& theResult)
1048 {
1049   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1050   if (aData) {
1051     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1052     return feature(aFeatureLab);
1053   }
1054   return FeaturePtr();
1055 }
1056
1057 void Model_Document::updateResults(FeaturePtr theFeature)
1058 {
1059   // for not persistent is will be done by parametric updater automatically
1060   //if (!theFeature->isPersistentResult()) return;
1061   // check the existing results and remove them if there is nothing on the label
1062   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1063   while(aResIter != theFeature->results().cend()) {
1064     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1065     if (aBody) {
1066       if (!aBody->data()->isValid()) { 
1067         // found a disappeared result => remove it
1068         theFeature->removeResult(aBody);
1069         // start iterate from beginning because iterator is corrupted by removing
1070         aResIter = theFeature->results().cbegin();
1071         continue;
1072       }
1073     }
1074     aResIter++;
1075   }
1076   // it may be on undo
1077   if (!theFeature->data() || !theFeature->data()->isValid())
1078     return;
1079   // check that results are presented on all labels
1080   int aResSize = theFeature->results().size();
1081   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1082   for(; aLabIter.More(); aLabIter.Next()) {
1083     // here must be GUID of the feature
1084     int aResIndex = aLabIter.Value().Tag() - 1;
1085     ResultPtr aNewBody;
1086     if (aResSize <= aResIndex) {
1087       TDF_Label anArgLab = aLabIter.Value();
1088       Handle(TDataStd_Comment) aGroup;
1089       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1090         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1091           aNewBody = createBody(theFeature->data(), aResIndex);
1092         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1093           aNewBody = createPart(theFeature->data(), aResIndex);
1094         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1095           theFeature->execute(); // construction shapes are needed for sketch solver
1096           break;
1097         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1098           aNewBody = createGroup(theFeature->data(), aResIndex);
1099         } else {
1100           Events_Error::send(std::string("Unknown type of result is found in the document:") +
1101             TCollection_AsciiString(aGroup->Get()).ToCString());
1102         }
1103       }
1104       if (aNewBody) {
1105         theFeature->setResult(aNewBody, aResIndex);
1106       }
1107     }
1108   }
1109 }
1110
1111 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1112 {
1113   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1114
1115 }
1116 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1117 {
1118   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1119 }
1120
1121 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1122 {
1123   myNamingNames[theName] = theLabel;
1124 }
1125
1126 TDF_Label Model_Document::findNamingName(std::string theName)
1127 {
1128   std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1129   if (aFind == myNamingNames.end())
1130     return TDF_Label(); // not found
1131   return aFind->second;
1132 }