]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Document.cpp
Salome HOME
Fix for Issue #375: abort of nested operation problem
[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     undoInternal(false);
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::undoInternal(const bool theWithSubs)
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   if (theWithSubs) {
433     synchronizeFeatures(true, true);
434     // undo for all subs
435     const std::set<std::string> aSubs = subDocuments(true);
436     std::set<std::string>::iterator aSubIter = aSubs.begin();
437     for (; aSubIter != aSubs.end(); aSubIter++)
438       subDoc(*aSubIter)->undo();
439   }
440 }
441
442 void Model_Document::undo()
443 {
444   undoInternal(true);
445 }
446
447 bool Model_Document::canRedo()
448 {
449   if (myDoc->GetAvailableRedos() > 0)
450     return true;
451   // check other subs contains operation that can be redoed
452   const std::set<std::string> aSubs = subDocuments(true);
453   std::set<std::string>::iterator aSubIter = aSubs.begin();
454   for (; aSubIter != aSubs.end(); aSubIter++)
455     if (subDoc(*aSubIter)->canRedo())
456       return true;
457   return false;
458 }
459
460 void Model_Document::redo()
461 {
462   if (!myNestedNum.empty())
463     (*myNestedNum.rbegin())++;
464   int aNumRedos = *myRedos.rbegin();
465   myRedos.pop_back();
466   myTransactions.push_back(aNumRedos);
467   for(int a = 0; a < aNumRedos; a++)
468     myDoc->Redo();
469
470   synchronizeFeatures(true, true);
471   // redo for all subs
472   const std::set<std::string> aSubs = subDocuments(true);
473   std::set<std::string>::iterator aSubIter = aSubs.begin();
474   for (; aSubIter != aSubs.end(); aSubIter++)
475     subDoc(*aSubIter)->redo();
476 }
477
478 /// Append to the array of references a new referenced label
479 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
480 {
481   Handle(TDataStd_ReferenceArray) aRefs;
482   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
483     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
484     aRefs->SetValue(0, theReferenced);
485   } else {  // extend array by one more element
486     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
487                                                                         aRefs->Upper() + 1);
488     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
489       aNewArray->SetValue(a, aRefs->Value(a));
490     }
491     aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
492     aRefs->SetInternalArray(aNewArray);
493   }
494 }
495
496 FeaturePtr Model_Document::addFeature(std::string theID)
497 {
498   TDF_Label anEmptyLab;
499   FeaturePtr anEmptyFeature;
500   FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
501   if (!aFeature)
502     return aFeature;
503   std::shared_ptr<Model_Document> aDocToAdd = std::dynamic_pointer_cast<Model_Document>(
504       aFeature->documentToAdd());
505   if (aFeature) {
506     TDF_Label aFeatureLab;
507     if (!aFeature->isAction()) {  // do not add action to the data model
508       TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
509       aFeatureLab = aFeaturesLab.NewChild();
510       aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
511       // keep the feature ID to restore document later correctly
512       TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
513       aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
514       // store feature in the history of features array
515       if (aFeature->isInHistory()) {
516         AddToRefArray(aFeaturesLab, aFeatureLab);
517       }
518     }
519     if (!aFeature->isAction()) {  // do not add action to the data model
520       // event: feature is added
521       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
522       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
523     } else { // feature must be executed
524        // no creation event => updater not working, problem with remove part
525       aFeature->execute();
526     }
527   }
528   return aFeature;
529 }
530
531 /// Appenad to the array of references a new referenced label.
532 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
533 /// \returns the index of removed element
534 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
535                                   -1)
536 {
537   int aResult = -1;  // no returned
538   Handle(TDataStd_ReferenceArray) aRefs;
539   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
540     if (aRefs->Length() == 1) {  // just erase an array
541       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
542         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
543       }
544       aResult = 0;
545     } else {  // reduce the array
546       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
547                                                                           aRefs->Upper() - 1);
548       int aCount = aRefs->Lower();
549       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
550         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
551           aCount--;
552           aResult = a;
553         } else {
554           aNewArray->SetValue(aCount, aRefs->Value(a));
555         }
556       }
557       aRefs->SetInternalArray(aNewArray);
558     }
559   }
560   return aResult;
561 }
562
563 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
564 {
565   if (theCheck) {
566     // check the feature: it must have no depended objects on it
567     std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
568     for(; aResIter != theFeature->results().cend(); aResIter++) {
569       std::shared_ptr<Model_Data> aData = 
570         std::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
571       if (aData && !aData->refsToMe().empty()) {
572         Events_Error::send(
573           "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
574         return;
575       }
576     }
577   }
578
579   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
580   if (aData) {
581     TDF_Label aFeatureLabel = aData->label().Father();
582     if (myObjs.IsBound(aFeatureLabel))
583       myObjs.UnBind(aFeatureLabel);
584     else
585       return;  // not found feature => do not remove
586     // erase fields
587     theFeature->erase();
588     // erase all attributes under the label of feature
589     aFeatureLabel.ForgetAllAttributes();
590     // remove it from the references array
591     if (theFeature->isInHistory()) {
592       RemoveFromRefArray(featuresLabel(), aFeatureLabel);
593     }
594   }
595   // event: feature is deleted
596   ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
597 }
598
599 FeaturePtr Model_Document::feature(TDF_Label& theLabel) const
600 {
601   if (myObjs.IsBound(theLabel))
602     return myObjs.Find(theLabel);
603   return FeaturePtr();  // not found
604 }
605
606 ObjectPtr Model_Document::object(TDF_Label theLabel)
607 {
608   // try feature by label
609   FeaturePtr aFeature = feature(theLabel);
610   if (aFeature)
611     return feature(theLabel);
612   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
613   aFeature = feature(aFeatureLabel);
614   if (aFeature) {
615     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
616     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
617     for (; aRIter != aResults.cend(); aRIter++) {
618       std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
619           (*aRIter)->data());
620       if (aResData->label().Father().IsEqual(theLabel))
621         return *aRIter;
622     }
623   }
624   return FeaturePtr();  // not found
625 }
626
627 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
628 {
629   return Model_Application::getApplication()->getDocument(theDocID);
630 }
631
632 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
633 {
634   std::set<std::string> aResult;
635   // comment must be in any feature: it is kind
636   int anIndex = 0;
637   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
638   for (; aLabIter.More(); aLabIter.Next()) {
639     TDF_Label aFLabel = aLabIter.Value()->Label();
640     FeaturePtr aFeature = feature(aFLabel);
641     if (aFeature.get()) { // if document is closed the feature may be not in myObjs map
642       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
643       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
644       for (; aRIter != aResults.cend(); aRIter++) {
645         if ((*aRIter)->groupName() != ModelAPI_ResultPart::group()) continue;
646         if ((*aRIter)->isInHistory()) {
647           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
648           if (aPart && (!theActivatedOnly || aPart->isActivated()))
649             aResult.insert(aPart->data()->name());
650         }
651       }
652     }
653   }
654   return aResult;
655 }
656
657 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
658 {
659   // just store sub-document identifier here to manage it later
660   return std::dynamic_pointer_cast<Model_Document>(
661     Model_Application::getApplication()->getDocument(theDocID));
662 }
663
664 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
665                                  const bool theHidden)
666 {
667   if (theGroupID == ModelAPI_Feature::group()) {
668     if (theHidden) {
669       int anIndex = 0;
670       TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
671       for (; aLabIter.More(); aLabIter.Next()) {
672         if (theIndex == anIndex) {
673           TDF_Label aFLabel = aLabIter.Value()->Label();
674           return feature(aFLabel);
675         }
676         anIndex++;
677       }
678     } else {
679       Handle(TDataStd_ReferenceArray) aRefs;
680       if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
681         return ObjectPtr();
682       if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
683         return ObjectPtr();
684       TDF_Label aFeatureLabel = aRefs->Value(theIndex);
685       return feature(aFeatureLabel);
686     }
687   } else {
688     // comment must be in any feature: it is kind
689     int anIndex = 0;
690     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
691     for (; aLabIter.More(); aLabIter.Next()) {
692       TDF_Label aFLabel = aLabIter.Value()->Label();
693       FeaturePtr aFeature = feature(aFLabel);
694       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
695       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
696       for (; aRIter != aResults.cend(); aRIter++) {
697         if ((*aRIter)->groupName() != theGroupID) continue;
698         bool isIn = theHidden && (*aRIter)->isInHistory();
699         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
700           isIn = !(*aRIter)->isConcealed();
701         }
702         if (isIn) {
703           if (anIndex == theIndex)
704             return *aRIter;
705           anIndex++;
706         }
707       }
708     }
709   }
710   // not found
711   return ObjectPtr();
712 }
713
714 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
715 {
716   int aResult = 0;
717   if (theGroupID == ModelAPI_Feature::group()) {
718     if (theHidden) {
719       return myObjs.Size();
720     } else {
721       Handle(TDataStd_ReferenceArray) aRefs;
722       if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
723         return aRefs->Length();
724     }
725   } else {
726     // comment must be in any feature: it is kind
727     TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
728     for (; aLabIter.More(); aLabIter.Next()) {
729       TDF_Label aFLabel = aLabIter.Value()->Label();
730       FeaturePtr aFeature = feature(aFLabel);
731       if (!aFeature) // may be on close
732         continue;
733       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
734       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
735       for (; aRIter != aResults.cend(); aRIter++) {
736         if ((*aRIter)->groupName() != theGroupID) continue;
737         bool isIn = theHidden;
738         if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
739           isIn = !(*aRIter)->isConcealed();
740         }
741         if (isIn)
742           aResult++;
743       }
744     }
745   }
746   // group is not found
747   return aResult;
748 }
749
750 TDF_Label Model_Document::featuresLabel() const
751 {
752   return myDoc->Main().FindChild(TAG_OBJECTS);
753 }
754
755 void Model_Document::setUniqueName(FeaturePtr theFeature)
756 {
757   if (!theFeature->data()->name().empty())
758     return;  // not needed, name is already defined
759   std::string aName;  // result
760   // first count all objects of such kind to start with index = count + 1
761   int aNumObjects = 0;
762   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
763   for (; aFIter.More(); aFIter.Next()) {
764     if (aFIter.Value()->getKind() == theFeature->getKind())
765       aNumObjects++;
766   }
767   // generate candidate name
768   std::stringstream aNameStream;
769   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
770   aName = aNameStream.str();
771   // check this is unique, if not, increase index by 1
772   for (aFIter.Initialize(myObjs); aFIter.More();) {
773     FeaturePtr aFeature = aFIter.Value();
774     bool isSameName = aFeature->data()->name() == aName;
775     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
776       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
777       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
778       for (; aRIter != aResults.cend(); aRIter++) {
779         isSameName = (*aRIter)->data()->name() == aName;
780       }
781     }
782     if (isSameName) {
783       aNumObjects++;
784       std::stringstream aNameStream;
785       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
786       aName = aNameStream.str();
787       // reinitialize iterator to make sure a new name is unique
788       aFIter.Initialize(myObjs);
789     } else
790       aFIter.Next();
791   }
792   theFeature->data()->setName(aName);
793 }
794
795 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
796 {
797   std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
798       myID);
799   std::shared_ptr<Model_Data> aData(new Model_Data);
800   aData->setLabel(theLab.FindChild(theTag));
801   aData->setObject(theObj);
802   theObj->setDoc(aThis);
803   theObj->setData(aData);
804   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
805   if (aFeature) {
806     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
807     aFeature->initAttributes();
808   }
809 }
810
811 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
812 {
813   std::shared_ptr<ModelAPI_Document> aThis = 
814     Model_Application::getApplication()->getDocument(myID);
815   // after all updates, sends a message that groups of features were created or updated
816   std::static_pointer_cast<Model_Session>(Model_Session::get())
817     ->setCheckTransactions(false);
818   Events_Loop* aLoop = Events_Loop::loop();
819   aLoop->activateFlushes(false);
820
821   // update all objects by checking are they of labels or not
822   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
823   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
824   for (; aLabIter.More(); aLabIter.Next()) {
825     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
826     FeaturePtr aFeature;
827     if (!myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
828       // create a feature
829       aFeature = ModelAPI_Session::get()->createFeature(
830           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
831               .ToCString());
832       if (!aFeature) {  // somethig is wrong, most probably, the opened document has invalid structure
833         Events_Error::send("Invalid type of object in the document");
834         aLabIter.Value()->Label().ForgetAllAttributes();
835         continue;
836       }
837       // this must be before "setData" to redo the sketch line correctly
838       myObjs.Bind(aFeatureLabel, aFeature);
839       aNewFeatures.insert(aFeature);
840       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
841
842       // event: model is updated
843       static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
844       ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
845     } else {  // nothing is changed, both iterators are incremented
846       aFeature = myObjs.Find(aFeatureLabel);
847       aKeptFeatures.insert(aFeature);
848       if (theMarkUpdated) {
849         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
850         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
851       }
852     }
853   }
854   // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
855   std::list<FeaturePtr> aComposites; // composites must be updated after their subs (issue 360)
856   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
857   for (; aLabIter2.More(); aLabIter2.Next()) {
858     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
859     if (myObjs.IsBound(aFeatureLabel)) {  // a new feature is inserted
860       FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
861       if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature).get())
862         aComposites.push_back(aFeature);
863       updateResults(aFeature);
864     }
865   }
866   std::list<FeaturePtr>::iterator aComposite = aComposites.begin();
867   for(; aComposite != aComposites.end(); aComposite++) {
868     updateResults(*aComposite);
869   }
870
871   // check all features are checked: if not => it was removed
872   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
873   while (aFIter.More()) {
874     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
875         && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
876       FeaturePtr aFeature = aFIter.Value();
877       // event: model is updated
878       //if (aFeature->isInHistory()) {
879         ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
880       //}
881       // results of this feature must be redisplayed (hided)
882       static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
883       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
884       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
885       // redisplay also removed feature (used for sketch and AISObject)
886       ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
887       aFeature->erase();
888       // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
889       TDF_Label aLab = aFIter.Key();
890       aFIter.Next();
891       myObjs.UnBind(aLab);
892     } else
893       aFIter.Next();
894   }
895
896   if (theUpdateReferences) {
897     synchronizeBackRefs();
898   }
899
900   myExecuteFeatures = false;
901   aLoop->activateFlushes(true);
902
903   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
904   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
905   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
906   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
907   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
908   std::static_pointer_cast<Model_Session>(Model_Session::get())
909     ->setCheckTransactions(true);
910   myExecuteFeatures = true;
911 }
912
913 void Model_Document::synchronizeBackRefs()
914 {
915   std::shared_ptr<ModelAPI_Document> aThis = 
916     Model_Application::getApplication()->getDocument(myID);
917   // keeps the concealed flags of result to catch the change and create created/deleted events
918   std::list<std::pair<ResultPtr, bool> > aConcealed;
919   // first cycle: erase all data about back-references
920   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
921   for(; aFeatures.More(); aFeatures.Next()) {
922     FeaturePtr aFeature = aFeatures.Value();
923     std::shared_ptr<Model_Data> aFData = 
924       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
925     if (aFData) {
926       aFData->eraseBackReferences();
927     }
928     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
929     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
930     for (; aRIter != aResults.cend(); aRIter++) {
931       std::shared_ptr<Model_Data> aResData = 
932         std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
933       if (aResData) {
934         aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
935         aResData->eraseBackReferences();
936       }
937     }
938   }
939
940   // second cycle: set new back-references: only features may have reference, iterate only them
941   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
942   for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
943     FeaturePtr aFeature = aFeatures.Value();
944     std::shared_ptr<Model_Data> aFData = 
945       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
946     if (aFData) {
947       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
948       aFData->referencesToObjects(aRefs);
949       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
950       for(; aRefsIter != aRefs.end(); aRefsIter++) {
951         std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
952         for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
953           if (*aRefTo) {
954             std::shared_ptr<Model_Data> aRefData = 
955               std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
956             aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
957           }
958         }
959       }
960     }
961   }
962   std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
963   for(; aCIter != aConcealed.end(); aCIter++) {
964     if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
965       if (aCIter->second) { // was concealed become not => creation event
966         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
967         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
968       } else { // was not concealed become concealed => delete event
969         ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
970         // redisplay for the viewer (it must be disappeared also)
971         static Events_ID EVENT_DISP = 
972           Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
973         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
974       }
975     }
976   }
977 }
978
979 TDF_Label Model_Document::resultLabel(
980   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
981 {
982   const std::shared_ptr<Model_Data>& aData = 
983     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
984   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
985 }
986
987 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
988                                  std::shared_ptr<ModelAPI_Result> theResult,
989                                  const int theResultIndex)
990 {
991   std::shared_ptr<ModelAPI_Document> aThis = 
992     Model_Application::getApplication()->getDocument(myID);
993   theResult->setDoc(aThis);
994   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
995   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
996     theResult->data()->setName(theFeatureData->name());
997   }
998 }
999
1000 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1001     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1002 {
1003   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1004   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
1005   ObjectPtr anOldObject = object(aLab);
1006   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
1007   if (anOldObject) {
1008     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
1009   }
1010   if (!aResult) {
1011     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1012     storeResult(theFeatureData, aResult, theIndex);
1013   }
1014   return aResult;
1015 }
1016
1017 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1018     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1019 {
1020   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1021   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1022   ObjectPtr anOldObject = object(aLab);
1023   std::shared_ptr<ModelAPI_ResultBody> aResult;
1024   if (anOldObject) {
1025     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1026   }
1027   if (!aResult) {
1028     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1029     storeResult(theFeatureData, aResult, theIndex);
1030   }
1031   return aResult;
1032 }
1033
1034 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1035     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1036 {
1037   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1038   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1039   ObjectPtr anOldObject = object(aLab);
1040   std::shared_ptr<ModelAPI_ResultPart> aResult;
1041   if (anOldObject) {
1042     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1043   }
1044   if (!aResult) {
1045     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1046     storeResult(theFeatureData, aResult, theIndex);
1047   }
1048   return aResult;
1049 }
1050
1051 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1052     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1053 {
1054   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1055   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1056   ObjectPtr anOldObject = object(aLab);
1057   std::shared_ptr<ModelAPI_ResultGroup> aResult;
1058   if (anOldObject) {
1059     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1060   }
1061   if (!aResult) {
1062     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1063     storeResult(theFeatureData, aResult, theIndex);
1064   }
1065   return aResult;
1066 }
1067
1068 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1069     const std::shared_ptr<ModelAPI_Result>& theResult)
1070 {
1071   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1072   if (aData) {
1073     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1074     return feature(aFeatureLab);
1075   }
1076   return FeaturePtr();
1077 }
1078
1079 void Model_Document::updateResults(FeaturePtr theFeature)
1080 {
1081   // for not persistent is will be done by parametric updater automatically
1082   //if (!theFeature->isPersistentResult()) return;
1083   // check the existing results and remove them if there is nothing on the label
1084   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1085   while(aResIter != theFeature->results().cend()) {
1086     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1087     if (aBody) {
1088       if (!aBody->data()->isValid()) { 
1089         // found a disappeared result => remove it
1090         theFeature->removeResult(aBody);
1091         // start iterate from beginning because iterator is corrupted by removing
1092         aResIter = theFeature->results().cbegin();
1093         continue;
1094       }
1095     }
1096     aResIter++;
1097   }
1098   // it may be on undo
1099   if (!theFeature->data() || !theFeature->data()->isValid())
1100     return;
1101   // check that results are presented on all labels
1102   int aResSize = theFeature->results().size();
1103   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1104   for(; aLabIter.More(); aLabIter.Next()) {
1105     // here must be GUID of the feature
1106     int aResIndex = aLabIter.Value().Tag() - 1;
1107     ResultPtr aNewBody;
1108     if (aResSize <= aResIndex) {
1109       TDF_Label anArgLab = aLabIter.Value();
1110       Handle(TDataStd_Comment) aGroup;
1111       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1112         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1113           aNewBody = createBody(theFeature->data(), aResIndex);
1114         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1115           aNewBody = createPart(theFeature->data(), aResIndex);
1116         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1117           theFeature->execute(); // construction shapes are needed for sketch solver
1118           break;
1119         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1120           aNewBody = createGroup(theFeature->data(), aResIndex);
1121         } else {
1122           Events_Error::send(std::string("Unknown type of result is found in the document:") +
1123             TCollection_AsciiString(aGroup->Get()).ToCString());
1124         }
1125       }
1126       if (aNewBody) {
1127         theFeature->setResult(aNewBody, aResIndex);
1128       }
1129     }
1130   }
1131 }
1132
1133 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1134 {
1135   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1136
1137 }
1138 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1139 {
1140   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1141 }
1142
1143 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1144 {
1145   myNamingNames[theName] = theLabel;
1146 }
1147
1148 TDF_Label Model_Document::findNamingName(std::string theName)
1149 {
1150   std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1151   if (aFind == myNamingNames.end())
1152     return TDF_Label(); // not found
1153   return aFind->second;
1154 }
1155
1156 ResultPtr Model_Document::findByName(const std::string theName)
1157 {
1158   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myObjs);
1159   for(; anObjIter.More(); anObjIter.Next()) {
1160     FeaturePtr& aFeature = anObjIter.ChangeValue();
1161     if (!aFeature) // may be on close
1162       continue;
1163     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
1164     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
1165     for (; aRIter != aResults.cend(); aRIter++) {
1166       if (aRIter->get() && (*aRIter)->data() && (*aRIter)->data()->isValid() &&
1167           (*aRIter)->data()->name() == theName) {
1168         return *aRIter;
1169       }
1170     }
1171   }
1172   // not found
1173   return ResultPtr();
1174 }