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