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