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