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