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