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