Salome HOME
Method to remove folder (Task 2.3. Ability to put consecutive Features in a folder)
[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, true, 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   return aGroupID.empty() ? myHistory[theGroupID][theIndex] : myHistory[aGroupID][theIndex];
568 }
569
570 std::shared_ptr<ModelAPI_Object> Model_Objects::objectByName(
571     const std::string& theGroupID, const std::string& theName)
572 {
573   createHistory(theGroupID);
574   if (theGroupID == ModelAPI_Feature::group()) { // searching among features (in history or not)
575     std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
576     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator anObjIter = allObjs.begin();
577     for(; anObjIter != allObjs.end(); anObjIter++) {
578       if ((*anObjIter)->data()->name() == theName)
579         return *anObjIter;
580     }
581   } else { // searching among results (concealed or not)
582     std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
583     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator anObjIter = allObjs.begin();
584     for(; anObjIter != allObjs.end(); anObjIter++) {
585       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = (*anObjIter)->results();
586       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
587       for (; aRIter != aResults.cend(); aRIter++) {
588         if (aRIter->get() && (*aRIter)->groupName() == theGroupID) {
589           if ((*aRIter)->data()->name() == theName)
590             return *aRIter;
591           ResultCompSolidPtr aCompRes =
592             std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
593           if (aCompRes.get()) {
594             int aNumSubs = aCompRes->numberOfSubs();
595             for(int a = 0; a < aNumSubs; a++) {
596               ResultPtr aSub = aCompRes->subResult(a);
597               if (aSub.get() && aSub->groupName() == theGroupID) {
598                 if (aSub->data()->name() == theName)
599                   return aSub;
600               }
601             }
602           }
603         }
604       }
605     }
606   }
607   // not found
608   return ObjectPtr();
609 }
610
611 const int Model_Objects::index(std::shared_ptr<ModelAPI_Object> theObject,
612                                const bool theAllowFolder)
613 {
614   std::string aGroup = theObject->groupName();
615   // treat folder as feature
616   if (aGroup == ModelAPI_Folder::group())
617     aGroup = ModelAPI_Feature::group();
618   createHistory(aGroup);
619
620   // get the group of features out of folder (if enabled)
621   if (theAllowFolder && !groupNameFoldering(aGroup, theAllowFolder).empty())
622     aGroup = groupNameFoldering(aGroup, theAllowFolder);
623
624   std::vector<ObjectPtr>& allObjs = myHistory[aGroup];
625   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin(); // iterate to search object
626   for(int anIndex = 0; anObjIter != allObjs.end(); anObjIter++, anIndex++) {
627     if ((*anObjIter) == theObject)
628       return anIndex;
629   }
630   // not found
631   return -1;
632 }
633
634 int Model_Objects::size(const std::string& theGroupID, const bool theAllowFolder)
635 {
636   createHistory(theGroupID);
637   const std::string& aGroupID = groupNameFoldering(theGroupID, theAllowFolder);
638   return aGroupID.empty() ? int(myHistory[theGroupID].size()) : int(myHistory[aGroupID].size());
639 }
640
641 void Model_Objects::allResults(const std::string& theGroupID, std::list<ResultPtr>& theResults)
642 {
643   // iterate the array of references and get feature by feature from the array
644   Handle(TDataStd_ReferenceArray) aRefs;
645   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
646     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
647       FeaturePtr aFeature = feature(aRefs->Value(a));
648       if (aFeature.get()) {
649         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
650         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
651         for (; aRIter != aResults.cend(); aRIter++) {
652           ResultPtr aRes = *aRIter;
653           if (aRes->groupName() != theGroupID) break; // feature have only same group results
654           // iterate also concealed: ALL RESULTS (for translation parts undo/redo management)
655           //if (aRes->isInHistory() && !aRes->isConcealed()) {
656             theResults.push_back(*aRIter);
657           //}
658         }
659       }
660     }
661   }
662 }
663
664
665 TDF_Label Model_Objects::featuresLabel() const
666 {
667   return myMain.FindChild(TAG_OBJECTS);
668 }
669
670 static std::string composeName(const std::string& theFeatureKind, const int theIndex)
671 {
672   std::stringstream aNameStream;
673   aNameStream << theFeatureKind << "_" << theIndex;
674   return aNameStream.str();
675 }
676
677 void Model_Objects::setUniqueName(FeaturePtr theFeature)
678 {
679   if (!theFeature->data()->name().empty())
680     return;  // not needed, name is already defined
681   std::string aName;  // result
682   // first count all features of such kind to start with index = count + 1
683   int aNumObjects = -1; // this feature is already in this map
684   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
685   for (; aFIter.More(); aFIter.Next()) {
686     if (aFIter.Value()->getKind() == theFeature->getKind())
687       aNumObjects++;
688   }
689   // generate candidate name
690   aName = composeName(theFeature->getKind(), aNumObjects + 1);
691   // check this is unique, if not, increase index by 1
692   for (aFIter.Initialize(myFeatures); aFIter.More();) {
693     FeaturePtr aFeature = aFIter.Value();
694     bool isSameName = aFeature->data()->name() == aName;
695     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
696       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
697       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
698       for (; aRIter != aResults.cend(); aRIter++) {
699         isSameName = (*aRIter)->data()->name() == aName;
700       }
701     }
702
703     if (isSameName) {
704       aNumObjects++;
705       aName = composeName(theFeature->getKind(), aNumObjects + 1);
706       // reinitialize iterator to make sure a new name is unique
707       aFIter.Initialize(myFeatures);
708     } else
709       aFIter.Next();
710   }
711   theFeature->data()->setName(aName);
712 }
713
714 void Model_Objects::setUniqueName(FolderPtr theFolder)
715 {
716   if (!theFolder->name().empty())
717     return; // name is already defined
718
719   int aNbFolders = myFolders.Size();
720   std::string aName = composeName(ModelAPI_Folder::ID(), aNbFolders);
721
722   // check the uniqueness of the name
723   NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator anIt(myFolders);
724   while (anIt.More()) {
725     if (anIt.Value()->data()->name() == aName) {
726       aName = composeName(ModelAPI_Folder::ID(), aNbFolders);
727       // reinitialize iterator to make sure a new name is unique
728       anIt.Initialize(myFolders);
729     } else
730       anIt.Next();
731   }
732
733   theFolder->data()->setName(aName);
734 }
735
736 void Model_Objects::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
737 {
738   std::shared_ptr<Model_Data> aData(new Model_Data);
739   aData->setLabel(theLab.FindChild(theTag));
740   aData->setObject(theObj);
741   theObj->setDoc(myDoc);
742   theObj->setData(aData);
743   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
744   if (aFeature.get()) {
745     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
746   } else { // is it a folder?
747     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theObj);
748     if (aFolder)
749       setUniqueName(aFolder);
750   }
751   theObj->initAttributes();
752 }
753
754 std::shared_ptr<ModelAPI_Feature> Model_Objects::featureById(const int theId)
755 {
756   if (theId > 0) {
757     TDF_Label aLab = featuresLabel().FindChild(theId, Standard_False);
758     return feature(aLab);
759   }
760   return std::shared_ptr<ModelAPI_Feature>(); // not found
761 }
762
763 void Model_Objects::synchronizeFeatures(
764   const TDF_LabelList& theUpdated, const bool theUpdateReferences,
765   const bool theExecuteFeatures, const bool theOpen, const bool theFlush)
766 {
767   Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
768   if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
769     return;
770   // after all updates, sends a message that groups of features were created or updated
771   Events_Loop* aLoop = Events_Loop::loop();
772   static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
773   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
774   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
775   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
776   static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
777   static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
778   bool isActive = aLoop->activateFlushes(false);
779
780   // collect all updated labels map
781   TDF_LabelMap anUpdatedMap;
782   TDF_ListIteratorOfLabelList anUpdatedIter(theUpdated);
783   for(; anUpdatedIter.More(); anUpdatedIter.Next()) {
784     TDF_Label& aFeatureLab = anUpdatedIter.Value();
785     while(aFeatureLab.Depth() > 3)
786       aFeatureLab = aFeatureLab.Father();
787     if (myFeatures.IsBound(aFeatureLab))
788       anUpdatedMap.Add(aFeatureLab);
789   }
790
791   // update all objects by checking are they on labels or not
792   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
793   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
794   for (; aLabIter.More(); aLabIter.Next()) {
795     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
796     FeaturePtr aFeature;
797     if (!myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
798       // create a feature
799       aFeature = std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get())->createFeature(
800         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
801         .ToCString(), anOwner);
802       if (!aFeature.get()) {
803         // somethig is wrong, most probably, the opened document has invalid structure
804         Events_InfoMessage("Model_Objects", "Invalid type of object in the document").send();
805         aLabIter.Value()->Label().ForgetAllAttributes();
806         continue;
807       }
808       aFeature->init();
809       // this must be before "setData" to redo the sketch line correctly
810       myFeatures.Bind(aFeatureLabel, aFeature);
811       aNewFeatures.insert(aFeature);
812       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
813       updateHistory(aFeature);
814
815       // event: model is updated
816       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
817     } else {  // nothing is changed, both iterators are incremented
818       aFeature = myFeatures.Find(aFeatureLabel);
819       aKeptFeatures.insert(aFeature);
820       if (anUpdatedMap.Contains(aFeatureLabel)) {
821         if (!theOpen) { // on abort/undo/redo reinitialize attributes if something is changed
822           std::list<std::shared_ptr<ModelAPI_Attribute> > anAttrs =
823             aFeature->data()->attributes("");
824           std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttr = anAttrs.begin();
825           for(; anAttr != anAttrs.end(); anAttr++)
826             (*anAttr)->reinit();
827         }
828         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anUpdateEvent);
829         if (aFeature->getKind() == "Parameter") {
830           // if parameters are changed, update the results (issue 937)
831           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
832           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
833           for (; aRIter != aResults.cend(); aRIter++) {
834             std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
835             if (aRes->data()->isValid() && !aRes->isDisabled()) {
836               ModelAPI_EventCreator::get()->sendUpdated(aRes, anUpdateEvent);
837             }
838           }
839         }
840       }
841     }
842   }
843
844   // check all features are checked: if not => it was removed
845   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
846   while (aFIter.More()) {
847     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
848       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
849         FeaturePtr aFeature = aFIter.Value();
850         // event: model is updated
851         //if (aFeature->isInHistory()) {
852         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
853         //}
854         // results of this feature must be redisplayed (hided)
855         // redisplay also removed feature (used for sketch and AISObject)
856         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
857         updateHistory(aFeature);
858         aFeature->erase();
859
860         // unbind after the "erase" call: on abort sketch
861         // is removes sub-objects that corrupts aFIter
862         myFeatures.UnBind(aFIter.Key());
863         // reinitialize iterator because unbind may corrupt the previous order in the map
864         aFIter.Initialize(myFeatures);
865     } else
866       aFIter.Next();
867   }
868
869   if (theUpdateReferences) {
870     synchronizeBackRefs();
871   }
872   // update results of the features (after features created because
873   // they may be connected, like sketch and sub elements)
874   // After synchronisation of back references because sketch
875   // must be set in sub-elements before "execute" by updateResults
876   std::set<FeaturePtr> aProcessed; // composites must be updated after their subs (issue 360)
877   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
878   for (; aLabIter2.More(); aLabIter2.Next()) {
879     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
880     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
881       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
882       updateResults(aFeature, aProcessed);
883     }
884   }
885   // the synchronize should be done after updateResults
886   // in order to correct back references of updated results
887   if (theUpdateReferences) {
888     synchronizeBackRefs();
889   }
890   if (!theUpdated.IsEmpty()) {
891     // this means there is no control what was modified => remove history cash
892     myHistory.clear();
893   }
894
895   if (theExecuteFeatures)
896     anOwner->executeFeatures() = false;
897   aLoop->activateFlushes(isActive);
898
899   if (theFlush) {
900     aLoop->flush(aDeleteEvent);
901     // delete should be emitted before create to reacts to aborted feature
902     aLoop->flush(aCreateEvent);
903     aLoop->flush(anUpdateEvent);
904     aLoop->flush(aCreateEvent); // after update of features, there could be results created
905     aLoop->flush(aDeleteEvent); // or deleted
906     aLoop->flush(aRedispEvent);
907     aLoop->flush(aToHideEvent);
908   }
909   if (theExecuteFeatures)
910     anOwner->executeFeatures() = true;
911 }
912
913 /// synchronises back references for the given object basing on the collected data
914 void Model_Objects::synchronizeBackRefsForObject(const std::set<AttributePtr>& theNewRefs,
915   ObjectPtr theObject)
916 {
917   if (!theObject.get() || !theObject->data()->isValid())
918     return; // invalid
919   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theObject->data());
920   // iterate new list to compare with curent
921   std::set<AttributePtr>::iterator aNewIter = theNewRefs.begin();
922   for(; aNewIter != theNewRefs.end(); aNewIter++) {
923     if (aData->refsToMe().find(*aNewIter) == aData->refsToMe().end()) {
924       FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aNewIter)->owner());
925       aData->addBackReference(aRefFeat, (*aNewIter)->id());
926     }
927   }
928   if (theNewRefs.size() != aData->refsToMe().size()) { // some back ref must be removed
929     std::set<AttributePtr>::iterator aCurrentIter = aData->refsToMe().begin();
930     while(aCurrentIter != aData->refsToMe().end()) {
931       if (theNewRefs.find(*aCurrentIter) == theNewRefs.end()) {
932         // for external references from other documents this system
933         // is not working: refs are collected from
934         // different Model_Objects, so before remove check this
935         // external object exists and still referenced
936         bool aLeaveIt = false;
937         if ((*aCurrentIter)->owner().get() && (*aCurrentIter)->owner()->document() != myDoc &&
938             (*aCurrentIter)->owner()->data().get() && (*aCurrentIter)->owner()->data()->isValid()) {
939           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
940           (*aCurrentIter)->owner()->data()->referencesToObjects(aRefs);
941           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> >>>::iterator
942             aRefIter = aRefs.begin();
943           for(; aRefIter != aRefs.end(); aRefIter++) {
944             if ((*aCurrentIter)->id() == aRefIter->first) {
945               std::list<std::shared_ptr<ModelAPI_Object> >::iterator anOIt;
946               for(anOIt = aRefIter->second.begin(); anOIt != aRefIter->second.end(); anOIt++) {
947                 if (*anOIt == theObject) {
948                   aLeaveIt = true;
949                 }
950               }
951             }
952           }
953         }
954         if (!aLeaveIt) {
955           aData->removeBackReference(*aCurrentIter);
956           aCurrentIter = aData->refsToMe().begin(); // reinitialize iteration after delete
957         } else aCurrentIter++;
958       } else aCurrentIter++;
959     }
960   }
961   aData->updateConcealmentFlag();
962 }
963
964 static void collectReferences(std::shared_ptr<ModelAPI_Data> theData,
965                               std::map<ObjectPtr, std::set<AttributePtr> >& theRefs)
966 {
967   if (theData.get()) {
968     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
969     theData->referencesToObjects(aRefs);
970     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIt = aRefs.begin();
971     for(; aRefsIt != aRefs.end(); aRefsIt++) {
972       std::list<ObjectPtr>::iterator aRefTo = aRefsIt->second.begin();
973       for(; aRefTo != aRefsIt->second.end(); aRefTo++) {
974         if (*aRefTo) {
975           std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = theRefs.find(*aRefTo);
976           if (aFound == theRefs.end()) {
977             theRefs[*aRefTo] = std::set<AttributePtr>();
978             aFound = theRefs.find(*aRefTo);
979           }
980           aFound->second.insert(theData->attribute(aRefsIt->first));
981         }
982       }
983     }
984   }
985 }
986
987 void Model_Objects::synchronizeBackRefs()
988 {
989   // collect all back references in the separated container: to update everything at once,
990   // without additional Concealment switchin on and off: only the final modification
991
992   // referenced (slave) objects to referencing attirbutes
993   std::map<ObjectPtr, std::set<AttributePtr> > allRefs;
994   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
995   for(; aFeatures.More(); aFeatures.Next()) {
996     FeaturePtr aFeature = aFeatures.Value();
997     collectReferences(aFeature->data(), allRefs);
998   }
999   NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFolders(myFolders);
1000   for(; aFolders.More(); aFolders.Next()) {
1001     ObjectPtr aFolder = aFolders.Value();
1002     collectReferences(aFolder->data(), allRefs);
1003   }
1004   // second iteration: just compare back-references with existing in features and results
1005   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1006     FeaturePtr aFeature = aFeatures.Value();
1007     static std::set<AttributePtr> anEmpty;
1008     std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = allRefs.find(aFeature);
1009     if (aFound == allRefs.end()) { // not found => erase all back references
1010       synchronizeBackRefsForObject(anEmpty, aFeature);
1011     } else {
1012       synchronizeBackRefsForObject(aFound->second, aFeature);
1013       allRefs.erase(aFound); // to check that all refs are counted
1014     }
1015     // also for results
1016     std::list<ResultPtr> aResults;
1017     ModelAPI_Tools::allResults(aFeature, aResults);
1018     std::list<ResultPtr>::iterator aRIter = aResults.begin();
1019     for(; aRIter != aResults.cend(); aRIter++) {
1020       aFound = allRefs.find(*aRIter);
1021       if (aFound == allRefs.end()) { // not found => erase all back references
1022         synchronizeBackRefsForObject(anEmpty, *aRIter);
1023       } else {
1024         synchronizeBackRefsForObject(aFound->second, *aRIter);
1025         allRefs.erase(aFound); // to check that all refs are counted
1026       }
1027     }
1028   }
1029   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1030     FeaturePtr aFeature = aFeatures.Value();
1031     std::list<ResultPtr> aResults;
1032     ModelAPI_Tools::allResults(aFeature, aResults);
1033     // update the concealment status for disply in isConcealed of ResultBody
1034     std::list<ResultPtr>::iterator aRIter = aResults.begin();
1035     for(; aRIter != aResults.cend(); aRIter++) {
1036       (*aRIter)->isConcealed();
1037     }
1038   }
1039   // the rest all refs means that feature references to the external document feature:
1040   // process also them
1041   std::map<ObjectPtr, std::set<AttributePtr> >::iterator anExtIter = allRefs.begin();
1042   for(; anExtIter != allRefs.end(); anExtIter++) {
1043     synchronizeBackRefsForObject(anExtIter->second, anExtIter->first);
1044   }
1045 }
1046
1047 TDF_Label Model_Objects::resultLabel(
1048   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
1049 {
1050   const std::shared_ptr<Model_Data>& aData =
1051     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
1052   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
1053 }
1054
1055 bool Model_Objects::hasCustomName(DataPtr theFeatureData,
1056                                   ResultPtr theResult,
1057                                   int theResultIndex,
1058                                   std::string& theParentName) const
1059 {
1060   ResultCompSolidPtr aCompSolidRes =
1061       std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theFeatureData->owner());
1062   if (aCompSolidRes) {
1063     FeaturePtr anOwner = ModelAPI_Feature::feature(theResult->data()->owner());
1064
1065     // names of sub-solids in CompSolid should be default (for example,
1066     // result of boolean operation 'Boolean_1' is a CompSolid which is renamed to 'MyBOOL',
1067     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1', 'Boolean_1_2' etc.)
1068     std::ostringstream aDefaultName;
1069     aDefaultName << anOwner->name();
1070     // compute default name of CompSolid (name of feature + index of CompSolid's result)
1071     int aCompSolidResultIndex = 0;
1072     const std::list<ResultPtr>& aResults = anOwner->results();
1073     for (std::list<ResultPtr>::const_iterator anIt = aResults.begin();
1074          anIt != aResults.end(); ++anIt, ++aCompSolidResultIndex)
1075       if (aCompSolidRes == *anIt)
1076         break;
1077     aDefaultName << "_" << (aCompSolidResultIndex + 1);
1078     theParentName = aDefaultName.str();
1079     return false;
1080   }
1081
1082   theParentName = ModelAPI_Tools::getDefaultName(theResult, theResultIndex);
1083   return true;
1084 }
1085
1086 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
1087                                 std::shared_ptr<ModelAPI_Result> theResult,
1088                                 const int theResultIndex)
1089 {
1090   theResult->init();
1091   theResult->setDoc(myDoc);
1092   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
1093   if (theResult->data()->name().empty()) {
1094     // if was not initialized, generate event and set a name
1095     std::string aNewName = theFeatureData->name();
1096     if (!hasCustomName(theFeatureData, theResult, theResultIndex, aNewName)) {
1097       std::stringstream aName;
1098       aName << aNewName;
1099       // if there are several results (issue #899: any number of result),
1100       // add unique prefix starting from second
1101       if (theResultIndex > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
1102         aName << "_" << theResultIndex + 1;
1103       aNewName = aName.str();
1104     }
1105     theResult->data()->setName(aNewName);
1106   }
1107 }
1108
1109 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
1110     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1111 {
1112   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1113   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
1114   ObjectPtr anOldObject = object(aLab);
1115   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
1116   if (anOldObject.get()) {
1117     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
1118   }
1119   if (!aResult.get()) {
1120     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1121     storeResult(theFeatureData, aResult, theIndex);
1122   }
1123   return aResult;
1124 }
1125
1126 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
1127     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1128 {
1129   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1130   // for feature create compsolid, but for result sub create body:
1131   // only one level of recursion is supported now
1132   ResultPtr aResultOwner = std::dynamic_pointer_cast<ModelAPI_Result>(theFeatureData->owner());
1133   ObjectPtr anOldObject;
1134   if (aResultOwner.get()) {
1135     TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1136   } else { // in compsolid (higher level result) old object probably may be found
1137     TDataStd_Comment::Set(aLab, ModelAPI_ResultCompSolid::group().c_str());
1138     anOldObject = object(aLab);
1139   }
1140   std::shared_ptr<ModelAPI_ResultBody> aResult;
1141   if (anOldObject.get()) {
1142     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1143   }
1144   if (!aResult.get()) {
1145     // create compsolid anyway; if it is compsolid, it will create sub-bodies internally
1146     if (aResultOwner.get()) {
1147       aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1148     } else {
1149       aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultCompSolid);
1150     }
1151     storeResult(theFeatureData, aResult, theIndex);
1152   }
1153   return aResult;
1154 }
1155
1156 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
1157     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1158 {
1159   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1160   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1161   ObjectPtr anOldObject = object(aLab);
1162   std::shared_ptr<ModelAPI_ResultPart> aResult;
1163   if (anOldObject.get()) {
1164     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1165   }
1166   if (!aResult.get()) {
1167     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1168     storeResult(theFeatureData, aResult, theIndex);
1169   }
1170   return aResult;
1171 }
1172
1173 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
1174     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1175     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1176 {
1177   std::shared_ptr<ModelAPI_ResultPart> aResult = createPart(theFeatureData, theIndex);
1178   aResult->data()->reference(Model_ResultPart::BASE_REF_ID())->setValue(theOrigin);
1179   return aResult;
1180 }
1181
1182 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
1183     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1184 {
1185   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1186   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1187   ObjectPtr anOldObject = object(aLab);
1188   std::shared_ptr<ModelAPI_ResultGroup> aResult;
1189   if (anOldObject.get()) {
1190     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1191   }
1192   if (!aResult.get()) {
1193     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1194     storeResult(theFeatureData, aResult, theIndex);
1195   }
1196   return aResult;
1197 }
1198
1199 std::shared_ptr<ModelAPI_ResultField> Model_Objects::createField(
1200     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1201 {
1202   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1203   TDataStd_Comment::Set(aLab, ModelAPI_ResultField::group().c_str());
1204   ObjectPtr anOldObject = object(aLab);
1205   std::shared_ptr<ModelAPI_ResultField> aResult;
1206   if (anOldObject.get()) {
1207     aResult = std::dynamic_pointer_cast<ModelAPI_ResultField>(anOldObject);
1208   }
1209   if (!aResult.get()) {
1210     aResult = std::shared_ptr<ModelAPI_ResultField>(new Model_ResultField(theFeatureData));
1211     storeResult(theFeatureData, aResult, theIndex);
1212   }
1213   return aResult;
1214 }
1215
1216 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
1217       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1218 {
1219   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1220   TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
1221   ObjectPtr anOldObject = object(aLab);
1222   std::shared_ptr<ModelAPI_ResultParameter> aResult;
1223   if (anOldObject.get()) {
1224     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
1225   }
1226   if (!aResult.get()) {
1227     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
1228     storeResult(theFeatureData, aResult, theIndex);
1229   }
1230   return aResult;
1231 }
1232
1233 std::shared_ptr<ModelAPI_Folder> Model_Objects::createFolder(
1234     const std::shared_ptr<ModelAPI_Feature>& theBeforeThis)
1235 {
1236   FolderPtr aFolder(new ModelAPI_Folder);
1237   if (!aFolder)
1238     return aFolder;
1239
1240   TDF_Label aFeaturesLab = featuresLabel();
1241   TDF_Label aFolderLab = aFeaturesLab.NewChild();
1242   // store feature in the features array: before "initData" because in macro features
1243   // in initData it creates new features, appeared later than this
1244   TDF_Label aPrevFeatureLab;
1245   if (theBeforeThis.get()) { // searching for the previous feature label
1246     std::shared_ptr<Model_Data> aPrevData =
1247         std::dynamic_pointer_cast<Model_Data>(theBeforeThis->data());
1248     if (aPrevData.get()) {
1249       aPrevFeatureLab = nextLabel(aPrevData->label().Father(), true);
1250     }
1251   } else { // find the label of the last feature
1252     Handle(TDataStd_ReferenceArray) aRefs;
1253     if (aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1254       aPrevFeatureLab = aRefs->Value(aRefs->Upper());
1255   }
1256   AddToRefArray(aFeaturesLab, aFolderLab, aPrevFeatureLab);
1257
1258   // keep the feature ID to restore document later correctly
1259   TDataStd_Comment::Set(aFolderLab, ModelAPI_Folder::ID().c_str());
1260   myFolders.Bind(aFolderLab, aFolder);
1261   // must be before the event sending: for OB the feature is already added
1262   updateHistory(ModelAPI_Folder::group());
1263   updateHistory(ModelAPI_Feature::group());
1264
1265   // must be after binding to the map because of "Box" macro feature that
1266   // creates other features in "initData"
1267   initData(aFolder, aFolderLab, TAG_FEATURE_ARGUMENTS);
1268   // event: folder is added, must be before "initData" to update OB correctly on Duplicate:
1269   // first new part, then the content
1270   static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
1271   ModelAPI_EventCreator::get()->sendUpdated(aFolder, anEvent);
1272
1273   return aFolder;
1274 }
1275
1276 void Model_Objects::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1277 {
1278   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFolder->data());
1279   if (!aData.get() || !aData->isValid())
1280     return;
1281
1282   // this must be before erase since theFolder erasing removes all information about it
1283   clearHistory(theFolder);
1284   // erase fields
1285   theFolder->erase();
1286
1287   TDF_Label aFolderLabel = aData->label().Father();
1288   if (myFolders.IsBound(aFolderLabel))
1289     myFolders.UnBind(aFolderLabel);
1290
1291   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1292   ModelAPI_EventCreator::get()->sendUpdated(theFolder, EVENT_DISP);
1293   // erase all attributes under the label of feature
1294   aFolderLabel.ForgetAllAttributes();
1295   // remove it from the references array
1296   RemoveFromRefArray(featuresLabel(), aFolderLabel);
1297   // event: feature is deleted
1298   ModelAPI_EventCreator::get()->sendDeleted(theFolder->document(), ModelAPI_Folder::group());
1299   updateHistory(ModelAPI_Folder::group());
1300   updateHistory(ModelAPI_Feature::group());
1301 }
1302
1303 static FeaturePtr limitingFeature(std::list<FeaturePtr>& theFeatures, const bool isLast)
1304 {
1305   FeaturePtr aFeature;
1306   if (isLast) {
1307     aFeature = theFeatures.back();
1308     theFeatures.pop_back();
1309   } else {
1310     aFeature = theFeatures.front();
1311     theFeatures.pop_front();
1312   }
1313   return aFeature;
1314 }
1315
1316 std::shared_ptr<ModelAPI_Folder> Model_Objects::findFolder(
1317       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1318       const bool theBelow)
1319 {
1320   if (theFeatures.empty())
1321     return FolderPtr(); // nothing to move
1322
1323   TDF_Label aFeaturesLab = featuresLabel();
1324   Handle(TDataStd_ReferenceArray) aRefs;
1325   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1326     return FolderPtr(); // no reference array (something is wrong)
1327
1328   std::list<std::shared_ptr<ModelAPI_Feature> > aFeatures = theFeatures;
1329   std::shared_ptr<ModelAPI_Feature> aLimitingFeature = limitingFeature(aFeatures, theBelow);
1330
1331   std::shared_ptr<Model_Data> aData =
1332       std::static_pointer_cast<Model_Data>(aLimitingFeature->data());
1333   if (!aData || !aData->isValid())
1334     return FolderPtr(); // invalid feature
1335
1336   // label of the first feature in the list for fast searching
1337   TDF_Label aFirstFeatureLabel = aData->label().Father();
1338
1339   // find a folder above the features and
1340   // check the given features represent a sequential list of objects following the folder
1341   FolderPtr aFoundFolder;
1342   TDF_Label aLastFeatureInFolder;
1343   int aRefIndex = aRefs->Lower();
1344   for(; aRefIndex <= aRefs->Upper(); ++aRefIndex) { // iterate all existing features
1345     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1346     if (IsEqual(aCurLabel, aFirstFeatureLabel))
1347       break; // no need to continue searching
1348
1349     // searching the folder below, just continue to search last feature from the list
1350     if (theBelow)
1351       continue;
1352
1353     if (!aLastFeatureInFolder.IsNull()) {
1354       if (IsEqual(aCurLabel, aLastFeatureInFolder))
1355         aLastFeatureInFolder.Nullify(); // the last feature in the folder is achived
1356       continue;
1357     }
1358
1359     aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(folder(aCurLabel));
1360     if (aFoundFolder) {
1361       AttributeReferencePtr aLastFeatAttr =
1362           aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1363       if (aLastFeatAttr) {
1364         // setup iterating inside a folder to find last feature
1365         ObjectPtr aLastFeature = aLastFeatAttr->value();
1366         if (aLastFeature) {
1367           aData = std::static_pointer_cast<Model_Data>(aLastFeature->data());
1368           if (aData && aData->isValid())
1369             aLastFeatureInFolder = aData->label().Father();
1370         }
1371       }
1372     }
1373   }
1374
1375   if (theBelow && aRefIndex < aRefs->Upper()) {
1376     // check the next object is a folder
1377     TDF_Label aLabel = aRefs->Value(aRefIndex + 1);
1378     aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(folder(aLabel));
1379   }
1380
1381   if (!aLastFeatureInFolder.IsNull() || // the last feature of the folder above is not found
1382       !aFoundFolder)
1383     return FolderPtr();
1384
1385   // check the given features are sequential list
1386   int aStep = theBelow ? -1 : 1;
1387   for (aRefIndex += aStep;
1388        !aFeatures.empty() && aRefIndex >= aRefs->Lower() && aRefIndex <= aRefs->Upper();
1389        aRefIndex += aStep) {
1390     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1391     TDF_Label aFeatureLabel;
1392
1393     aLimitingFeature = limitingFeature(aFeatures, theBelow);
1394     aData = std::static_pointer_cast<Model_Data>(aLimitingFeature->data());
1395     if (aData && aData->isValid())
1396       aFeatureLabel = aData->label().Father();
1397
1398     if (!IsEqual(aCurLabel, aFeatureLabel))
1399       return FolderPtr(); // not a sequential list
1400   }
1401
1402   return aFoundFolder;
1403 }
1404
1405 bool Model_Objects::moveToFolder(
1406       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1407       const std::shared_ptr<ModelAPI_Folder>& theFolder)
1408 {
1409   if (theFeatures.empty() || !theFolder)
1410     return false;
1411
1412   // labels for the folder and last feature in the list
1413   TDF_Label aFolderLabel, aLastFeatureLabel;
1414   std::shared_ptr<Model_Data> aData =
1415       std::static_pointer_cast<Model_Data>(theFolder->data());
1416   if (aData && aData->isValid())
1417     aFolderLabel = aData->label().Father();
1418   aData = std::static_pointer_cast<Model_Data>(theFeatures.back()->data());
1419   if (aData && aData->isValid())
1420     aLastFeatureLabel = aData->label().Father();
1421
1422   if (aFolderLabel.IsNull() || aLastFeatureLabel.IsNull())
1423     return false;
1424
1425   AttributeReferencePtr aFirstFeatAttr =
1426       theFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID());
1427   AttributeReferencePtr aLastFeatAttr =
1428       theFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1429   bool initFirstAttr = !aFirstFeatAttr->value().get();
1430   bool initLastAttr  = !aLastFeatAttr->value().get();
1431
1432   // check the folder is below the list of features
1433   bool isFolderBelow = false;
1434   TDF_Label aFeaturesLab = featuresLabel();
1435   Handle(TDataStd_ReferenceArray) aRefs;
1436   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1437     return false; // no reference array (something is wrong)
1438   for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1439     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1440     if (aCurLabel == aFolderLabel)
1441       break; // folder is above the features
1442     else if (aCurLabel == aLastFeatureLabel) {
1443       isFolderBelow = true;
1444       break;
1445     }
1446   }
1447
1448   if (isFolderBelow) {
1449     aData = std::static_pointer_cast<Model_Data>(theFeatures.front()->data());
1450     if (!aData || !aData->isValid())
1451       return false;
1452     TDF_Label aPrevFeatureLabel = aData->label().Father();
1453     // label of the feature before the first feature in the list
1454     for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex)
1455       if (aPrevFeatureLabel == aRefs->Value(aRefIndex)) {
1456         if (aRefIndex == aRefs->Lower())
1457           aPrevFeatureLabel.Nullify();
1458         else
1459           aPrevFeatureLabel = aRefs->Value(aRefIndex - 1);
1460         break;
1461       }
1462
1463     // move the folder in the list of references before the first feature
1464     RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1465     AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1466     // update first feature of the folder
1467     initFirstAttr = true;
1468   } else {
1469     // update last feature of the folder
1470     initLastAttr = true;
1471   }
1472
1473   if (initFirstAttr)
1474     aFirstFeatAttr->setValue(theFeatures.front());
1475   if (initLastAttr)
1476     aLastFeatAttr->setValue(theFeatures.back());
1477
1478   updateHistory(ModelAPI_Feature::group());
1479   return true;
1480 }
1481
1482 static FolderPtr inFolder(const FeaturePtr& theFeature, const std::string& theFolderAttr)
1483 {
1484   const std::set<AttributePtr>& aRefs = theFeature->data()->refsToMe();
1485   for (std::set<AttributePtr>::iterator anIt = aRefs.begin(); anIt != aRefs.end(); ++anIt) {
1486     if ((*anIt)->id() != theFolderAttr)
1487       continue;
1488
1489     ObjectPtr anOwner = (*anIt)->owner();
1490     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(anOwner);
1491     if (aFolder.get())
1492       return aFolder;
1493   }
1494   return FolderPtr();
1495 }
1496
1497 static FolderPtr isExtractionCorrect(const FolderPtr& theFirstFeatureFolder,
1498                                      const FolderPtr& theLastFeatureFolder,
1499                                      bool& isExtractBefore)
1500 {
1501   if (theFirstFeatureFolder.get()) {
1502     if (theLastFeatureFolder.get())
1503       return theFirstFeatureFolder == theLastFeatureFolder ? theFirstFeatureFolder : FolderPtr();
1504     else
1505       isExtractBefore = true;
1506     return theFirstFeatureFolder;
1507   } else if (theLastFeatureFolder.get()) {
1508     isExtractBefore = false;
1509     return theLastFeatureFolder;
1510   }
1511   // no folder found
1512   return FolderPtr();
1513 }
1514
1515 bool Model_Objects::removeFromFolder(
1516       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1517       const bool theBefore)
1518 {
1519   if (theFeatures.empty())
1520     return false;
1521
1522   FolderPtr aFirstFeatureFolder =
1523       inFolder(theFeatures.front(), ModelAPI_Folder::FIRST_FEATURE_ID());
1524   FolderPtr aLastFeatureFolder =
1525       inFolder(theFeatures.back(),  ModelAPI_Folder::LAST_FEATURE_ID());
1526
1527   bool isExtractBeforeFolder = theBefore;
1528   FolderPtr aFoundFolder =
1529       isExtractionCorrect(aFirstFeatureFolder, aLastFeatureFolder, isExtractBeforeFolder);
1530   if (!aFoundFolder)
1531     return false; // list of features cannot be extracted
1532
1533   // references of the current folder
1534   ObjectPtr aFolderStartFeature;
1535   ObjectPtr aFolderEndFeature;
1536   if (aFirstFeatureFolder != aLastFeatureFolder) {
1537     aFolderStartFeature = aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->value();
1538     aFolderEndFeature   = aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->value();
1539   }
1540
1541   FeaturePtr aFeatureToFind = isExtractBeforeFolder ? theFeatures.back() : theFeatures.front();
1542   std::shared_ptr<Model_Data> aData =
1543       std::static_pointer_cast<Model_Data>(aFeatureToFind->data());
1544   if (!aData || !aData->isValid())
1545     return false;
1546   TDF_Label aLabelToFind = aData->label().Father();
1547
1548   // search the label in the list of references
1549   TDF_Label aFeaturesLab = featuresLabel();
1550   Handle(TDataStd_ReferenceArray) aRefs;
1551   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1552     return false; // no reference array (something is wrong)
1553   int aRefIndex = aRefs->Lower();
1554   for (; aRefIndex <= aRefs->Upper(); ++aRefIndex)
1555     if (aRefs->Value(aRefIndex) == aLabelToFind)
1556       break;
1557
1558   // update folder position
1559   if (isExtractBeforeFolder) {
1560     aData = std::dynamic_pointer_cast<Model_Data>(aFoundFolder->data());
1561     TDF_Label aFolderLabel = aData->label().Father();
1562     TDF_Label aPrevFeatureLabel = aRefs->Value(aRefIndex);
1563     // update start reference of the folder
1564     if (aFolderStartFeature.get())
1565       aFolderStartFeature = feature(aRefs->Value(aRefIndex + 1));
1566     // move the folder in the list of references after the last feature from the list
1567     RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1568     AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1569   } else {
1570     // update end reference of the folder
1571     if (aFolderEndFeature.get())
1572       aFolderEndFeature = feature(aRefs->Value(aRefIndex - 1));
1573   }
1574
1575   // update folder references
1576   aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->setValue(aFolderStartFeature);
1577   aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aFolderEndFeature);
1578
1579   updateHistory(ModelAPI_Feature::group());
1580   return true;
1581 }
1582
1583
1584 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
1585     const std::shared_ptr<ModelAPI_Result>& theResult)
1586 {
1587   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1588   if (aData.get()) {
1589     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1590     FeaturePtr aFeature = feature(aFeatureLab);
1591     if (!aFeature.get() && aFeatureLab.Depth() > 1) { // this may be sub-result of result
1592       aFeatureLab = aFeatureLab.Father().Father();
1593       aFeature = feature(aFeatureLab);
1594     }
1595     return aFeature;
1596   }
1597   return FeaturePtr();
1598 }
1599
1600 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
1601 {
1602   if (theFeature->data()->isValid()) {
1603     TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1604     if (aLabIter.More()) {
1605       TDF_Label anArgLab = aLabIter.Value();
1606       Handle(TDataStd_Comment) aGroup;
1607       if (aLabIter.Value().FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1608         return TCollection_AsciiString(aGroup->Get()).ToCString();
1609       }
1610     }
1611   }
1612   static std::string anEmpty;
1613   return anEmpty; // not found
1614 }
1615
1616 void Model_Objects::updateResults(FeaturePtr theFeature, std::set<FeaturePtr>& theProcessed)
1617 {
1618   if (theProcessed.find(theFeature) != theProcessed.end())
1619     return;
1620   theProcessed.insert(theFeature);
1621   // for composites update subs recursively (sketch elements results are needed for the sketch)
1622   CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
1623   if (aComp.get() && aComp->getKind() != "Part") { // don't go inside of parts sub-features
1624     // update subs of composites first
1625     int aSubNum = aComp->numberOfSubs();
1626     for(int a = 0; a < aSubNum; a++) {
1627       FeaturePtr aSub = aComp->subFeature(a);
1628       updateResults(aComp->subFeature(a), theProcessed);
1629     }
1630   }
1631
1632   // for not persistent is will be done by parametric updater automatically
1633   //if (!theFeature->isPersistentResult()) return;
1634   // check the existing results and remove them if there is nothing on the label
1635   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1636   while(aResIter != theFeature->results().cend()) {
1637     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1638     if (aBody.get()) {
1639       std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(aBody->data());
1640       if (!aData.get() || !aData->isValid() || (!aBody->isDisabled() && aData->isDeleted())) {
1641         // found a disappeared result => remove it
1642         theFeature->eraseResultFromList(aBody);
1643         // start iterate from beginning because iterator is corrupted by removing
1644         aResIter = theFeature->results().cbegin();
1645         continue;
1646       }
1647     }
1648     aResIter++;
1649   }
1650   // it may be on undo
1651   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
1652     return;
1653   // check that results are presented on all labels
1654   int aResSize = int(theFeature->results().size());
1655   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1656   for(; aLabIter.More(); aLabIter.Next()) {
1657     // here must be GUID of the feature
1658     int aResIndex = aLabIter.Value().Tag() - 1;
1659     ResultPtr aNewBody;
1660     if (aResSize <= aResIndex) {
1661       TDF_Label anArgLab = aLabIter.Value();
1662       Handle(TDataStd_Comment) aGroup;
1663       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1664         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str() ||
1665             aGroup->Get() == ModelAPI_ResultCompSolid::group().c_str()) {
1666           aNewBody = createBody(theFeature->data(), aResIndex);
1667         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1668           std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex);
1669           theFeature->setResult(aNewP, aResIndex);
1670           if (!aNewP->partDoc().get())
1671             // create the part result: it is better to restore the previous result if it is possible
1672             theFeature->execute();
1673         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1674           theFeature->execute(); // construction shapes are needed for sketch solver
1675         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1676           aNewBody = createGroup(theFeature->data(), aResIndex);
1677         } else if (aGroup->Get() == ModelAPI_ResultField::group().c_str()) {
1678           aNewBody = createField(theFeature->data(), aResIndex);
1679         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
1680           theFeature->attributeChanged("expression"); // just produce a value
1681         } else {
1682           Events_InfoMessage("Model_Objects", "Unknown type of result is found in the document:")
1683             .arg(TCollection_AsciiString(aGroup->Get()).ToCString()).send();
1684         }
1685       }
1686       if (aNewBody && !aNewBody->data()->isDeleted()) {
1687         theFeature->setResult(aNewBody, aResIndex);
1688       }
1689     }
1690   }
1691 }
1692
1693 ResultPtr Model_Objects::findByName(const std::string theName)
1694 {
1695   ResultPtr aResult;
1696   FeaturePtr aResFeature; // keep feature to return the latest one
1697   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
1698   for(; anObjIter.More(); anObjIter.Next()) {
1699     FeaturePtr& aFeature = anObjIter.ChangeValue();
1700     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
1701       continue;
1702     std::list<ResultPtr> allResults;
1703     ModelAPI_Tools::allResults(aFeature, allResults);
1704     std::list<ResultPtr>::iterator aRIter = allResults.begin();
1705     for (; aRIter != allResults.cend(); aRIter++) {
1706       ResultPtr aRes = *aRIter;
1707       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
1708           aRes->data()->name() == theName)
1709       {
1710         if (!aResult.get() || isLater(aFeature, aResFeature)) { // select the latest
1711           aResult = aRes;
1712           aResFeature = aFeature;
1713         }
1714       }
1715     }
1716   }
1717   return aResult;
1718 }
1719
1720 TDF_Label Model_Objects::nextLabel(TDF_Label theCurrent, const bool theReverse)
1721 {
1722   Handle(TDataStd_ReferenceArray) aRefs;
1723   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1724     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
1725       TDF_Label aCurLab = aRefs->Value(a);
1726       if (aCurLab.IsEqual(theCurrent)) {
1727         a += theReverse ? -1 : 1;
1728         if (a >= aRefs->Lower() && a <= aRefs->Upper())
1729           return aRefs->Value(a);
1730         break; // finish iiteration: it's last feature
1731       }
1732     }
1733   }
1734   return TDF_Label();
1735 }
1736
1737 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, const bool theReverse)
1738 {
1739   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1740   if (aData.get() && aData->isValid()) {
1741     TDF_Label aFeatureLabel = aData->label().Father();
1742     TDF_Label aNextLabel = nextLabel(aFeatureLabel, theReverse);
1743     if (!aNextLabel.IsNull())
1744       return feature(aNextLabel);
1745   }
1746   return FeaturePtr(); // not found, last, or something is wrong
1747 }
1748
1749 FeaturePtr Model_Objects::firstFeature()
1750 {
1751   Handle(TDataStd_ReferenceArray) aRefs;
1752   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1753     return feature(aRefs->Value(aRefs->Lower()));
1754   }
1755   return FeaturePtr(); // no features at all
1756 }
1757
1758 FeaturePtr Model_Objects::lastFeature()
1759 {
1760   Handle(TDataStd_ReferenceArray) aRefs;
1761   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1762     return feature(aRefs->Value(aRefs->Upper()));
1763   }
1764   return FeaturePtr(); // no features at all
1765 }
1766
1767 bool Model_Objects::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
1768 {
1769   std::shared_ptr<Model_Data> aLaterD = std::static_pointer_cast<Model_Data>(theLater->data());
1770   std::shared_ptr<Model_Data> aCurrentD = std::static_pointer_cast<Model_Data>(theCurrent->data());
1771   if (aLaterD.get() && aLaterD->isValid() && aCurrentD.get() && aCurrentD->isValid()) {
1772     TDF_Label aLaterL = aLaterD->label().Father();
1773     TDF_Label aCurrentL = aCurrentD->label().Father();
1774     int aLaterI = -1, aCurentI = -1; // not found yet state
1775     Handle(TDataStd_ReferenceArray) aRefs;
1776     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1777       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
1778         TDF_Label aCurLab = aRefs->Value(a);
1779         if (aCurLab.IsEqual(aLaterL)) {
1780           aLaterI = a;
1781         } else if (aCurLab.IsEqual(aCurrentL)) {
1782           aCurentI = a;
1783         } else continue;
1784         if (aLaterI != -1 && aCurentI != -1) // both are found
1785           return aLaterI > aCurentI;
1786       }
1787     }
1788   }
1789   return false; // not found, or something is wrong
1790 }
1791
1792 std::list<std::shared_ptr<ModelAPI_Object> > Model_Objects::allObjects()
1793 {
1794   std::list<std::shared_ptr<ModelAPI_Object> > aResult;
1795   Handle(TDataStd_ReferenceArray) aRefs;
1796   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1797     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
1798       ObjectPtr anObject = object(aRefs->Value(a));
1799       if (!anObject.get()) // is it a folder?
1800         anObject = folder(aRefs->Value(a));
1801       if (anObject.get())
1802         aResult.push_back(anObject);
1803     }
1804   }
1805   return aResult;
1806 }
1807
1808 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
1809 {
1810   std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
1811   Handle(TDataStd_ReferenceArray) aRefs;
1812   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1813     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
1814       FeaturePtr aFeature = feature(aRefs->Value(a));
1815       if (aFeature.get())
1816         aResult.push_back(aFeature);
1817     }
1818   }
1819   return aResult;
1820 }
1821
1822 int Model_Objects::numInternalFeatures()
1823 {
1824   Handle(TDataStd_ReferenceArray) aRefs;
1825   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1826     return aRefs->Upper() - aRefs->Lower() + 1;
1827   }
1828   return 0; // invalid
1829 }
1830
1831 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
1832 {
1833   Handle(TDataStd_ReferenceArray) aRefs;
1834   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1835     return feature(aRefs->Value(aRefs->Lower() + theIndex));
1836   }
1837   return FeaturePtr(); // invalid
1838 }
1839
1840 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1841 {
1842   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1843
1844 }
1845 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1846 {
1847   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1848 }