Salome HOME
Moving features to a folder has been implemented (Task 2.3. Ability to put consecutiv...
[modules/shaper.git] / src / Model / Model_Objects.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <Model_Objects.h>
22 #include <Model_Data.h>
23 #include <Model_Document.h>
24 #include <Model_Events.h>
25 #include <Model_Session.h>
26 #include <Model_ResultPart.h>
27 #include <Model_ResultConstruction.h>
28 #include <Model_ResultBody.h>
29 #include <Model_ResultCompSolid.h>
30 #include <Model_ResultGroup.h>
31 #include <Model_ResultField.h>
32 #include <Model_ResultParameter.h>
33 #include <ModelAPI_Validator.h>
34 #include <ModelAPI_CompositeFeature.h>
35 #include <ModelAPI_Tools.h>
36
37 #include <Events_Loop.h>
38 #include <Events_InfoMessage.h>
39
40 #include <TDataStd_Integer.hxx>
41 #include <TDataStd_Comment.hxx>
42 #include <TDF_ChildIDIterator.hxx>
43 #include <TDataStd_ReferenceArray.hxx>
44 #include <TDataStd_HLabelArray1.hxx>
45 #include <TDataStd_Name.hxx>
46 #include <TDF_Reference.hxx>
47 #include <TDF_ChildIDIterator.hxx>
48 #include <TDF_LabelMapHasher.hxx>
49 #include <TDF_LabelMap.hxx>
50 #include <TDF_ListIteratorOfLabelList.hxx>
51
52 static const std::string& groupNameFoldering(const std::string& theGroupID,
53                                              const bool theAllowFolder)
54 {
55   if (theAllowFolder) {
56     static std::map<std::string, std::string> aNames;
57     std::map<std::string, std::string>::const_iterator aFound = aNames.find(theGroupID);
58     if (aFound == aNames.end()) {
59       aNames[theGroupID] = std::string("__") + theGroupID;
60       aFound = aNames.find(theGroupID);
61     }
62     return aFound->second;
63   }
64   return theGroupID;
65 }
66
67
68 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
69
70 // feature sub-labels
71 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
72 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
73
74 ///
75 /// 0:1:2 - where features are located
76 /// 0:1:2:N:1 - data of the feature N
77 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
78
79 Model_Objects::Model_Objects(TDF_Label theMainLab) : myMain(theMainLab)
80 {
81 }
82
83 void Model_Objects::setOwner(DocumentPtr theDoc)
84 {
85   myDoc = theDoc;
86   // update all fields and recreate features and result objects if needed
87   TDF_LabelList aNoUpdated;
88   synchronizeFeatures(aNoUpdated, true, true, true, true);
89   myHistory.clear();
90 }
91
92 Model_Objects::~Model_Objects()
93 {
94   // delete all features of this document
95   Events_Loop* aLoop = Events_Loop::loop();
96   // erase one by one to avoid access from the feature destructor itself from he map
97   // blocks the flush signals to avoid the temporary objects visualization in the viewer
98   // they should not be shown in order to do not lose highlight by erasing them
99   bool isActive = aLoop->activateFlushes(false);
100
101   while(!myFeatures.IsEmpty()) {
102     NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myFeatures);
103     FeaturePtr aFeature = aFeaturesIter.Value();
104     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
105     ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
106     ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
107     aFeature->removeResults(0, false);
108     aFeature->erase();
109     myFeatures.UnBind(aFeaturesIter.Key());
110   }
111   while (!myFolders.IsEmpty()) {
112     NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFoldersIter(myFolders);
113     ObjectPtr aFolder = aFoldersIter.Value();
114     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
115     ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Folder::group());
116     ModelAPI_EventCreator::get()->sendUpdated(aFolder, EVENT_DISP);
117     aFolder->erase();
118     myFolders.UnBind(aFoldersIter.Key());
119   }
120   myHistory.clear();
121   aLoop->activateFlushes(isActive);
122   // erase update, because features are destroyed and update should not performed for them anywhere
123   aLoop->eraseMessages(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
124   aLoop->eraseMessages(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
125   // deleted and redisplayed is correctly performed: they know that features are destroyed
126   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
127   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
128
129 }
130
131 /// Appends to the array of references a new referenced label
132 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced, TDF_Label& thePrevLab)
133 {
134   Handle(TDataStd_ReferenceArray) aRefs;
135   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
136     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
137     aRefs->SetValue(0, theReferenced);
138   } else {  // extend array by one more element
139     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
140                                                                         aRefs->Upper() + 1);
141     int aPassedPrev = 0; // prev feature is found and passed
142     if (thePrevLab.IsNull()) { // null means that inserted feature must be the first
143       aNewArray->SetValue(aRefs->Lower(), theReferenced);
144       aPassedPrev = 1;
145     }
146     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
147       aNewArray->SetValue(a + aPassedPrev, aRefs->Value(a));
148       if (!aPassedPrev && aRefs->Value(a).IsEqual(thePrevLab)) {
149         aPassedPrev = 1;
150         aNewArray->SetValue(a + 1, theReferenced);
151       }
152     }
153     if (!aPassedPrev) // not found: unknown situation
154       aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
155     aRefs->SetInternalArray(aNewArray);
156   }
157 }
158
159 void Model_Objects::addFeature(FeaturePtr theFeature, const FeaturePtr theAfterThis)
160 {
161   if (!theFeature->isAction()) {  // do not add action to the data model
162     TDF_Label aFeaturesLab = featuresLabel();
163     TDF_Label aFeatureLab = aFeaturesLab.NewChild();
164     // store feature in the features array: before "initData" because in macro features
165     // in initData it creates new features, appeared later than this
166     TDF_Label aPrevFeateureLab;
167     if (theAfterThis.get()) { // searching for the previous feature label
168       std::shared_ptr<Model_Data> aPrevData =
169         std::dynamic_pointer_cast<Model_Data>(theAfterThis->data());
170       if (aPrevData.get()) {
171         aPrevFeateureLab = aPrevData->label().Father();
172       }
173     }
174     AddToRefArray(aFeaturesLab, aFeatureLab, aPrevFeateureLab);
175
176     // keep the feature ID to restore document later correctly
177     TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
178     myFeatures.Bind(aFeatureLab, theFeature);
179     // must be before the event sending: for OB the feature is already added
180     updateHistory(ModelAPI_Feature::group());
181     // do not change the order:
182     // initData()
183     // sendUpdated()
184     // during python script with fillet constraint feature data should be
185     // initialized before using it in GUI
186
187     // must be after binding to the map because of "Box" macro feature that
188     // creates other features in "initData"
189     initData(theFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
190     // event: feature is added, mist be before "initData" to update OB correctly on Duplicate:
191     // first new part, then the content
192     static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
193     ModelAPI_EventCreator::get()->sendUpdated(theFeature, anEvent);
194   } else { // make feature has not-null data anyway
195     theFeature->setData(Model_Data::invalidData());
196     theFeature->setDoc(myDoc);
197   }
198 }
199
200 /// Appends to the array of references a new referenced label.
201 /// If theIndex is not -1, removes element at this index, not theReferenced.
202 /// \returns the index of removed element
203 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced,
204   const int theIndex = -1)
205 {
206   int aResult = -1;  // no returned
207   Handle(TDataStd_ReferenceArray) aRefs;
208   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
209     if (aRefs->Length() == 1) {  // just erase an array
210       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
211         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
212       }
213       aResult = 0;
214     } else {  // reduce the array
215       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
216                                                                           aRefs->Upper() - 1);
217       int aCount = aRefs->Lower();
218       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
219         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
220           aCount--;
221           aResult = a;
222         } else {
223           aNewArray->SetValue(aCount, aRefs->Value(a));
224         }
225       }
226       aRefs->SetInternalArray(aNewArray);
227     }
228   }
229   return aResult;
230 }
231
232 void Model_Objects::refsToFeature(FeaturePtr theFeature,
233   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
234 {
235   // check the feature: it must have no depended objects on it
236   // the dependencies can be in the feature results
237   std::list<ResultPtr> aResults;
238   ModelAPI_Tools::allResults(theFeature, aResults);
239   std::list<ResultPtr>::const_iterator aResIter = aResults.cbegin();
240   for (; aResIter != aResults.cend(); aResIter++) {
241     ResultPtr aResult = (*aResIter);
242     std::shared_ptr<Model_Data> aData =
243         std::dynamic_pointer_cast<Model_Data>(aResult->data());
244     if (aData.get() != NULL) {
245       const std::set<AttributePtr>& aRefs = aData->refsToMe();
246       std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
247       for (; aRefIt != aRefLast; aRefIt++) {
248         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
249         if (aFeature.get() != NULL)
250           theRefs.insert(aFeature);
251       }
252     }
253   }
254   // the dependencies can be in the feature itself
255   std::shared_ptr<Model_Data> aData =
256       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
257   if (aData.get() && !aData->refsToMe().empty()) {
258     const std::set<AttributePtr>& aRefs = aData->refsToMe();
259     std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
260     for (; aRefIt != aRefLast; aRefIt++) {
261       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
262       if (aFeature.get() != NULL)
263         theRefs.insert(aFeature);
264     }
265   }
266
267   if (!theRefs.empty() && isSendError) {
268     Events_InfoMessage("Model_Objects",
269       "Feature '%1' is used and can not be deleted").arg(theFeature->data()->name()).send();
270   }
271 }
272
273 void Model_Objects::removeFeature(FeaturePtr theFeature)
274 {
275   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
276   if (aData.get() && aData->isValid()) {
277     // checking that the sub-element of composite feature is removed: if yes, inform the owner
278     std::set<std::shared_ptr<ModelAPI_Feature> > aRefs;
279     refsToFeature(theFeature, aRefs, false);
280     std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aRefIter = aRefs.begin();
281     for(; aRefIter != aRefs.end(); aRefIter++) {
282       std::shared_ptr<ModelAPI_CompositeFeature> aComposite =
283         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aRefIter);
284       if (aComposite.get() && aComposite->isSub(theFeature)) {
285         aComposite->removeFeature(theFeature);
286       }
287     }
288     // this must be before erase since theFeature erasing removes all information about
289     // the feature results and groups of results
290     // To reproduce: create sketch, extrusion, remove sketch => constructions tree is not updated
291     clearHistory(theFeature);
292     // erase fields
293     theFeature->erase();
294
295     TDF_Label aFeatureLabel = aData->label().Father();
296     if (myFeatures.IsBound(aFeatureLabel))
297       myFeatures.UnBind(aFeatureLabel);
298
299     static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
300     ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
301     // erase all attributes under the label of feature
302     aFeatureLabel.ForgetAllAttributes();
303     // remove it from the references array
304     RemoveFromRefArray(featuresLabel(), aFeatureLabel);
305     // event: feature is deleted
306     ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
307     updateHistory(ModelAPI_Feature::group());
308   }
309 }
310
311 void Model_Objects::eraseAllFeatures()
312 {
313   static Events_ID kDispEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
314   static const ModelAPI_EventCreator* kCreator = ModelAPI_EventCreator::get();
315   // make all features invalid (like deleted)
316   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
317   for(; aFIter.More(); aFIter.Next()) {
318     FeaturePtr aFeature = aFIter.Value();
319     std::list<ResultPtr> aResList;
320     ModelAPI_Tools::allResults(aFeature, aResList);
321     std::list<ResultPtr>::iterator aRIter = aResList.begin();
322     for(; aRIter != aResList.end(); aRIter++) {
323       ResultPtr aRes = *aRIter;
324       if (aRes && aRes->data()->isValid()) {
325         kCreator->sendDeleted(myDoc, aRes->groupName());
326         kCreator->sendUpdated(aRes, kDispEvent);
327         aRes->setData(aRes->data()->invalidPtr());
328
329       }
330     }
331     kCreator->sendUpdated(aFeature, kDispEvent);
332     aFeature->setData(aFeature->data()->invalidPtr());
333   }
334   kCreator->sendDeleted(myDoc, ModelAPI_Feature::group());
335   myFeatures.Clear(); // just remove features without modification of DS
336   updateHistory(ModelAPI_Feature::group());
337 }
338
339 void Model_Objects::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
340 {
341   TDF_Label aFeaturesLab = featuresLabel();
342   Handle(TDataStd_ReferenceArray) aRefs;
343   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
344     return;
345   TDF_Label anAfterLab, aMovedLab =
346     std::dynamic_pointer_cast<Model_Data>(theMoved->data())->label().Father();
347   if (theAfterThis.get())
348     anAfterLab = std::dynamic_pointer_cast<Model_Data>(theAfterThis->data())->label().Father();
349
350   Handle(TDataStd_HLabelArray1) aNewArray =
351     new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper());
352   int aPassedMovedFrom = 0; // the prev feature location is found and passed
353   int aPassedMovedTo = 0; // the feature is added and this location is passed
354   if (!theAfterThis.get()) { // null means that inserted feature must be the first
355     aNewArray->SetValue(aRefs->Lower(), aMovedLab);
356     aPassedMovedTo = 1;
357   }
358   for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
359     if (aPassedMovedTo == 0 && aRefs->Value(a) == anAfterLab) { // add two
360       aPassedMovedTo++;
361       aNewArray->SetValue(a - aPassedMovedFrom, anAfterLab);
362       if (a + 1 - aPassedMovedFrom <= aRefs->Upper())
363         aNewArray->SetValue(a + 1 - aPassedMovedFrom, aMovedLab);
364     } else if (aPassedMovedFrom == 0 && aRefs->Value(a) == aMovedLab) { // skip
365       aPassedMovedFrom++;
366     } else { // just copy one
367       if (a - aPassedMovedFrom + aPassedMovedTo <= aRefs->Upper())
368         aNewArray->SetValue(a - aPassedMovedFrom + aPassedMovedTo, aRefs->Value(a));
369     }
370   }
371   if (!aPassedMovedFrom || !aPassedMovedTo) {// not found: unknown situation
372     if (!aPassedMovedFrom) {
373       static std::string aMovedFromError("The moved feature is not found");
374       Events_InfoMessage("Model_Objects", aMovedFromError).send();
375     } else {
376       static std::string aMovedToError("The 'after' feature for movement is not found");
377       Events_InfoMessage("Model_Objects", aMovedToError).send();
378     }
379     return;
380   }
381   // store the new array
382   aRefs->SetInternalArray(aNewArray);
383   // update the feature and the history
384   clearHistory(theMoved);
385   // make sure all (selection) attributes of moved feature will be updated
386   static Events_ID kUpdateSelection = Events_Loop::loop()->eventByName(EVENT_UPDATE_SELECTION);
387   ModelAPI_EventCreator::get()->sendUpdated(theMoved, kUpdateSelection, false);
388   ModelAPI_EventCreator::get()->sendReordered(theMoved);
389 }
390
391 void Model_Objects::clearHistory(ObjectPtr theObj)
392 {
393   if (theObj.get()) {
394     const std::string aGroup = theObj->groupName();
395     updateHistory(aGroup);
396
397     if (theObj->groupName() == ModelAPI_Feature::group()) { // clear results group of the feature
398       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
399       std::string aResultGroup = featureResultGroup(aFeature);
400       if (!aResultGroup.empty()) {
401         std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter =
402           myHistory.find(aResultGroup);
403         if (aHIter != myHistory.end())
404           myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
405       }
406     }
407   }
408 }
409
410 void Model_Objects::createHistory(const std::string& theGroupID)
411 {
412   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroupID);
413   if (aHIter == myHistory.end()) {
414     std::vector<ObjectPtr> aResult;
415     std::vector<ObjectPtr> aResultOutOfFolder;
416     FeaturePtr aLastFeatureInFolder;
417     // iterate the array of references and get feature by feature from the array
418     bool isFeature = theGroupID == ModelAPI_Feature::group();
419     Handle(TDataStd_ReferenceArray) aRefs;
420     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
421       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
422         FeaturePtr aFeature = feature(aRefs->Value(a));
423         if (aFeature.get()) {
424           // if feature is in sub-component, remove it from history:
425           // it is in sub-tree of sub-component
426           bool isSub = ModelAPI_Tools::compositeOwner(aFeature).get() != NULL;
427           if (isFeature) { // here may be also disabled features
428             if (!isSub && aFeature->isInHistory()) {
429               aResult.push_back(aFeature);
430               // the feature is out of the folders
431               if (aLastFeatureInFolder.get() == NULL)
432                 aResultOutOfFolder.push_back(aFeature);
433             }
434           } else if (!aFeature->isDisabled()) { // iterate all results of not-disabled feature
435             // construction results of sub-features should not be in the tree
436             if (!isSub || theGroupID != ModelAPI_ResultConstruction::group()) {
437               // do not use reference to the list here since results can be changed by "isConcealed"
438               const std::list<std::shared_ptr<ModelAPI_Result> > aResults = aFeature->results();
439               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator
440                 aRIter = aResults.begin();
441               for (; aRIter != aResults.cend(); aRIter++) {
442                 ResultPtr aRes = *aRIter;
443                 if (aRes->groupName() != theGroupID) break; // feature have only same group results
444                 if (!aRes->isDisabled() && aRes->isInHistory() && !aRes->isConcealed()) {
445                   aResult.push_back(*aRIter);
446                 }
447               }
448             }
449           }
450
451           // the feature closes the folder, so the next features will be treated as out-of-folder
452           if (aLastFeatureInFolder.get() && aLastFeatureInFolder == aFeature)
453             aLastFeatureInFolder = FeaturePtr();
454
455         } else {
456           // it may be a folder
457           ObjectPtr aFolder = folder(aRefs->Value(a));
458           if (aFolder.get()) {
459             aResult.push_back(aFolder);
460             if (theGroupID != ModelAPI_Folder::group())
461               aResultOutOfFolder.push_back(aFolder);
462
463             // get the last feature in the folder
464             AttributeReferencePtr aLastFeatAttr =
465                 aFolder->data()->reference(ModelAPI_Folder::LAST_FEATURE_ID());
466             if (aLastFeatAttr)
467               aLastFeatureInFolder = ModelAPI_Feature::feature(aLastFeatAttr->value());
468           }
469         }
470       }
471     }
472     // to be sure that isConcealed did not update the history (issue 1089) during the iteration
473     if (myHistory.find(theGroupID) == myHistory.end()) {
474       myHistory[theGroupID] = aResult;
475
476       // store the features placed out of any folder
477       const std::string& anOutOfFolderGroupID = groupNameFoldering(theGroupID, true);
478       myHistory[anOutOfFolderGroupID] = aResultOutOfFolder;
479     }
480   }
481 }
482
483 void Model_Objects::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
484 {
485   clearHistory(theObject);
486 }
487
488 void Model_Objects::updateHistory(const std::string theGroup)
489 {
490   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroup);
491   if (aHIter != myHistory.end()) {
492     myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
493
494     // erase history for the group of objects placed out of any folder
495     const std::string& anOutOfFolderGroupID = groupNameFoldering(theGroup, true);
496     myHistory.erase(anOutOfFolderGroupID);
497   }
498 }
499
500 ObjectPtr Model_Objects::folder(TDF_Label theLabel) const
501 {
502   if (myFolders.IsBound(theLabel))
503     return myFolders.Find(theLabel);
504   return ObjectPtr();
505 }
506
507 FeaturePtr Model_Objects::feature(TDF_Label theLabel) const
508 {
509   if (myFeatures.IsBound(theLabel))
510     return myFeatures.Find(theLabel);
511   return FeaturePtr();  // not found
512 }
513
514 ObjectPtr Model_Objects::object(TDF_Label theLabel)
515 {
516   // try feature by label
517   FeaturePtr aFeature = feature(theLabel);
518   if (aFeature.get())
519     return feature(theLabel);
520   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
521   aFeature = feature(aFeatureLabel);
522   bool isSubResult = false;
523   if (!aFeature.get() && aFeatureLabel.Depth() > 1) { // let's suppose this is sub-result of result
524     aFeatureLabel = aFeatureLabel.Father().Father();
525     aFeature = feature(aFeatureLabel);
526     isSubResult = true;
527   }
528   if (aFeature.get()) {
529     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
530     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
531     for (; aRIter != aResults.cend(); aRIter++) {
532       if (isSubResult) {
533         ResultCompSolidPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
534         if (aCompRes.get()) {
535           int aNumSubs = aCompRes->numberOfSubs();
536           for(int a = 0; a < aNumSubs; a++) {
537             ResultPtr aSub = aCompRes->subResult(a);
538             if (aSub.get()) {
539               std::shared_ptr<Model_Data> aSubData = std::dynamic_pointer_cast<Model_Data>(
540                   aSub->data());
541               if (aSubData->label().Father().IsEqual(theLabel))
542                 return aSub;
543             }
544           }
545         }
546       } else {
547         std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
548             (*aRIter)->data());
549         if (aResData->label().Father().IsEqual(theLabel))
550           return *aRIter;
551       }
552     }
553   }
554   return FeaturePtr();  // not found
555 }
556
557 ObjectPtr Model_Objects::object(const std::string& theGroupID,
558                                 const int theIndex,
559                                 const bool theAllowFolder)
560 {
561   if (theIndex == -1)
562     return ObjectPtr();
563   createHistory(theGroupID);
564   const std::string& aGroupID = groupNameFoldering(theGroupID, theAllowFolder);
565   return myHistory[aGroupID][theIndex];
566 }
567
568 std::shared_ptr<ModelAPI_Object> Model_Objects::objectByName(
569     const std::string& theGroupID, const std::string& theName)
570 {
571   createHistory(theGroupID);
572   if (theGroupID == ModelAPI_Feature::group()) { // searching among features (in history or not)
573     std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
574     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator anObjIter = allObjs.begin();
575     for(; anObjIter != allObjs.end(); anObjIter++) {
576       if ((*anObjIter)->data()->name() == theName)
577         return *anObjIter;
578     }
579   } else { // searching among results (concealed or not)
580     std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
581     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator anObjIter = allObjs.begin();
582     for(; anObjIter != allObjs.end(); anObjIter++) {
583       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = (*anObjIter)->results();
584       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
585       for (; aRIter != aResults.cend(); aRIter++) {
586         if (aRIter->get() && (*aRIter)->groupName() == theGroupID) {
587           if ((*aRIter)->data()->name() == theName)
588             return *aRIter;
589           ResultCompSolidPtr aCompRes =
590             std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
591           if (aCompRes.get()) {
592             int aNumSubs = aCompRes->numberOfSubs();
593             for(int a = 0; a < aNumSubs; a++) {
594               ResultPtr aSub = aCompRes->subResult(a);
595               if (aSub.get() && aSub->groupName() == theGroupID) {
596                 if (aSub->data()->name() == theName)
597                   return aSub;
598               }
599             }
600           }
601         }
602       }
603     }
604   }
605   // not found
606   return ObjectPtr();
607 }
608
609 const int Model_Objects::index(std::shared_ptr<ModelAPI_Object> theObject)
610 {
611   std::string aGroup = theObject->groupName();
612   createHistory(aGroup);
613   std::vector<ObjectPtr>& allObjs = myHistory[aGroup];
614   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin(); // iterate to search object
615   for(int anIndex = 0; anObjIter != allObjs.end(); anObjIter++, anIndex++) {
616     if ((*anObjIter) == theObject)
617       return anIndex;
618   }
619   // not found
620   return -1;
621 }
622
623 int Model_Objects::size(const std::string& theGroupID, const bool theAllowFolder)
624 {
625   createHistory(theGroupID);
626   const std::string& aGroupID = groupNameFoldering(theGroupID, theAllowFolder);
627   return int(myHistory[aGroupID].size());
628 }
629
630 void Model_Objects::allResults(const std::string& theGroupID, std::list<ResultPtr>& theResults)
631 {
632   // iterate the array of references and get feature by feature from the array
633   Handle(TDataStd_ReferenceArray) aRefs;
634   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
635     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
636       FeaturePtr aFeature = feature(aRefs->Value(a));
637       if (aFeature.get()) {
638         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
639         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
640         for (; aRIter != aResults.cend(); aRIter++) {
641           ResultPtr aRes = *aRIter;
642           if (aRes->groupName() != theGroupID) break; // feature have only same group results
643           // iterate also concealed: ALL RESULTS (for translation parts undo/redo management)
644           //if (aRes->isInHistory() && !aRes->isConcealed()) {
645             theResults.push_back(*aRIter);
646           //}
647         }
648       }
649     }
650   }
651 }
652
653
654 TDF_Label Model_Objects::featuresLabel() const
655 {
656   return myMain.FindChild(TAG_OBJECTS);
657 }
658
659 static std::string composeName(const std::string& theFeatureKind, const int theIndex)
660 {
661   std::stringstream aNameStream;
662   aNameStream << theFeatureKind << "_" << theIndex;
663   return aNameStream.str();
664 }
665
666 void Model_Objects::setUniqueName(FeaturePtr theFeature)
667 {
668   if (!theFeature->data()->name().empty())
669     return;  // not needed, name is already defined
670   std::string aName;  // result
671   // first count all features of such kind to start with index = count + 1
672   int aNumObjects = -1; // this feature is already in this map
673   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
674   for (; aFIter.More(); aFIter.Next()) {
675     if (aFIter.Value()->getKind() == theFeature->getKind())
676       aNumObjects++;
677   }
678   // generate candidate name
679   aName = composeName(theFeature->getKind(), aNumObjects + 1);
680   // check this is unique, if not, increase index by 1
681   for (aFIter.Initialize(myFeatures); aFIter.More();) {
682     FeaturePtr aFeature = aFIter.Value();
683     bool isSameName = aFeature->data()->name() == aName;
684     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
685       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
686       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
687       for (; aRIter != aResults.cend(); aRIter++) {
688         isSameName = (*aRIter)->data()->name() == aName;
689       }
690     }
691
692     if (isSameName) {
693       aNumObjects++;
694       aName = composeName(theFeature->getKind(), aNumObjects + 1);
695       // reinitialize iterator to make sure a new name is unique
696       aFIter.Initialize(myFeatures);
697     } else
698       aFIter.Next();
699   }
700   theFeature->data()->setName(aName);
701 }
702
703 void Model_Objects::setUniqueName(FolderPtr theFolder)
704 {
705   if (!theFolder->name().empty())
706     return; // name is already defined
707
708   int aNbFolders = myFolders.Size();
709   std::string aName = composeName(ModelAPI_Folder::ID(), aNbFolders);
710
711   // check the uniqueness of the name
712   NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator anIt(myFolders);
713   while (anIt.More()) {
714     if (anIt.Value()->data()->name() == aName) {
715       aName = composeName(ModelAPI_Folder::ID(), aNbFolders);
716       // reinitialize iterator to make sure a new name is unique
717       anIt.Initialize(myFolders);
718     } else
719       anIt.Next();
720   }
721
722   theFolder->data()->setName(aName);
723 }
724
725 void Model_Objects::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
726 {
727   std::shared_ptr<Model_Data> aData(new Model_Data);
728   aData->setLabel(theLab.FindChild(theTag));
729   aData->setObject(theObj);
730   theObj->setDoc(myDoc);
731   theObj->setData(aData);
732   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
733   if (aFeature.get()) {
734     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
735   } else { // is it a folder?
736     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theObj);
737     if (aFolder)
738       setUniqueName(aFolder);
739   }
740   theObj->initAttributes();
741 }
742
743 std::shared_ptr<ModelAPI_Feature> Model_Objects::featureById(const int theId)
744 {
745   if (theId > 0) {
746     TDF_Label aLab = featuresLabel().FindChild(theId, Standard_False);
747     return feature(aLab);
748   }
749   return std::shared_ptr<ModelAPI_Feature>(); // not found
750 }
751
752 void Model_Objects::synchronizeFeatures(
753   const TDF_LabelList& theUpdated, const bool theUpdateReferences,
754   const bool theExecuteFeatures, const bool theOpen, const bool theFlush)
755 {
756   Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
757   if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
758     return;
759   // after all updates, sends a message that groups of features were created or updated
760   Events_Loop* aLoop = Events_Loop::loop();
761   static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
762   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
763   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
764   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
765   static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
766   static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
767   bool isActive = aLoop->activateFlushes(false);
768
769   // collect all updated labels map
770   TDF_LabelMap anUpdatedMap;
771   TDF_ListIteratorOfLabelList anUpdatedIter(theUpdated);
772   for(; anUpdatedIter.More(); anUpdatedIter.Next()) {
773     TDF_Label& aFeatureLab = anUpdatedIter.Value();
774     while(aFeatureLab.Depth() > 3)
775       aFeatureLab = aFeatureLab.Father();
776     if (myFeatures.IsBound(aFeatureLab))
777       anUpdatedMap.Add(aFeatureLab);
778   }
779
780   // update all objects by checking are they on labels or not
781   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
782   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
783   for (; aLabIter.More(); aLabIter.Next()) {
784     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
785     FeaturePtr aFeature;
786     if (!myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
787       // create a feature
788       aFeature = std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get())->createFeature(
789         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
790         .ToCString(), anOwner);
791       if (!aFeature.get()) {
792         // somethig is wrong, most probably, the opened document has invalid structure
793         Events_InfoMessage("Model_Objects", "Invalid type of object in the document").send();
794         aLabIter.Value()->Label().ForgetAllAttributes();
795         continue;
796       }
797       aFeature->init();
798       // this must be before "setData" to redo the sketch line correctly
799       myFeatures.Bind(aFeatureLabel, aFeature);
800       aNewFeatures.insert(aFeature);
801       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
802       updateHistory(aFeature);
803
804       // event: model is updated
805       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
806     } else {  // nothing is changed, both iterators are incremented
807       aFeature = myFeatures.Find(aFeatureLabel);
808       aKeptFeatures.insert(aFeature);
809       if (anUpdatedMap.Contains(aFeatureLabel)) {
810         if (!theOpen) { // on abort/undo/redo reinitialize attributes if something is changed
811           std::list<std::shared_ptr<ModelAPI_Attribute> > anAttrs =
812             aFeature->data()->attributes("");
813           std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttr = anAttrs.begin();
814           for(; anAttr != anAttrs.end(); anAttr++)
815             (*anAttr)->reinit();
816         }
817         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anUpdateEvent);
818         if (aFeature->getKind() == "Parameter") {
819           // if parameters are changed, update the results (issue 937)
820           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
821           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
822           for (; aRIter != aResults.cend(); aRIter++) {
823             std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
824             if (aRes->data()->isValid() && !aRes->isDisabled()) {
825               ModelAPI_EventCreator::get()->sendUpdated(aRes, anUpdateEvent);
826             }
827           }
828         }
829       }
830     }
831   }
832
833   // check all features are checked: if not => it was removed
834   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
835   while (aFIter.More()) {
836     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
837       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
838         FeaturePtr aFeature = aFIter.Value();
839         // event: model is updated
840         //if (aFeature->isInHistory()) {
841         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
842         //}
843         // results of this feature must be redisplayed (hided)
844         // redisplay also removed feature (used for sketch and AISObject)
845         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
846         updateHistory(aFeature);
847         aFeature->erase();
848
849         // unbind after the "erase" call: on abort sketch
850         // is removes sub-objects that corrupts aFIter
851         myFeatures.UnBind(aFIter.Key());
852         // reinitialize iterator because unbind may corrupt the previous order in the map
853         aFIter.Initialize(myFeatures);
854     } else
855       aFIter.Next();
856   }
857
858   if (theUpdateReferences) {
859     synchronizeBackRefs();
860   }
861   // update results of the features (after features created because
862   // they may be connected, like sketch and sub elements)
863   // After synchronisation of back references because sketch
864   // must be set in sub-elements before "execute" by updateResults
865   std::set<FeaturePtr> aProcessed; // composites must be updated after their subs (issue 360)
866   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
867   for (; aLabIter2.More(); aLabIter2.Next()) {
868     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
869     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
870       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
871       updateResults(aFeature, aProcessed);
872     }
873   }
874   // the synchronize should be done after updateResults
875   // in order to correct back references of updated results
876   if (theUpdateReferences) {
877     synchronizeBackRefs();
878   }
879   if (!theUpdated.IsEmpty()) {
880     // this means there is no control what was modified => remove history cash
881     myHistory.clear();
882   }
883
884   if (theExecuteFeatures)
885     anOwner->executeFeatures() = false;
886   aLoop->activateFlushes(isActive);
887
888   if (theFlush) {
889     aLoop->flush(aDeleteEvent);
890     // delete should be emitted before create to reacts to aborted feature
891     aLoop->flush(aCreateEvent);
892     aLoop->flush(anUpdateEvent);
893     aLoop->flush(aCreateEvent); // after update of features, there could be results created
894     aLoop->flush(aDeleteEvent); // or deleted
895     aLoop->flush(aRedispEvent);
896     aLoop->flush(aToHideEvent);
897   }
898   if (theExecuteFeatures)
899     anOwner->executeFeatures() = true;
900 }
901
902 /// synchronises back references for the given object basing on the collected data
903 void Model_Objects::synchronizeBackRefsForObject(const std::set<AttributePtr>& theNewRefs,
904   ObjectPtr theObject)
905 {
906   if (!theObject.get() || !theObject->data()->isValid())
907     return; // invalid
908   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theObject->data());
909   // iterate new list to compare with curent
910   std::set<AttributePtr>::iterator aNewIter = theNewRefs.begin();
911   for(; aNewIter != theNewRefs.end(); aNewIter++) {
912     if (aData->refsToMe().find(*aNewIter) == aData->refsToMe().end()) {
913       FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aNewIter)->owner());
914       aData->addBackReference(aRefFeat, (*aNewIter)->id());
915     }
916   }
917   if (theNewRefs.size() != aData->refsToMe().size()) { // some back ref must be removed
918     std::set<AttributePtr>::iterator aCurrentIter = aData->refsToMe().begin();
919     while(aCurrentIter != aData->refsToMe().end()) {
920       if (theNewRefs.find(*aCurrentIter) == theNewRefs.end()) {
921         // for external references from other documents this system
922         // is not working: refs are collected from
923         // different Model_Objects, so before remove check this
924         // external object exists and still referenced
925         bool aLeaveIt = false;
926         if ((*aCurrentIter)->owner().get() && (*aCurrentIter)->owner()->document() != myDoc &&
927             (*aCurrentIter)->owner()->data().get() && (*aCurrentIter)->owner()->data()->isValid()) {
928           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
929           (*aCurrentIter)->owner()->data()->referencesToObjects(aRefs);
930           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> >>>::iterator
931             aRefIter = aRefs.begin();
932           for(; aRefIter != aRefs.end(); aRefIter++) {
933             if ((*aCurrentIter)->id() == aRefIter->first) {
934               std::list<std::shared_ptr<ModelAPI_Object> >::iterator anOIt;
935               for(anOIt = aRefIter->second.begin(); anOIt != aRefIter->second.end(); anOIt++) {
936                 if (*anOIt == theObject) {
937                   aLeaveIt = true;
938                 }
939               }
940             }
941           }
942         }
943         if (!aLeaveIt) {
944           aData->removeBackReference(*aCurrentIter);
945           aCurrentIter = aData->refsToMe().begin(); // reinitialize iteration after delete
946         } else aCurrentIter++;
947       } else aCurrentIter++;
948     }
949   }
950   aData->updateConcealmentFlag();
951 }
952
953 void Model_Objects::synchronizeBackRefs()
954 {
955   // collect all back references in the separated container: to update everything at once,
956   // without additional Concealment switchin on and off: only the final modification
957
958   // referenced (slave) objects to referencing attirbutes
959   std::map<ObjectPtr, std::set<AttributePtr> > allRefs;
960   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
961   for(; aFeatures.More(); aFeatures.Next()) {
962     FeaturePtr aFeature = aFeatures.Value();
963     std::shared_ptr<Model_Data> aFData = std::dynamic_pointer_cast<Model_Data>(aFeature->data());
964     if (aFData.get()) {
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 aRefsIt = aRefs.begin();
968       for(; aRefsIt != aRefs.end(); aRefsIt++) {
969         std::list<ObjectPtr>::iterator aRefTo = aRefsIt->second.begin();
970         for(; aRefTo != aRefsIt->second.end(); aRefTo++) {
971           if (*aRefTo) {
972             std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = allRefs.find(*aRefTo);
973             if (aFound == allRefs.end()) {
974               allRefs[*aRefTo] = std::set<AttributePtr>();
975               aFound = allRefs.find(*aRefTo);
976             }
977             aFound->second.insert(aFeature->data()->attribute(aRefsIt->first));
978           }
979         }
980       }
981     }
982   }
983   // second iteration: just compare back-references with existing in features and results
984   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
985     FeaturePtr aFeature = aFeatures.Value();
986     static std::set<AttributePtr> anEmpty;
987     std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = allRefs.find(aFeature);
988     if (aFound == allRefs.end()) { // not found => erase all back references
989       synchronizeBackRefsForObject(anEmpty, aFeature);
990     } else {
991       synchronizeBackRefsForObject(aFound->second, aFeature);
992       allRefs.erase(aFound); // to check that all refs are counted
993     }
994     // also for results
995     std::list<ResultPtr> aResults;
996     ModelAPI_Tools::allResults(aFeature, aResults);
997     std::list<ResultPtr>::iterator aRIter = aResults.begin();
998     for(; aRIter != aResults.cend(); aRIter++) {
999       aFound = allRefs.find(*aRIter);
1000       if (aFound == allRefs.end()) { // not found => erase all back references
1001         synchronizeBackRefsForObject(anEmpty, *aRIter);
1002       } else {
1003         synchronizeBackRefsForObject(aFound->second, *aRIter);
1004         allRefs.erase(aFound); // to check that all refs are counted
1005       }
1006     }
1007   }
1008   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1009     FeaturePtr aFeature = aFeatures.Value();
1010     std::list<ResultPtr> aResults;
1011     ModelAPI_Tools::allResults(aFeature, aResults);
1012     // update the concealment status for disply in isConcealed of ResultBody
1013     std::list<ResultPtr>::iterator aRIter = aResults.begin();
1014     for(; aRIter != aResults.cend(); aRIter++) {
1015       (*aRIter)->isConcealed();
1016     }
1017   }
1018   // the rest all refs means that feature references to the external document feature:
1019   // process also them
1020   std::map<ObjectPtr, std::set<AttributePtr> >::iterator anExtIter = allRefs.begin();
1021   for(; anExtIter != allRefs.end(); anExtIter++) {
1022     synchronizeBackRefsForObject(anExtIter->second, anExtIter->first);
1023   }
1024 }
1025
1026 TDF_Label Model_Objects::resultLabel(
1027   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
1028 {
1029   const std::shared_ptr<Model_Data>& aData =
1030     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
1031   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
1032 }
1033
1034 bool Model_Objects::hasCustomName(DataPtr theFeatureData,
1035                                   ResultPtr theResult,
1036                                   int theResultIndex,
1037                                   std::string& theParentName) const
1038 {
1039   ResultCompSolidPtr aCompSolidRes =
1040       std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theFeatureData->owner());
1041   if (aCompSolidRes) {
1042     FeaturePtr anOwner = ModelAPI_Feature::feature(theResult->data()->owner());
1043
1044     // names of sub-solids in CompSolid should be default (for example,
1045     // result of boolean operation 'Boolean_1' is a CompSolid which is renamed to 'MyBOOL',
1046     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1', 'Boolean_1_2' etc.)
1047     std::ostringstream aDefaultName;
1048     aDefaultName << anOwner->name();
1049     // compute default name of CompSolid (name of feature + index of CompSolid's result)
1050     int aCompSolidResultIndex = 0;
1051     const std::list<ResultPtr>& aResults = anOwner->results();
1052     for (std::list<ResultPtr>::const_iterator anIt = aResults.begin();
1053          anIt != aResults.end(); ++anIt, ++aCompSolidResultIndex)
1054       if (aCompSolidRes == *anIt)
1055         break;
1056     aDefaultName << "_" << (aCompSolidResultIndex + 1);
1057     theParentName = aDefaultName.str();
1058     return false;
1059   }
1060
1061   theParentName = ModelAPI_Tools::getDefaultName(theResult, theResultIndex);
1062   return true;
1063 }
1064
1065 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
1066                                 std::shared_ptr<ModelAPI_Result> theResult,
1067                                 const int theResultIndex)
1068 {
1069   theResult->init();
1070   theResult->setDoc(myDoc);
1071   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
1072   if (theResult->data()->name().empty()) {
1073     // if was not initialized, generate event and set a name
1074     std::string aNewName = theFeatureData->name();
1075     if (!hasCustomName(theFeatureData, theResult, theResultIndex, aNewName)) {
1076       std::stringstream aName;
1077       aName << aNewName;
1078       // if there are several results (issue #899: any number of result),
1079       // add unique prefix starting from second
1080       if (theResultIndex > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
1081         aName << "_" << theResultIndex + 1;
1082       aNewName = aName.str();
1083     }
1084     theResult->data()->setName(aNewName);
1085   }
1086 }
1087
1088 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
1089     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1090 {
1091   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1092   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
1093   ObjectPtr anOldObject = object(aLab);
1094   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
1095   if (anOldObject.get()) {
1096     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
1097   }
1098   if (!aResult.get()) {
1099     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1100     storeResult(theFeatureData, aResult, theIndex);
1101   }
1102   return aResult;
1103 }
1104
1105 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
1106     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1107 {
1108   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1109   // for feature create compsolid, but for result sub create body:
1110   // only one level of recursion is supported now
1111   ResultPtr aResultOwner = std::dynamic_pointer_cast<ModelAPI_Result>(theFeatureData->owner());
1112   ObjectPtr anOldObject;
1113   if (aResultOwner.get()) {
1114     TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1115   } else { // in compsolid (higher level result) old object probably may be found
1116     TDataStd_Comment::Set(aLab, ModelAPI_ResultCompSolid::group().c_str());
1117     anOldObject = object(aLab);
1118   }
1119   std::shared_ptr<ModelAPI_ResultBody> aResult;
1120   if (anOldObject.get()) {
1121     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1122   }
1123   if (!aResult.get()) {
1124     // create compsolid anyway; if it is compsolid, it will create sub-bodies internally
1125     if (aResultOwner.get()) {
1126       aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1127     } else {
1128       aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultCompSolid);
1129     }
1130     storeResult(theFeatureData, aResult, theIndex);
1131   }
1132   return aResult;
1133 }
1134
1135 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
1136     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1137 {
1138   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1139   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1140   ObjectPtr anOldObject = object(aLab);
1141   std::shared_ptr<ModelAPI_ResultPart> aResult;
1142   if (anOldObject.get()) {
1143     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1144   }
1145   if (!aResult.get()) {
1146     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1147     storeResult(theFeatureData, aResult, theIndex);
1148   }
1149   return aResult;
1150 }
1151
1152 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
1153     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1154     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1155 {
1156   std::shared_ptr<ModelAPI_ResultPart> aResult = createPart(theFeatureData, theIndex);
1157   aResult->data()->reference(Model_ResultPart::BASE_REF_ID())->setValue(theOrigin);
1158   return aResult;
1159 }
1160
1161 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
1162     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1163 {
1164   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1165   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1166   ObjectPtr anOldObject = object(aLab);
1167   std::shared_ptr<ModelAPI_ResultGroup> aResult;
1168   if (anOldObject.get()) {
1169     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1170   }
1171   if (!aResult.get()) {
1172     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1173     storeResult(theFeatureData, aResult, theIndex);
1174   }
1175   return aResult;
1176 }
1177
1178 std::shared_ptr<ModelAPI_ResultField> Model_Objects::createField(
1179     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1180 {
1181   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1182   TDataStd_Comment::Set(aLab, ModelAPI_ResultField::group().c_str());
1183   ObjectPtr anOldObject = object(aLab);
1184   std::shared_ptr<ModelAPI_ResultField> aResult;
1185   if (anOldObject.get()) {
1186     aResult = std::dynamic_pointer_cast<ModelAPI_ResultField>(anOldObject);
1187   }
1188   if (!aResult.get()) {
1189     aResult = std::shared_ptr<ModelAPI_ResultField>(new Model_ResultField(theFeatureData));
1190     storeResult(theFeatureData, aResult, theIndex);
1191   }
1192   return aResult;
1193 }
1194
1195 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
1196       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1197 {
1198   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1199   TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
1200   ObjectPtr anOldObject = object(aLab);
1201   std::shared_ptr<ModelAPI_ResultParameter> aResult;
1202   if (anOldObject.get()) {
1203     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
1204   }
1205   if (!aResult.get()) {
1206     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
1207     storeResult(theFeatureData, aResult, theIndex);
1208   }
1209   return aResult;
1210 }
1211
1212 std::shared_ptr<ModelAPI_Folder> Model_Objects::createFolder(
1213     const std::shared_ptr<ModelAPI_Feature>& theBeforeThis)
1214 {
1215   FolderPtr aFolder(new ModelAPI_Folder);
1216   if (!aFolder)
1217     return aFolder;
1218
1219   TDF_Label aFeaturesLab = featuresLabel();
1220   TDF_Label aFolderLab = aFeaturesLab.NewChild();
1221   // store feature in the features array: before "initData" because in macro features
1222   // in initData it creates new features, appeared later than this
1223   TDF_Label aPrevFeatureLab;
1224   if (theBeforeThis.get()) { // searching for the previous feature label
1225     std::shared_ptr<Model_Data> aPrevData =
1226         std::dynamic_pointer_cast<Model_Data>(theBeforeThis->data());
1227     if (aPrevData.get()) {
1228       aPrevFeatureLab = nextLabel(aPrevData->label().Father(), true);
1229     }
1230   } else { // find the label of the last feature
1231     Handle(TDataStd_ReferenceArray) aRefs;
1232     if (aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1233       aPrevFeatureLab = aRefs->Value(aRefs->Upper());
1234   }
1235   AddToRefArray(aFeaturesLab, aFolderLab, aPrevFeatureLab);
1236
1237   // keep the feature ID to restore document later correctly
1238   TDataStd_Comment::Set(aFolderLab, ModelAPI_Folder::ID().c_str());
1239   myFolders.Bind(aFolderLab, aFolder);
1240   // must be before the event sending: for OB the feature is already added
1241   updateHistory(ModelAPI_Folder::group());
1242   updateHistory(ModelAPI_Feature::group());
1243
1244   // must be after binding to the map because of "Box" macro feature that
1245   // creates other features in "initData"
1246   initData(aFolder, aFolderLab, TAG_FEATURE_ARGUMENTS);
1247   // event: folder is added, must be before "initData" to update OB correctly on Duplicate:
1248   // first new part, then the content
1249   static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
1250   ModelAPI_EventCreator::get()->sendUpdated(aFolder, anEvent);
1251
1252   return aFolder;
1253 }
1254
1255 void Model_Objects::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1256 {
1257   /// \todo
1258 }
1259
1260 static FeaturePtr limitingFeature(std::list<FeaturePtr>& theFeatures, const bool isLast)
1261 {
1262   FeaturePtr aFeature;
1263   if (isLast) {
1264     aFeature = theFeatures.back();
1265     theFeatures.pop_back();
1266   } else {
1267     aFeature = theFeatures.front();
1268     theFeatures.pop_front();
1269   }
1270   return aFeature;
1271 }
1272
1273 std::shared_ptr<ModelAPI_Folder> Model_Objects::findFolder(
1274       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1275       const bool theBelow)
1276 {
1277   if (theFeatures.empty())
1278     return FolderPtr(); // nothing to move
1279
1280   TDF_Label aFeaturesLab = featuresLabel();
1281   Handle(TDataStd_ReferenceArray) aRefs;
1282   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1283     return FolderPtr(); // no reference array (something is wrong)
1284
1285   std::list<std::shared_ptr<ModelAPI_Feature> > aFeatures = theFeatures;
1286   std::shared_ptr<ModelAPI_Feature> aLimitingFeature = limitingFeature(aFeatures, theBelow);
1287
1288   std::shared_ptr<Model_Data> aData =
1289       std::static_pointer_cast<Model_Data>(aLimitingFeature->data());
1290   if (!aData || !aData->isValid())
1291     return FolderPtr(); // invalid feature
1292
1293   // label of the first feature in the list for fast searching
1294   TDF_Label aFirstFeatureLabel = aData->label().Father();
1295
1296   // find a folder above the features and
1297   // check the given features represent a sequential list of objects following the folder
1298   FolderPtr aFoundFolder;
1299   TDF_Label aLastFeatureInFolder;
1300   int aRefIndex = aRefs->Lower();
1301   for(; aRefIndex <= aRefs->Upper(); ++aRefIndex) { // iterate all existing features
1302     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1303     if (IsEqual(aCurLabel, aFirstFeatureLabel))
1304       break; // no need to continue searching
1305
1306     // searching the folder below, just continue to search last feature from the list
1307     if (theBelow)
1308       continue;
1309
1310     if (!aLastFeatureInFolder.IsNull()) {
1311       if (IsEqual(aCurLabel, aLastFeatureInFolder))
1312         aLastFeatureInFolder.Nullify(); // the last feature in the folder is achived
1313       continue;
1314     }
1315
1316     aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(folder(aCurLabel));
1317     if (aFoundFolder) {
1318       AttributeReferencePtr aLastFeatAttr =
1319           aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1320       if (aLastFeatAttr && aLastFeatAttr->isInitialized()) {
1321         // setup iterating inside a folder to find last feature
1322         ObjectPtr aLastFeature = aLastFeatAttr->value();
1323         if (aLastFeature) {
1324           aData = std::static_pointer_cast<Model_Data>(aLastFeature->data());
1325           if (aData && aData->isValid())
1326             aLastFeatureInFolder = aData->label().Father();
1327         }
1328       }
1329     }
1330   }
1331
1332   if (theBelow && aRefIndex < aRefs->Upper()) {
1333     // check the next object is a folder
1334     TDF_Label aLabel = aRefs->Value(aRefIndex + 1);
1335     aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(folder(aLabel));
1336   }
1337
1338   if (!aLastFeatureInFolder.IsNull() || // the last feature of the folder above is not found
1339       !aFoundFolder)
1340     return FolderPtr();
1341
1342   // check the given features are sequential list
1343   int aStep = theBelow ? -1 : 1;
1344   for (aRefIndex += aStep;
1345        !aFeatures.empty() && aRefIndex >= aRefs->Lower() && aRefIndex <= aRefs->Upper();
1346        aRefIndex += aStep) {
1347     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1348     TDF_Label aFeatureLabel;
1349
1350     aLimitingFeature = limitingFeature(aFeatures, theBelow);
1351     aData = std::static_pointer_cast<Model_Data>(aLimitingFeature->data());
1352     if (aData && aData->isValid())
1353       aFeatureLabel = aData->label().Father();
1354
1355     if (!IsEqual(aCurLabel, aFeatureLabel))
1356       return FolderPtr(); // not a sequential list
1357   }
1358
1359   return aFoundFolder;
1360 }
1361
1362 bool Model_Objects::moveToFolder(
1363       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1364       const std::shared_ptr<ModelAPI_Folder>& theFolder)
1365 {
1366   if (theFeatures.empty() || !theFolder)
1367     return false;
1368
1369   // labels for the folder and last feature in the list
1370   TDF_Label aFolderLabel, aLastFeatureLabel;
1371   std::shared_ptr<Model_Data> aData =
1372       std::static_pointer_cast<Model_Data>(theFolder->data());
1373   if (aData && aData->isValid())
1374     aFolderLabel = aData->label().Father();
1375   aData = std::static_pointer_cast<Model_Data>(theFeatures.back()->data());
1376   if (aData && aData->isValid())
1377     aLastFeatureLabel = aData->label().Father();
1378
1379   if (aFolderLabel.IsNull() || aLastFeatureLabel.IsNull())
1380     return false;
1381
1382   // check the folder is below the list of features
1383   bool isFolderBelow = false;
1384   TDF_Label aFeaturesLab = featuresLabel();
1385   Handle(TDataStd_ReferenceArray) aRefs;
1386   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1387     return false; // no reference array (something is wrong)
1388   for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1389     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1390     if (aCurLabel == aFolderLabel)
1391       break; // folder is above the features
1392     else if (aCurLabel == aLastFeatureLabel) {
1393       isFolderBelow = true;
1394       break;
1395     }
1396   }
1397
1398   if (isFolderBelow) {
1399     aData = std::static_pointer_cast<Model_Data>(theFeatures.front()->data());
1400     if (!aData || !aData->isValid())
1401       return false;
1402     TDF_Label aPrevFeatureLabel = aData->label().Father();
1403     // label of the feature before the first feature in the list
1404     for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex)
1405       if (aPrevFeatureLabel == aRefs->Value(aRefIndex)) {
1406         if (aRefIndex == aRefs->Lower())
1407           aPrevFeatureLabel.Nullify();
1408         else
1409           aPrevFeatureLabel = aRefs->Value(aRefIndex - 1);
1410         break;
1411       }
1412
1413     // move the folder in the list of references before the first feature
1414     RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1415     AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1416   } else {
1417     // update last feature of the folder
1418     AttributeReferencePtr aLastFeatAttr =
1419         theFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1420     aLastFeatAttr->setValue(theFeatures.back());
1421   }
1422
1423   updateHistory(ModelAPI_Feature::group());
1424   return true;
1425 }
1426
1427 bool Model_Objects::removeFromFolder(
1428       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1429 {
1430   /// \todo
1431   return false;
1432 }
1433
1434
1435 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
1436     const std::shared_ptr<ModelAPI_Result>& theResult)
1437 {
1438   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1439   if (aData.get()) {
1440     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1441     FeaturePtr aFeature = feature(aFeatureLab);
1442     if (!aFeature.get() && aFeatureLab.Depth() > 1) { // this may be sub-result of result
1443       aFeatureLab = aFeatureLab.Father().Father();
1444       aFeature = feature(aFeatureLab);
1445     }
1446     return aFeature;
1447   }
1448   return FeaturePtr();
1449 }
1450
1451 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
1452 {
1453   if (theFeature->data()->isValid()) {
1454     TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1455     if (aLabIter.More()) {
1456       TDF_Label anArgLab = aLabIter.Value();
1457       Handle(TDataStd_Comment) aGroup;
1458       if (aLabIter.Value().FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1459         return TCollection_AsciiString(aGroup->Get()).ToCString();
1460       }
1461     }
1462   }
1463   static std::string anEmpty;
1464   return anEmpty; // not found
1465 }
1466
1467 void Model_Objects::updateResults(FeaturePtr theFeature, std::set<FeaturePtr>& theProcessed)
1468 {
1469   if (theProcessed.find(theFeature) != theProcessed.end())
1470     return;
1471   theProcessed.insert(theFeature);
1472   // for composites update subs recursively (sketch elements results are needed for the sketch)
1473   CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
1474   if (aComp.get() && aComp->getKind() != "Part") { // don't go inside of parts sub-features
1475     // update subs of composites first
1476     int aSubNum = aComp->numberOfSubs();
1477     for(int a = 0; a < aSubNum; a++) {
1478       FeaturePtr aSub = aComp->subFeature(a);
1479       updateResults(aComp->subFeature(a), theProcessed);
1480     }
1481   }
1482
1483   // for not persistent is will be done by parametric updater automatically
1484   //if (!theFeature->isPersistentResult()) return;
1485   // check the existing results and remove them if there is nothing on the label
1486   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1487   while(aResIter != theFeature->results().cend()) {
1488     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1489     if (aBody.get()) {
1490       std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(aBody->data());
1491       if (!aData.get() || !aData->isValid() || (!aBody->isDisabled() && aData->isDeleted())) {
1492         // found a disappeared result => remove it
1493         theFeature->eraseResultFromList(aBody);
1494         // start iterate from beginning because iterator is corrupted by removing
1495         aResIter = theFeature->results().cbegin();
1496         continue;
1497       }
1498     }
1499     aResIter++;
1500   }
1501   // it may be on undo
1502   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
1503     return;
1504   // check that results are presented on all labels
1505   int aResSize = int(theFeature->results().size());
1506   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1507   for(; aLabIter.More(); aLabIter.Next()) {
1508     // here must be GUID of the feature
1509     int aResIndex = aLabIter.Value().Tag() - 1;
1510     ResultPtr aNewBody;
1511     if (aResSize <= aResIndex) {
1512       TDF_Label anArgLab = aLabIter.Value();
1513       Handle(TDataStd_Comment) aGroup;
1514       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1515         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str() ||
1516             aGroup->Get() == ModelAPI_ResultCompSolid::group().c_str()) {
1517           aNewBody = createBody(theFeature->data(), aResIndex);
1518         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1519           std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex);
1520           theFeature->setResult(aNewP, aResIndex);
1521           if (!aNewP->partDoc().get())
1522             // create the part result: it is better to restore the previous result if it is possible
1523             theFeature->execute();
1524         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1525           theFeature->execute(); // construction shapes are needed for sketch solver
1526         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1527           aNewBody = createGroup(theFeature->data(), aResIndex);
1528         } else if (aGroup->Get() == ModelAPI_ResultField::group().c_str()) {
1529           aNewBody = createField(theFeature->data(), aResIndex);
1530         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
1531           theFeature->attributeChanged("expression"); // just produce a value
1532         } else {
1533           Events_InfoMessage("Model_Objects", "Unknown type of result is found in the document:")
1534             .arg(TCollection_AsciiString(aGroup->Get()).ToCString()).send();
1535         }
1536       }
1537       if (aNewBody && !aNewBody->data()->isDeleted()) {
1538         theFeature->setResult(aNewBody, aResIndex);
1539       }
1540     }
1541   }
1542 }
1543
1544 ResultPtr Model_Objects::findByName(const std::string theName)
1545 {
1546   ResultPtr aResult;
1547   FeaturePtr aResFeature; // keep feature to return the latest one
1548   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
1549   for(; anObjIter.More(); anObjIter.Next()) {
1550     FeaturePtr& aFeature = anObjIter.ChangeValue();
1551     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
1552       continue;
1553     std::list<ResultPtr> allResults;
1554     ModelAPI_Tools::allResults(aFeature, allResults);
1555     std::list<ResultPtr>::iterator aRIter = allResults.begin();
1556     for (; aRIter != allResults.cend(); aRIter++) {
1557       ResultPtr aRes = *aRIter;
1558       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
1559           aRes->data()->name() == theName)
1560       {
1561         if (!aResult.get() || isLater(aFeature, aResFeature)) { // select the latest
1562           aResult = aRes;
1563           aResFeature = aFeature;
1564         }
1565       }
1566     }
1567   }
1568   return aResult;
1569 }
1570
1571 TDF_Label Model_Objects::nextLabel(TDF_Label theCurrent, const bool theReverse)
1572 {
1573   Handle(TDataStd_ReferenceArray) aRefs;
1574   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1575     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
1576       TDF_Label aCurLab = aRefs->Value(a);
1577       if (aCurLab.IsEqual(theCurrent)) {
1578         a += theReverse ? -1 : 1;
1579         if (a >= aRefs->Lower() && a <= aRefs->Upper())
1580           return aRefs->Value(a);
1581         break; // finish iiteration: it's last feature
1582       }
1583     }
1584   }
1585   return TDF_Label();
1586 }
1587
1588 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, const bool theReverse)
1589 {
1590   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1591   if (aData.get() && aData->isValid()) {
1592     TDF_Label aFeatureLabel = aData->label().Father();
1593     TDF_Label aNextLabel = nextLabel(aFeatureLabel, theReverse);
1594     if (!aNextLabel.IsNull())
1595       return feature(aNextLabel);
1596   }
1597   return FeaturePtr(); // not found, last, or something is wrong
1598 }
1599
1600 FeaturePtr Model_Objects::firstFeature()
1601 {
1602   Handle(TDataStd_ReferenceArray) aRefs;
1603   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1604     return feature(aRefs->Value(aRefs->Lower()));
1605   }
1606   return FeaturePtr(); // no features at all
1607 }
1608
1609 FeaturePtr Model_Objects::lastFeature()
1610 {
1611   Handle(TDataStd_ReferenceArray) aRefs;
1612   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1613     return feature(aRefs->Value(aRefs->Upper()));
1614   }
1615   return FeaturePtr(); // no features at all
1616 }
1617
1618 bool Model_Objects::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
1619 {
1620   std::shared_ptr<Model_Data> aLaterD = std::static_pointer_cast<Model_Data>(theLater->data());
1621   std::shared_ptr<Model_Data> aCurrentD = std::static_pointer_cast<Model_Data>(theCurrent->data());
1622   if (aLaterD.get() && aLaterD->isValid() && aCurrentD.get() && aCurrentD->isValid()) {
1623     TDF_Label aLaterL = aLaterD->label().Father();
1624     TDF_Label aCurrentL = aCurrentD->label().Father();
1625     int aLaterI = -1, aCurentI = -1; // not found yet state
1626     Handle(TDataStd_ReferenceArray) aRefs;
1627     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1628       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
1629         TDF_Label aCurLab = aRefs->Value(a);
1630         if (aCurLab.IsEqual(aLaterL)) {
1631           aLaterI = a;
1632         } else if (aCurLab.IsEqual(aCurrentL)) {
1633           aCurentI = a;
1634         } else continue;
1635         if (aLaterI != -1 && aCurentI != -1) // both are found
1636           return aLaterI > aCurentI;
1637       }
1638     }
1639   }
1640   return false; // not found, or something is wrong
1641 }
1642
1643 std::list<std::shared_ptr<ModelAPI_Object> > Model_Objects::allObjects()
1644 {
1645   std::list<std::shared_ptr<ModelAPI_Object> > aResult;
1646   Handle(TDataStd_ReferenceArray) aRefs;
1647   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1648     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
1649       ObjectPtr anObject = object(aRefs->Value(a));
1650       if (!anObject.get()) // is it a folder?
1651         anObject = folder(aRefs->Value(a));
1652       if (anObject.get())
1653         aResult.push_back(anObject);
1654     }
1655   }
1656   return aResult;
1657 }
1658
1659 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
1660 {
1661   std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
1662   Handle(TDataStd_ReferenceArray) aRefs;
1663   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1664     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
1665       FeaturePtr aFeature = feature(aRefs->Value(a));
1666       if (aFeature.get())
1667         aResult.push_back(aFeature);
1668     }
1669   }
1670   return aResult;
1671 }
1672
1673 int Model_Objects::numInternalFeatures()
1674 {
1675   Handle(TDataStd_ReferenceArray) aRefs;
1676   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1677     return aRefs->Upper() - aRefs->Lower() + 1;
1678   }
1679   return 0; // invalid
1680 }
1681
1682 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
1683 {
1684   Handle(TDataStd_ReferenceArray) aRefs;
1685   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1686     return feature(aRefs->Value(aRefs->Lower() + theIndex));
1687   }
1688   return FeaturePtr(); // invalid
1689 }
1690
1691 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1692 {
1693   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1694
1695 }
1696 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1697 {
1698   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1699 }