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