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