Salome HOME
Make the movement, placement and rotation 3D features may be applied to the Part...
[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::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
247 {
248   TDF_Label aFeaturesLab = featuresLabel();
249   Handle(TDataStd_ReferenceArray) aRefs;
250   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
251     return;
252   TDF_Label anAfterLab, aMovedLab = 
253     std::dynamic_pointer_cast<Model_Data>(theMoved->data())->label().Father();
254   if (theAfterThis.get())
255     anAfterLab = std::dynamic_pointer_cast<Model_Data>(theAfterThis->data())->label().Father();
256
257   Handle(TDataStd_HLabelArray1) aNewArray = 
258     new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper());
259   int aPassedMovedFrom = 0; // the prev feature location is found and passed
260   int aPassedMovedTo = 0; // the feature is added and this location is passed
261   if (!theAfterThis.get()) { // null means that inserted feature must be the first
262     aNewArray->SetValue(aRefs->Lower(), aMovedLab);
263     aPassedMovedTo = 1;
264   }
265   for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
266     if (aPassedMovedTo == 0 && aRefs->Value(a) == anAfterLab) { // add two
267       aPassedMovedTo++;
268       aNewArray->SetValue(a - aPassedMovedFrom, anAfterLab);
269       if (a + 1 - aPassedMovedFrom <= aRefs->Upper())
270         aNewArray->SetValue(a + 1 - aPassedMovedFrom, aMovedLab);
271     } else if (aPassedMovedFrom == 0 && aRefs->Value(a) == aMovedLab) { // skip
272       aPassedMovedFrom++;
273     } else { // just copy one
274       if (a - aPassedMovedFrom + aPassedMovedTo <= aRefs->Upper())
275         aNewArray->SetValue(a - aPassedMovedFrom + aPassedMovedTo, aRefs->Value(a));
276     }
277   }
278   if (!aPassedMovedFrom || !aPassedMovedTo) {// not found: unknown situation
279     if (!aPassedMovedFrom) {
280       static std::string aMovedFromError("The moved feature is not found");
281       Events_Error::send(aMovedFromError);
282     } else {
283       static std::string aMovedToError("The 'after' feature for movement is not found");
284       Events_Error::send(aMovedToError);
285     }
286     return;
287   }
288   // store the new array
289   aRefs->SetInternalArray(aNewArray);
290   // update the feature and the history
291   clearHistory(theMoved);
292   static Events_ID EVENT_UPD = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
293   ModelAPI_EventCreator::get()->sendUpdated(theMoved, EVENT_UPD);
294 }
295
296 void Model_Objects::clearHistory(ObjectPtr theObj)
297 {
298   if (theObj) {
299     const std::string aGroup = theObj->groupName();
300     std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(aGroup);
301     if (aHIter != myHistory.end())
302       myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
303     if (theObj->groupName() == ModelAPI_Feature::group()) { // clear results group of the feature
304       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
305       std::string aResultGroup = featureResultGroup(aFeature);
306       if (!aResultGroup.empty()) {
307         std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = 
308           myHistory.find(aResultGroup);
309         if (aHIter != myHistory.end())
310           myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
311       }
312     }
313   }
314 }
315
316 void Model_Objects::createHistory(const std::string& theGroupID)
317 {
318   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroupID);
319   if (aHIter == myHistory.end()) {
320     myHistory[theGroupID] = std::vector<ObjectPtr>();
321     std::vector<ObjectPtr>& aResult = myHistory[theGroupID];
322     // iterate the array of references and get feature by feature from the array
323     bool isFeature = theGroupID == ModelAPI_Feature::group();
324     Handle(TDataStd_ReferenceArray) aRefs;
325     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
326       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
327         FeaturePtr aFeature = feature(aRefs->Value(a));
328         if (aFeature.get()) {
329           if (isFeature) { // here may be also disabled features
330             if (aFeature->isInHistory()) {
331               aResult.push_back(aFeature);
332             }
333           } else if (!aFeature->isDisabled()) { // iterate all results of not-disabled feature
334             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
335             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
336             for (; aRIter != aResults.cend(); aRIter++) {
337               ResultPtr aRes = *aRIter;
338               if (aRes->groupName() != theGroupID) break; // feature have only same group results
339               if (!aRes->isDisabled() && aRes->isInHistory() && !aRes->isConcealed()) {
340                 aResult.push_back(*aRIter);
341               }
342             }
343           }
344         }
345       }
346     }
347   }
348 }
349
350 void Model_Objects::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
351 {
352   clearHistory(theObject);
353 }
354
355 void Model_Objects::updateHistory(const std::string theGroup)
356 {
357   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroup);
358   if (aHIter != myHistory.end())
359     myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
360 }
361
362 FeaturePtr Model_Objects::feature(TDF_Label theLabel) const
363 {
364   if (myFeatures.IsBound(theLabel))
365     return myFeatures.Find(theLabel);
366   return FeaturePtr();  // not found
367 }
368
369 ObjectPtr Model_Objects::object(TDF_Label theLabel)
370 {
371   // try feature by label
372   FeaturePtr aFeature = feature(theLabel);
373   if (aFeature)
374     return feature(theLabel);
375   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
376   aFeature = feature(aFeatureLabel);
377   if (aFeature) {
378     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
379     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
380     for (; aRIter != aResults.cend(); aRIter++) {
381       std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
382           (*aRIter)->data());
383       if (aResData->label().Father().IsEqual(theLabel))
384         return *aRIter;
385     }
386   }
387   return FeaturePtr();  // not found
388 }
389
390 ObjectPtr Model_Objects::object(const std::string& theGroupID, const int theIndex)
391 {
392   if (theIndex == -1)
393     return ObjectPtr();
394   createHistory(theGroupID);
395   return myHistory[theGroupID][theIndex];
396 }
397
398 std::shared_ptr<ModelAPI_Object> Model_Objects::objectByName(
399     const std::string& theGroupID, const std::string& theName)
400 {
401   createHistory(theGroupID);
402   std::vector<ObjectPtr>& allObjs = myHistory[theGroupID];
403   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin();
404   for(; anObjIter != allObjs.end(); anObjIter++) {
405     if ((*anObjIter)->data()->name() == theName)
406       return *anObjIter;
407   }
408   // not found
409   return ObjectPtr();
410 }
411
412 const int Model_Objects::index(std::shared_ptr<ModelAPI_Object> theObject)
413 {
414   std::string aGroup = theObject->groupName();
415   createHistory(aGroup);
416   std::vector<ObjectPtr>& allObjs = myHistory[aGroup];
417   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin(); // iterate to search object
418   for(int anIndex = 0; anObjIter != allObjs.end(); anObjIter++, anIndex++) {
419     if ((*anObjIter) == theObject)
420       return anIndex;
421   }
422   // not found
423   return -1;
424 }
425
426 int Model_Objects::size(const std::string& theGroupID)
427 {
428   createHistory(theGroupID);
429   return myHistory[theGroupID].size();
430 }
431
432 void Model_Objects::allResults(const std::string& theGroupID, std::list<ResultPtr>& theResults)
433 {
434   // iterate the array of references and get feature by feature from the array
435   Handle(TDataStd_ReferenceArray) aRefs;
436   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
437     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
438       FeaturePtr aFeature = feature(aRefs->Value(a));
439       if (aFeature.get()) {
440         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
441         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
442         for (; aRIter != aResults.cend(); aRIter++) {
443           ResultPtr aRes = *aRIter;
444           if (aRes->groupName() != theGroupID) break; // feature have only same group results
445           if (aRes->isInHistory() && !aRes->isConcealed()) {
446             theResults.push_back(*aRIter);
447           }
448         }
449       }
450     }
451   }
452 }
453
454
455 TDF_Label Model_Objects::featuresLabel() const
456 {
457   return myMain.FindChild(TAG_OBJECTS);
458 }
459
460 void Model_Objects::setUniqueName(FeaturePtr theFeature)
461 {
462   if (!theFeature->data()->name().empty())
463     return;  // not needed, name is already defined
464   std::string aName;  // result
465   // first count all features of such kind to start with index = count + 1
466   int aNumObjects = 0;
467   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
468   for (; aFIter.More(); aFIter.Next()) {
469     if (aFIter.Value()->getKind() == theFeature->getKind())
470       aNumObjects++;
471   }
472   // generate candidate name
473   std::stringstream aNameStream;
474   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
475   aName = aNameStream.str();
476   // check this is unique, if not, increase index by 1
477   for (aFIter.Initialize(myFeatures); aFIter.More();) {
478     FeaturePtr aFeature = aFIter.Value();
479     bool isSameName = aFeature->data()->name() == aName;
480     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
481       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
482       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
483       for (; aRIter != aResults.cend(); aRIter++) {
484         isSameName = (*aRIter)->data()->name() == aName;
485       }
486     }
487     if (isSameName) {
488       aNumObjects++;
489       std::stringstream aNameStream;
490       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
491       aName = aNameStream.str();
492       // reinitialize iterator to make sure a new name is unique
493       aFIter.Initialize(myFeatures);
494     } else
495       aFIter.Next();
496   }
497   theFeature->data()->setName(aName);
498 }
499
500 void Model_Objects::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
501 {
502   std::shared_ptr<Model_Data> aData(new Model_Data);
503   aData->setLabel(theLab.FindChild(theTag));
504   aData->setObject(theObj);
505   theObj->setDoc(myDoc);
506   theObj->setData(aData);
507   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
508   if (aFeature) {
509     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
510   }
511   theObj->initAttributes();
512 }
513
514 void Model_Objects::synchronizeFeatures(
515   const bool theMarkUpdated, const bool theUpdateReferences, const bool theFlush)
516 {
517   Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
518   if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
519     return;
520   // after all updates, sends a message that groups of features were created or updated
521   Events_Loop* aLoop = Events_Loop::loop();
522   static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
523   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
524   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
525   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
526   static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
527   static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
528   bool isActive = aLoop->activateFlushes(false);
529
530   // update all objects by checking are they on labels or not
531   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
532   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
533   for (; aLabIter.More(); aLabIter.Next()) {
534     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
535     FeaturePtr aFeature;
536     if (!myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
537       // create a feature
538       aFeature = std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get())->createFeature(
539         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
540         .ToCString(), anOwner);
541       if (!aFeature) {  // somethig is wrong, most probably, the opened document has invalid structure
542         Events_Error::send("Invalid type of object in the document");
543         aLabIter.Value()->Label().ForgetAllAttributes();
544         continue;
545       }
546       // this must be before "setData" to redo the sketch line correctly
547       myFeatures.Bind(aFeatureLabel, aFeature);
548       aNewFeatures.insert(aFeature);
549       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
550       updateHistory(aFeature);
551       aFeature->setDisabled(false); // by default created feature is enabled (this allows to recreate the results before "setCurrent" is called)
552
553       // event: model is updated
554       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
555     } else {  // nothing is changed, both iterators are incremented
556       aFeature = myFeatures.Find(aFeatureLabel);
557       aKeptFeatures.insert(aFeature);
558       if (theMarkUpdated) {
559         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anUpdateEvent);
560       }
561     }
562   }
563
564   // check all features are checked: if not => it was removed
565   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
566   while (aFIter.More()) {
567     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
568       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
569         FeaturePtr aFeature = aFIter.Value();
570         // event: model is updated
571         //if (aFeature->isInHistory()) {
572         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
573         //}
574         // results of this feature must be redisplayed (hided)
575         // redisplay also removed feature (used for sketch and AISObject)
576         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
577         updateHistory(aFeature);
578         aFeature->erase();
579         // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
580         myFeatures.UnBind(aFIter.Key());
581         // reinitialize iterator because unbind may corrupt the previous order in the map
582         aFIter.Initialize(myFeatures);
583     } else
584       aFIter.Next();
585   }
586
587   if (theUpdateReferences) {
588     synchronizeBackRefs();
589   }
590   // update results of the features (after features created because they may be connected, like sketch and sub elements)
591   // After synchronisation of back references because sketch must be set in sub-elements before "execute" by updateResults
592   std::list<FeaturePtr> aComposites; // composites must be updated after their subs (issue 360)
593   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
594   for (; aLabIter2.More(); aLabIter2.Next()) {
595     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
596     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
597       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
598       if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature).get())
599         aComposites.push_back(aFeature);
600       updateResults(aFeature);
601     }
602   }
603   std::list<FeaturePtr>::iterator aComposite = aComposites.begin();
604   for(; aComposite != aComposites.end(); aComposite++) {
605     updateResults(*aComposite);
606   }
607
608   // the synchronize should be done after updateResults in order to correct back references of updated results
609   if (theUpdateReferences) {
610     synchronizeBackRefs();
611   }
612   if (theMarkUpdated) { // this means there is no control what was modified => remove history cash
613     myHistory.clear();
614   }
615
616   anOwner->executeFeatures() = false;
617   aLoop->activateFlushes(isActive);
618
619   if (theFlush) {
620     aLoop->flush(aCreateEvent);
621     aLoop->flush(aDeleteEvent);
622     aLoop->flush(anUpdateEvent);
623     aLoop->flush(aRedispEvent);
624     aLoop->flush(aToHideEvent);
625   }
626   anOwner->executeFeatures() = true;
627 }
628
629 void Model_Objects::synchronizeBackRefs()
630 {
631   // keeps the concealed flags of result to catch the change and create created/deleted events
632   std::list<std::pair<ResultPtr, bool> > aConcealed;
633   // first cycle: erase all data about back-references
634   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
635   for(; aFeatures.More(); aFeatures.Next()) {
636     FeaturePtr aFeature = aFeatures.Value();
637     std::shared_ptr<Model_Data> aFData = 
638       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
639     if (aFData) {
640       aFData->eraseBackReferences();
641     }
642     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
643     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
644     for (; aRIter != aResults.cend(); aRIter++) {
645       std::shared_ptr<Model_Data> aResData = 
646         std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
647       if (aResData) {
648         aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
649         aResData->eraseBackReferences();
650       }
651     }
652   }
653
654   // second cycle: set new back-references: only features may have reference, iterate only them
655   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
656   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
657     FeaturePtr aFeature = aFeatures.Value();
658     std::shared_ptr<Model_Data> aFData = 
659       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
660     if (aFData) {
661       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
662       aFData->referencesToObjects(aRefs);
663       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator 
664         aRefsIter = aRefs.begin();
665       for(; aRefsIter != aRefs.end(); aRefsIter++) {
666         std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
667         for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
668           if (*aRefTo) {
669             std::shared_ptr<Model_Data> aRefData = 
670               std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
671             aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
672             // update enable/disable status: the nested status must be equal to the composite
673             CompositeFeaturePtr aComp = 
674               std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
675             if (aComp.get()) {
676               FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>(*aRefTo);
677               if (aReferenced.get()) {
678                 aReferenced->setDisabled(aComp->isDisabled());
679               }
680             }
681           }
682         }
683       }
684     }
685   }
686   std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
687   for(; aCIter != aConcealed.end(); aCIter++) {
688     if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
689       if (aCIter->second) { // was concealed become not => creation event
690         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
691         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
692       } else { // was not concealed become concealed => delete event
693         ModelAPI_EventCreator::get()->sendDeleted(myDoc, aCIter->first->groupName());
694         // redisplay for the viewer (it must be disappeared also)
695         static Events_ID EVENT_DISP = 
696           Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
697         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
698       }
699     }
700   }
701 }
702
703 TDF_Label Model_Objects::resultLabel(
704   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
705 {
706   const std::shared_ptr<Model_Data>& aData = 
707     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
708   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
709 }
710
711 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
712                                  std::shared_ptr<ModelAPI_Result> theResult,
713                                  const int theResultIndex)
714 {
715   theResult->setDoc(myDoc);
716   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
717   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
718     std::stringstream aNewName;
719     aNewName<<theFeatureData->name();
720     if (theResultIndex > 0) // if there are several results, add unique prefix starting from second
721       aNewName<<"_"<<theResultIndex + 1;
722     theResult->data()->setName(aNewName.str());
723   }
724 }
725
726 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
727     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
728 {
729   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
730   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
731   ObjectPtr anOldObject = object(aLab);
732   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
733   if (anOldObject) {
734     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
735   }
736   if (!aResult) {
737     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
738     storeResult(theFeatureData, aResult, theIndex);
739   }
740   return aResult;
741 }
742
743 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
744     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
745 {
746   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
747   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
748   ObjectPtr anOldObject = object(aLab);
749   std::shared_ptr<ModelAPI_ResultBody> aResult;
750   if (anOldObject) {
751     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
752   }
753   if (!aResult) {
754     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
755     storeResult(theFeatureData, aResult, theIndex);
756   }
757   return aResult;
758 }
759
760 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
761     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
762 {
763   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
764   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
765   ObjectPtr anOldObject = object(aLab);
766   std::shared_ptr<ModelAPI_ResultPart> aResult;
767   if (anOldObject) {
768     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
769   }
770   if (!aResult) {
771     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
772     storeResult(theFeatureData, aResult, theIndex);
773   }
774   return aResult;
775 }
776
777 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
778     const std::shared_ptr<ModelAPI_Result>& theOldPart, 
779     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin, const int theIndex)
780 {
781   std::shared_ptr<ModelAPI_ResultPart> aResult;
782   if (theOldPart.get()) {
783     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theOldPart);
784   }
785   if (!aResult) {
786     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
787     aResult->setDoc(myDoc);
788     aResult->setData(theOrigin->data());
789   }
790   return aResult;
791 }
792
793 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
794     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
795 {
796   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
797   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
798   ObjectPtr anOldObject = object(aLab);
799   std::shared_ptr<ModelAPI_ResultGroup> aResult;
800   if (anOldObject) {
801     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
802   }
803   if (!aResult) {
804     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
805     storeResult(theFeatureData, aResult, theIndex);
806   }
807   return aResult;
808 }
809
810 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
811       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
812 {
813   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
814   TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
815   ObjectPtr anOldObject = object(aLab);
816   std::shared_ptr<ModelAPI_ResultParameter> aResult;
817   if (anOldObject) {
818     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
819   }
820   if (!aResult) {
821     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
822     storeResult(theFeatureData, aResult, theIndex);
823   }
824   return aResult;
825 }
826
827 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
828     const std::shared_ptr<ModelAPI_Result>& theResult)
829 {
830   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
831   if (aData) {
832     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
833     return feature(aFeatureLab);
834   }
835   return FeaturePtr();
836 }
837
838 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
839 {
840   if (theFeature->data()->isValid()) {
841     TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
842     if (aLabIter.More()) {
843       TDF_Label anArgLab = aLabIter.Value();
844       Handle(TDataStd_Comment) aGroup;
845       if (aLabIter.Value().FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
846         return TCollection_AsciiString(aGroup->Get()).ToCString();
847       }
848     }
849   }
850   static std::string anEmpty;
851   return anEmpty; // not found
852 }
853
854 void Model_Objects::updateResults(FeaturePtr theFeature)
855 {
856   // for not persistent is will be done by parametric updater automatically
857   //if (!theFeature->isPersistentResult()) return;
858   // check the existing results and remove them if there is nothing on the label
859   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
860   while(aResIter != theFeature->results().cend()) {
861     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
862     if (aBody.get()) {
863       if (!aBody->data()->isValid()) { 
864         // found a disappeared result => remove it
865         theFeature->eraseResultFromList(aBody);
866         // start iterate from beginning because iterator is corrupted by removing
867         aResIter = theFeature->results().cbegin();
868         continue;
869       }
870     }
871     aResIter++;
872   }
873   // it may be on undo
874   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
875     return;
876   // check that results are presented on all labels
877   int aResSize = theFeature->results().size();
878   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
879   for(; aLabIter.More(); aLabIter.Next()) {
880     // here must be GUID of the feature
881     int aResIndex = aLabIter.Value().Tag() - 1;
882     ResultPtr aNewBody;
883     if (aResSize <= aResIndex) {
884       TDF_Label anArgLab = aLabIter.Value();
885       Handle(TDataStd_Comment) aGroup;
886       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
887         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
888           aNewBody = createBody(theFeature->data(), aResIndex);
889         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
890           std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex); 
891           theFeature->setResult(aNewP, aResIndex);
892           if (!aNewP->partDoc().get())
893             theFeature->execute(); // create the part result: it is better to restore the previous result if it is possible
894           break;
895         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
896           theFeature->execute(); // construction shapes are needed for sketch solver
897           break;
898         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
899           aNewBody = createGroup(theFeature->data(), aResIndex);
900         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
901           theFeature->attributeChanged("expression"); // just produce a value
902           break;
903         } else {
904           Events_Error::send(std::string("Unknown type of result is found in the document:") +
905             TCollection_AsciiString(aGroup->Get()).ToCString());
906         }
907       }
908       if (aNewBody) {
909         theFeature->setResult(aNewBody, aResIndex);
910       }
911     }
912   }
913 }
914
915 ResultPtr Model_Objects::findByName(const std::string theName)
916 {
917   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
918   for(; anObjIter.More(); anObjIter.Next()) {
919     FeaturePtr& aFeature = anObjIter.ChangeValue();
920     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
921       continue;
922     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
923     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
924     for (; aRIter != aResults.cend(); aRIter++) {
925       ResultPtr aRes = *aRIter;
926       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
927           aRes->data()->name() == theName) {
928         return aRes;
929       }
930     }
931   }
932   // not found
933   return ResultPtr();
934 }
935
936 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, const bool theReverse)
937 {
938   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
939   if (aData && aData->isValid()) {
940     TDF_Label aFeatureLabel = aData->label().Father();
941     Handle(TDataStd_ReferenceArray) aRefs;
942     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
943       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
944         if (aRefs->Value(a).IsEqual(aFeatureLabel)) {
945           a += theReverse ? -1 : 1;
946           if (a >= aRefs->Lower() && a <= aRefs->Upper())
947             return feature(aRefs->Value(a));
948           break; // finish iiteration: it's last feature
949         }
950       }
951     }
952   }
953   return FeaturePtr(); // not found, last, or something is wrong
954 }
955
956 FeaturePtr Model_Objects::firstFeature()
957 {
958   Handle(TDataStd_ReferenceArray) aRefs;
959   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
960     return feature(aRefs->Value(aRefs->Lower()));
961   }
962   return FeaturePtr(); // no features at all
963 }
964
965 FeaturePtr Model_Objects::lastFeature()
966 {
967   Handle(TDataStd_ReferenceArray) aRefs;
968   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
969     return feature(aRefs->Value(aRefs->Upper()));
970   }
971   return FeaturePtr(); // no features at all
972 }
973
974 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
975 {
976   std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
977   Handle(TDataStd_ReferenceArray) aRefs;
978   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
979     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
980       FeaturePtr aFeature = feature(aRefs->Value(a));
981       if (aFeature.get())
982         aResult.push_back(aFeature);
983     }
984   }
985   return aResult;
986 }
987
988 int Model_Objects::numInternalFeatures()
989 {
990   Handle(TDataStd_ReferenceArray) aRefs;
991   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
992     return aRefs->Upper() - aRefs->Lower() + 1;
993   }
994   return 0; // invalid
995 }
996
997 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
998 {
999   Handle(TDataStd_ReferenceArray) aRefs;
1000   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1001     return feature(aRefs->Value(aRefs->Lower() + theIndex));
1002   }
1003   return FeaturePtr(); // invalid
1004 }
1005
1006 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1007 {
1008   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1009
1010 }
1011 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1012 {
1013   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1014 }