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