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