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