Salome HOME
Added ability to deselect objects on edit in Boolean operation and reselect them...
[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_ResultGroup.h>
16 #include <Model_ResultParameter.h>
17 #include <ModelAPI_Validator.h>
18 #include <ModelAPI_CompositeFeature.h>
19
20 #include <Events_Loop.h>
21 #include <Events_Error.h>
22
23 #include <TDataStd_Integer.hxx>
24 #include <TDataStd_Comment.hxx>
25 #include <TDF_ChildIDIterator.hxx>
26 #include <TDataStd_ReferenceArray.hxx>
27 #include <TDataStd_HLabelArray1.hxx>
28 #include <TDataStd_Name.hxx>
29 #include <TDF_Reference.hxx>
30 #include <TDF_ChildIDIterator.hxx>
31 #include <TDF_LabelMapHasher.hxx>
32
33 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
34
35 // feature sub-labels
36 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
37 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
38
39 ///
40 /// 0:1:2 - where features are located
41 /// 0:1:2:N:1 - data of the feature N
42 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
43
44 Model_Objects::Model_Objects(TDF_Label theMainLab) : myMain(theMainLab)
45 {
46 }
47
48 void Model_Objects::setOwner(DocumentPtr theDoc)
49 {
50   myDoc = theDoc;
51   // update all fields and recreate features and result objects if needed
52   synchronizeFeatures(false, true, true);
53   myHistory.clear();
54 }
55
56 Model_Objects::~Model_Objects()
57 {
58   // delete all features of this document
59   Events_Loop* aLoop = Events_Loop::loop();
60   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myFeatures);
61   for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
62     FeaturePtr aFeature = aFeaturesIter.Value();
63     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
64     ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
65     ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
66     aFeature->eraseResults();
67     aFeature->erase();
68   }
69   myFeatures.Clear();
70   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
71   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
72
73 }
74
75 /// Appends to the array of references a new referenced label
76 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced, TDF_Label& thePrevLab)
77 {
78   Handle(TDataStd_ReferenceArray) aRefs;
79   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
80     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
81     aRefs->SetValue(0, theReferenced);
82   } else {  // extend array by one more element
83     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
84                                                                         aRefs->Upper() + 1);
85     int aPassedPrev = 0; // prev feature is found and passed
86     if (thePrevLab.IsNull()) { // null means that inserted feature must be the first
87       aNewArray->SetValue(aRefs->Lower(), theReferenced);
88       aPassedPrev = 1;
89     }
90     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
91       aNewArray->SetValue(a + aPassedPrev, aRefs->Value(a));
92       if (!aPassedPrev && aRefs->Value(a).IsEqual(thePrevLab)) {
93         aPassedPrev = 1;
94         aNewArray->SetValue(a + 1, theReferenced);
95       }
96     }
97     if (!aPassedPrev) // not found: unknown situation
98       aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
99     aRefs->SetInternalArray(aNewArray);
100   }
101 }
102
103 void Model_Objects::addFeature(FeaturePtr theFeature, const FeaturePtr theAfterThis)
104 {
105   if (!theFeature->isAction()) {  // do not add action to the data model
106     TDF_Label aFeaturesLab = featuresLabel();
107     TDF_Label aFeatureLab = aFeaturesLab.NewChild();
108     // store feature in the features array: before "initData" because in macro features
109     // in initData it creates new features, appeared later than this
110     TDF_Label aPrevFeateureLab;
111     if (theAfterThis.get()) { // searching for the previous feature label
112       std::shared_ptr<Model_Data> aPrevData = 
113         std::dynamic_pointer_cast<Model_Data>(theAfterThis->data());
114       if (aPrevData.get()) {
115         aPrevFeateureLab = aPrevData->label().Father();
116       }
117     }
118     AddToRefArray(aFeaturesLab, aFeatureLab, aPrevFeateureLab);
119
120     initData(theFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
121     // keep the feature ID to restore document later correctly
122     TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
123     myFeatures.Bind(aFeatureLab, theFeature);
124     // event: feature is added
125     static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
126     ModelAPI_EventCreator::get()->sendUpdated(theFeature, anEvent);
127     theFeature->setDisabled(false); // by default created feature is enabled
128     updateHistory(ModelAPI_Feature::group());
129   } else { // make feature has not-null data anyway
130     theFeature->setData(Model_Data::invalidData());
131     theFeature->setDoc(myDoc);
132   }
133 }
134
135 /// Appends to the array of references a new referenced label.
136 /// If theIndex is not -1, removes element at this index, not theReferenced.
137 /// \returns the index of removed element
138 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, 
139   const int theIndex = -1)
140 {
141   int aResult = -1;  // no returned
142   Handle(TDataStd_ReferenceArray) aRefs;
143   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
144     if (aRefs->Length() == 1) {  // just erase an array
145       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
146         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
147       }
148       aResult = 0;
149     } else {  // reduce the array
150       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
151                                                                           aRefs->Upper() - 1);
152       int aCount = aRefs->Lower();
153       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
154         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
155           aCount--;
156           aResult = a;
157         } else {
158           aNewArray->SetValue(aCount, aRefs->Value(a));
159         }
160       }
161       aRefs->SetInternalArray(aNewArray);
162     }
163   }
164   return aResult;
165 }
166
167 void Model_Objects::refsToFeature(FeaturePtr theFeature,
168   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
169 {
170   // check the feature: it must have no depended objects on it
171   // the dependencies can be in the feature results
172   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
173   for(; aResIter != theFeature->results().cend(); aResIter++) {
174     ResultPtr aResult = (*aResIter);
175     std::shared_ptr<Model_Data> aData = 
176       std::dynamic_pointer_cast<Model_Data>(aResult->data());
177     if (aData.get() != NULL) {
178       const std::set<AttributePtr>& aRefs = aData->refsToMe();
179       std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
180       for(; aRefIt != aRefLast; aRefIt++) {
181         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
182         if (aFeature.get() != NULL)
183           theRefs.insert(aFeature);
184       }
185     }
186   }
187   // the dependencies can be in the feature itself
188   std::shared_ptr<Model_Data> aData = 
189       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
190   if (aData && !aData->refsToMe().empty()) {
191     const std::set<AttributePtr>& aRefs = aData->refsToMe();
192     std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
193     for(; aRefIt != aRefLast; aRefIt++) {
194       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
195       if (aFeature.get() != NULL)
196         theRefs.insert(aFeature);
197     }
198   }
199
200   if (!theRefs.empty() && isSendError) {
201     Events_Error::send(
202       "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
203   }
204 }
205
206 void Model_Objects::removeFeature(FeaturePtr theFeature)
207 {
208   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
209   if (aData && aData->isValid()) {
210     // checking that the sub-element of composite feature is removed: if yes, inform the owner
211     std::set<std::shared_ptr<ModelAPI_Feature> > aRefs;
212     refsToFeature(theFeature, aRefs, false);
213     std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aRefIter = aRefs.begin();
214     for(; aRefIter != aRefs.end(); aRefIter++) {
215       std::shared_ptr<ModelAPI_CompositeFeature> aComposite = 
216         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aRefIter);
217       if (aComposite.get()) {
218         aComposite->removeFeature(theFeature);
219       }
220     }
221     // this must be before erase since theFeature erasing removes all information about
222     // the feature results and groups of results
223     // To reproduce: create sketch, extrusion, remove sketch => constructions tree is not updated
224     clearHistory(theFeature);
225     // erase fields
226     theFeature->erase();
227
228     TDF_Label aFeatureLabel = aData->label().Father();
229     if (myFeatures.IsBound(aFeatureLabel))
230       myFeatures.UnBind(aFeatureLabel);
231
232     static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
233     ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
234     // erase all attributes under the label of feature
235     aFeatureLabel.ForgetAllAttributes();
236     // remove it from the references array
237     RemoveFromRefArray(featuresLabel(), aFeatureLabel);
238     // event: feature is deleted
239     ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
240     // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
241     Events_Loop::loop()->flush(EVENT_DISP);
242     updateHistory(ModelAPI_Feature::group());
243   }
244 }
245
246 void Model_Objects::clearHistory(ObjectPtr theObj)
247 {
248   if (theObj) {
249     const std::string aGroup = theObj->groupName();
250     std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(aGroup);
251     if (aHIter != myHistory.end())
252       myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
253     if (theObj->groupName() == ModelAPI_Feature::group()) { // clear results group of the feature
254       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
255       std::string aResultGroup = featureResultGroup(aFeature);
256       if (!aResultGroup.empty()) {
257         std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = 
258           myHistory.find(aResultGroup);
259         if (aHIter != myHistory.end())
260           myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
261       }
262     }
263   }
264 }
265
266 void Model_Objects::createHistory(const std::string& theGroupID)
267 {
268   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroupID);
269   if (aHIter == myHistory.end()) {
270     myHistory[theGroupID] = std::vector<ObjectPtr>();
271     std::vector<ObjectPtr>& aResult = myHistory[theGroupID];
272     // iterate the array of references and get feature by feature from the array
273     bool isFeature = theGroupID == ModelAPI_Feature::group();
274     Handle(TDataStd_ReferenceArray) aRefs;
275     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
276       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
277         FeaturePtr aFeature = feature(aRefs->Value(a));
278         if (aFeature.get()) {
279           if (isFeature) { // here may be also disabled features
280             if (aFeature->isInHistory()) {
281               aResult.push_back(aFeature);
282             }
283           } else if (!aFeature->isDisabled()) { // iterate all results of not-disabled feature
284             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
285             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
286             for (; aRIter != aResults.cend(); aRIter++) {
287               ResultPtr aRes = *aRIter;
288               if (aRes->groupName() != theGroupID) break; // feature have only same group results
289               if (!aRes->isDisabled() && aRes->isInHistory() && !aRes->isConcealed()) {
290                 aResult.push_back(*aRIter);
291               }
292             }
293           }
294         }
295       }
296     }
297   }
298 }
299
300 void Model_Objects::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
301 {
302   clearHistory(theObject);
303 }
304
305 void Model_Objects::updateHistory(const std::string theGroup)
306 {
307   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroup);
308   if (aHIter != myHistory.end())
309     myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
310 }
311
312 FeaturePtr Model_Objects::feature(TDF_Label theLabel) const
313 {
314   if (myFeatures.IsBound(theLabel))
315     return myFeatures.Find(theLabel);
316   return FeaturePtr();  // not found
317 }
318
319 ObjectPtr Model_Objects::object(TDF_Label theLabel)
320 {
321   // try feature by label
322   FeaturePtr aFeature = feature(theLabel);
323   if (aFeature)
324     return feature(theLabel);
325   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
326   aFeature = feature(aFeatureLabel);
327   if (aFeature) {
328     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
329     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
330     for (; aRIter != aResults.cend(); aRIter++) {
331       std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
332           (*aRIter)->data());
333       if (aResData->label().Father().IsEqual(theLabel))
334         return *aRIter;
335     }
336   }
337   return FeaturePtr();  // not found
338 }
339
340 ObjectPtr Model_Objects::object(const std::string& theGroupID, const int theIndex)
341 {
342   if (theIndex == -1)
343     return ObjectPtr();
344   createHistory(theGroupID);
345   return myHistory[theGroupID][theIndex];
346 }
347
348 std::shared_ptr<ModelAPI_Object> Model_Objects::objectByName(
349     const std::string& theGroupID, const std::string& theName)
350 {
351   createHistory(theGroupID);
352   std::vector<ObjectPtr>& allObjs = myHistory[theGroupID];
353   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin();
354   for(; anObjIter != allObjs.end(); anObjIter++) {
355     if ((*anObjIter)->data()->name() == theName)
356       return *anObjIter;
357   }
358   // not found
359   return ObjectPtr();
360 }
361
362 const int Model_Objects::index(std::shared_ptr<ModelAPI_Object> theObject)
363 {
364   std::string aGroup = theObject->groupName();
365   createHistory(aGroup);
366   std::vector<ObjectPtr>& allObjs = myHistory[aGroup];
367   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin(); // iterate to search object
368   for(int anIndex = 0; anObjIter != allObjs.end(); anObjIter++, anIndex++) {
369     if ((*anObjIter) == theObject)
370       return anIndex;
371   }
372   // not found
373   return -1;
374 }
375
376 int Model_Objects::size(const std::string& theGroupID)
377 {
378   createHistory(theGroupID);
379   return myHistory[theGroupID].size();
380 }
381
382 void Model_Objects::allResults(const std::string& theGroupID, std::list<ResultPtr>& theResults)
383 {
384   // iterate the array of references and get feature by feature from the array
385   Handle(TDataStd_ReferenceArray) aRefs;
386   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
387     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
388       FeaturePtr aFeature = feature(aRefs->Value(a));
389       if (aFeature.get()) {
390         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
391         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
392         for (; aRIter != aResults.cend(); aRIter++) {
393           ResultPtr aRes = *aRIter;
394           if (aRes->groupName() != theGroupID) break; // feature have only same group results
395           if (aRes->isInHistory() && !aRes->isConcealed()) {
396             theResults.push_back(*aRIter);
397           }
398         }
399       }
400     }
401   }
402 }
403
404
405 TDF_Label Model_Objects::featuresLabel() const
406 {
407   return myMain.FindChild(TAG_OBJECTS);
408 }
409
410 void Model_Objects::setUniqueName(FeaturePtr theFeature)
411 {
412   if (!theFeature->data()->name().empty())
413     return;  // not needed, name is already defined
414   std::string aName;  // result
415   // first count all features of such kind to start with index = count + 1
416   int aNumObjects = 0;
417   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
418   for (; aFIter.More(); aFIter.Next()) {
419     if (aFIter.Value()->getKind() == theFeature->getKind())
420       aNumObjects++;
421   }
422   // generate candidate name
423   std::stringstream aNameStream;
424   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
425   aName = aNameStream.str();
426   // check this is unique, if not, increase index by 1
427   for (aFIter.Initialize(myFeatures); aFIter.More();) {
428     FeaturePtr aFeature = aFIter.Value();
429     bool isSameName = aFeature->data()->name() == aName;
430     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
431       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
432       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
433       for (; aRIter != aResults.cend(); aRIter++) {
434         isSameName = (*aRIter)->data()->name() == aName;
435       }
436     }
437     if (isSameName) {
438       aNumObjects++;
439       std::stringstream aNameStream;
440       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
441       aName = aNameStream.str();
442       // reinitialize iterator to make sure a new name is unique
443       aFIter.Initialize(myFeatures);
444     } else
445       aFIter.Next();
446   }
447   theFeature->data()->setName(aName);
448 }
449
450 void Model_Objects::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
451 {
452   std::shared_ptr<Model_Data> aData(new Model_Data);
453   aData->setLabel(theLab.FindChild(theTag));
454   aData->setObject(theObj);
455   theObj->setDoc(myDoc);
456   theObj->setData(aData);
457   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
458   if (aFeature) {
459     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
460   }
461   theObj->initAttributes();
462 }
463
464 void Model_Objects::synchronizeFeatures(
465   const bool theMarkUpdated, const bool theUpdateReferences, const bool theFlush)
466 {
467   Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
468   if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
469     return;
470   // after all updates, sends a message that groups of features were created or updated
471   Events_Loop* aLoop = Events_Loop::loop();
472   static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
473   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
474   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
475   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
476   static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
477   static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
478   bool isActive = aLoop->activateFlushes(false);
479
480   // update all objects by checking are they on labels or not
481   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
482   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
483   for (; aLabIter.More(); aLabIter.Next()) {
484     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
485     FeaturePtr aFeature;
486     if (!myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
487       // create a feature
488       aFeature = std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get())->createFeature(
489         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
490         .ToCString(), anOwner);
491       if (!aFeature) {  // somethig is wrong, most probably, the opened document has invalid structure
492         Events_Error::send("Invalid type of object in the document");
493         aLabIter.Value()->Label().ForgetAllAttributes();
494         continue;
495       }
496       // this must be before "setData" to redo the sketch line correctly
497       myFeatures.Bind(aFeatureLabel, aFeature);
498       aNewFeatures.insert(aFeature);
499       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
500       updateHistory(aFeature);
501       aFeature->setDisabled(false); // by default created feature is enabled (this allows to recreate the results before "setCurrent" is called)
502
503       // event: model is updated
504       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
505     } else {  // nothing is changed, both iterators are incremented
506       aFeature = myFeatures.Find(aFeatureLabel);
507       aKeptFeatures.insert(aFeature);
508       if (theMarkUpdated) {
509         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anUpdateEvent);
510       }
511     }
512   }
513   // update results of the features (after features created because they may be connected, like sketch and sub elements)
514   std::list<FeaturePtr> aComposites; // composites must be updated after their subs (issue 360)
515   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
516   for (; aLabIter2.More(); aLabIter2.Next()) {
517     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
518     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
519       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
520       if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature).get())
521         aComposites.push_back(aFeature);
522       updateResults(aFeature);
523     }
524   }
525   std::list<FeaturePtr>::iterator aComposite = aComposites.begin();
526   for(; aComposite != aComposites.end(); aComposite++) {
527     updateResults(*aComposite);
528   }
529
530   // check all features are checked: if not => it was removed
531   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
532   while (aFIter.More()) {
533     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
534       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
535         FeaturePtr aFeature = aFIter.Value();
536         // event: model is updated
537         //if (aFeature->isInHistory()) {
538         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
539         //}
540         // results of this feature must be redisplayed (hided)
541         // redisplay also removed feature (used for sketch and AISObject)
542         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
543         updateHistory(aFeature);
544         aFeature->erase();
545         // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
546         myFeatures.UnBind(aFIter.Key());
547         // reinitialize iterator because unbind may corrupt the previous order in the map
548         aFIter.Initialize(myFeatures);
549     } else
550       aFIter.Next();
551   }
552
553   if (theUpdateReferences) {
554     synchronizeBackRefs();
555   }
556   if (theMarkUpdated) { // this means there is no control what was modified => remove history cash
557     myHistory.clear();
558   }
559
560   anOwner->executeFeatures() = false;
561   aLoop->activateFlushes(isActive);
562
563   if (theFlush) {
564     aLoop->flush(aCreateEvent);
565     aLoop->flush(aDeleteEvent);
566     aLoop->flush(anUpdateEvent);
567     aLoop->flush(aRedispEvent);
568     aLoop->flush(aToHideEvent);
569   }
570   anOwner->executeFeatures() = true;
571 }
572
573 void Model_Objects::synchronizeBackRefs()
574 {
575   // keeps the concealed flags of result to catch the change and create created/deleted events
576   std::list<std::pair<ResultPtr, bool> > aConcealed;
577   // first cycle: erase all data about back-references
578   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
579   for(; aFeatures.More(); aFeatures.Next()) {
580     FeaturePtr aFeature = aFeatures.Value();
581     std::shared_ptr<Model_Data> aFData = 
582       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
583     if (aFData) {
584       aFData->eraseBackReferences();
585     }
586     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
587     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
588     for (; aRIter != aResults.cend(); aRIter++) {
589       std::shared_ptr<Model_Data> aResData = 
590         std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
591       if (aResData) {
592         aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
593         aResData->eraseBackReferences();
594       }
595     }
596   }
597
598   // second cycle: set new back-references: only features may have reference, iterate only them
599   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
600   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
601     FeaturePtr aFeature = aFeatures.Value();
602     std::shared_ptr<Model_Data> aFData = 
603       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
604     if (aFData) {
605       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
606       aFData->referencesToObjects(aRefs);
607       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator 
608         aRefsIter = aRefs.begin();
609       for(; aRefsIter != aRefs.end(); aRefsIter++) {
610         std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
611         for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
612           if (*aRefTo) {
613             std::shared_ptr<Model_Data> aRefData = 
614               std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
615             aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
616             // update enable/disable status: the nested status must be equal to the composite
617             CompositeFeaturePtr aComp = 
618               std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
619             if (aComp.get()) {
620               FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>(*aRefTo);
621               if (aReferenced.get()) {
622                 aReferenced->setDisabled(aComp->isDisabled());
623               }
624             }
625           }
626         }
627       }
628     }
629   }
630   std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
631   for(; aCIter != aConcealed.end(); aCIter++) {
632     if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
633       if (aCIter->second) { // was concealed become not => creation event
634         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
635         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
636       } else { // was not concealed become concealed => delete event
637         ModelAPI_EventCreator::get()->sendDeleted(myDoc, aCIter->first->groupName());
638         // redisplay for the viewer (it must be disappeared also)
639         static Events_ID EVENT_DISP = 
640           Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
641         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
642       }
643     }
644   }
645 }
646
647 TDF_Label Model_Objects::resultLabel(
648   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
649 {
650   const std::shared_ptr<Model_Data>& aData = 
651     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
652   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
653 }
654
655 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
656                                  std::shared_ptr<ModelAPI_Result> theResult,
657                                  const int theResultIndex)
658 {
659   theResult->setDoc(myDoc);
660   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
661   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
662     std::stringstream aNewName;
663     aNewName<<theFeatureData->name();
664     if (theResultIndex > 0) // if there are several results, add unique prefix starting from second
665       aNewName<<"_"<<theResultIndex + 1;
666     theResult->data()->setName(aNewName.str());
667   }
668 }
669
670 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
671     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
672 {
673   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
674   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
675   ObjectPtr anOldObject = object(aLab);
676   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
677   if (anOldObject) {
678     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
679   }
680   if (!aResult) {
681     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
682     storeResult(theFeatureData, aResult, theIndex);
683   }
684   return aResult;
685 }
686
687 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
688     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
689 {
690   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
691   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
692   ObjectPtr anOldObject = object(aLab);
693   std::shared_ptr<ModelAPI_ResultBody> aResult;
694   if (anOldObject) {
695     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
696   }
697   if (!aResult) {
698     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
699     storeResult(theFeatureData, aResult, theIndex);
700   }
701   return aResult;
702 }
703
704 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
705     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
706 {
707   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
708   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
709   ObjectPtr anOldObject = object(aLab);
710   std::shared_ptr<ModelAPI_ResultPart> aResult;
711   if (anOldObject) {
712     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
713   }
714   if (!aResult) {
715     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
716     storeResult(theFeatureData, aResult, theIndex);
717   }
718   return aResult;
719 }
720
721 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
722     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
723 {
724   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
725   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
726   ObjectPtr anOldObject = object(aLab);
727   std::shared_ptr<ModelAPI_ResultGroup> aResult;
728   if (anOldObject) {
729     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
730   }
731   if (!aResult) {
732     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
733     storeResult(theFeatureData, aResult, theIndex);
734   }
735   return aResult;
736 }
737
738 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
739       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
740 {
741   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
742   TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
743   ObjectPtr anOldObject = object(aLab);
744   std::shared_ptr<ModelAPI_ResultParameter> aResult;
745   if (anOldObject) {
746     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
747   }
748   if (!aResult) {
749     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
750     storeResult(theFeatureData, aResult, theIndex);
751   }
752   return aResult;
753 }
754
755 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
756     const std::shared_ptr<ModelAPI_Result>& theResult)
757 {
758   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
759   if (aData) {
760     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
761     return feature(aFeatureLab);
762   }
763   return FeaturePtr();
764 }
765
766 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
767 {
768   if (theFeature->data()->isValid()) {
769     TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
770     if (aLabIter.More()) {
771       TDF_Label anArgLab = aLabIter.Value();
772       Handle(TDataStd_Comment) aGroup;
773       if (aLabIter.Value().FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
774         return TCollection_AsciiString(aGroup->Get()).ToCString();
775       }
776     }
777   }
778   static std::string anEmpty;
779   return anEmpty; // not found
780 }
781
782 void Model_Objects::updateResults(FeaturePtr theFeature)
783 {
784   // for not persistent is will be done by parametric updater automatically
785   //if (!theFeature->isPersistentResult()) return;
786   // check the existing results and remove them if there is nothing on the label
787   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
788   while(aResIter != theFeature->results().cend()) {
789     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
790     if (aBody.get()) {
791       if (!aBody->data()->isValid()) { 
792         // found a disappeared result => remove it
793         theFeature->eraseResultFromList(aBody);
794         // start iterate from beginning because iterator is corrupted by removing
795         aResIter = theFeature->results().cbegin();
796         continue;
797       }
798     }
799     aResIter++;
800   }
801   // it may be on undo
802   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
803     return;
804   // check that results are presented on all labels
805   int aResSize = theFeature->results().size();
806   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
807   for(; aLabIter.More(); aLabIter.Next()) {
808     // here must be GUID of the feature
809     int aResIndex = aLabIter.Value().Tag() - 1;
810     ResultPtr aNewBody;
811     if (aResSize <= aResIndex) {
812       TDF_Label anArgLab = aLabIter.Value();
813       Handle(TDataStd_Comment) aGroup;
814       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
815         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
816           aNewBody = createBody(theFeature->data(), aResIndex);
817         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
818           std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex); 
819           theFeature->setResult(aNewP, aResIndex);
820           if (!aNewP->partDoc().get())
821             theFeature->execute(); // create the part result: it is better to restore the previous result if it is possible
822           break;
823         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
824           theFeature->execute(); // construction shapes are needed for sketch solver
825           break;
826         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
827           aNewBody = createGroup(theFeature->data(), aResIndex);
828         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
829           theFeature->attributeChanged("expression"); // just produce a value
830           break;
831         } else {
832           Events_Error::send(std::string("Unknown type of result is found in the document:") +
833             TCollection_AsciiString(aGroup->Get()).ToCString());
834         }
835       }
836       if (aNewBody) {
837         theFeature->setResult(aNewBody, aResIndex);
838       }
839     }
840   }
841 }
842
843 ResultPtr Model_Objects::findByName(const std::string theName)
844 {
845   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
846   for(; anObjIter.More(); anObjIter.Next()) {
847     FeaturePtr& aFeature = anObjIter.ChangeValue();
848     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
849       continue;
850     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
851     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
852     for (; aRIter != aResults.cend(); aRIter++) {
853       ResultPtr aRes = *aRIter;
854       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
855           aRes->data()->name() == theName) {
856         return aRes;
857       }
858     }
859   }
860   // not found
861   return ResultPtr();
862 }
863
864 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, const bool theReverse)
865 {
866   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
867   if (aData && aData->isValid()) {
868     TDF_Label aFeatureLabel = aData->label().Father();
869     Handle(TDataStd_ReferenceArray) aRefs;
870     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
871       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
872         if (aRefs->Value(a).IsEqual(aFeatureLabel)) {
873           a += theReverse ? -1 : 1;
874           if (a >= aRefs->Lower() && a <= aRefs->Upper())
875             return feature(aRefs->Value(a));
876           break; // finish iiteration: it's last feature
877         }
878       }
879     }
880   }
881   return FeaturePtr(); // not found, last, or something is wrong
882 }
883
884 FeaturePtr Model_Objects::firstFeature()
885 {
886   Handle(TDataStd_ReferenceArray) aRefs;
887   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
888     return feature(aRefs->Value(aRefs->Lower()));
889   }
890   return FeaturePtr(); // no features at all
891 }
892
893 FeaturePtr Model_Objects::lastFeature()
894 {
895   Handle(TDataStd_ReferenceArray) aRefs;
896   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
897     return feature(aRefs->Value(aRefs->Upper()));
898   }
899   return FeaturePtr(); // no features at all
900 }
901
902 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
903 {
904   std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
905   Handle(TDataStd_ReferenceArray) aRefs;
906   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
907     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
908       FeaturePtr aFeature = feature(aRefs->Value(a));
909       if (aFeature.get())
910         aResult.push_back(aFeature);
911     }
912   }
913   return aResult;
914 }
915
916 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
917 {
918   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
919
920 }
921 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
922 {
923   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
924 }