Salome HOME
Merge branch 'Dev_1.2.0' of newgeom:newgeom into Dev_1.2.0
[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   }
130 }
131
132 /// Appends to the array of references a new referenced label.
133 /// If theIndex is not -1, removes element at this index, not theReferenced.
134 /// \returns the index of removed element
135 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, 
136   const int theIndex = -1)
137 {
138   int aResult = -1;  // no returned
139   Handle(TDataStd_ReferenceArray) aRefs;
140   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
141     if (aRefs->Length() == 1) {  // just erase an array
142       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
143         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
144       }
145       aResult = 0;
146     } else {  // reduce the array
147       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
148                                                                           aRefs->Upper() - 1);
149       int aCount = aRefs->Lower();
150       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
151         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
152           aCount--;
153           aResult = a;
154         } else {
155           aNewArray->SetValue(aCount, aRefs->Value(a));
156         }
157       }
158       aRefs->SetInternalArray(aNewArray);
159     }
160   }
161   return aResult;
162 }
163
164 void Model_Objects::refsToFeature(FeaturePtr theFeature,
165   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
166 {
167   // check the feature: it must have no depended objects on it
168   // the dependencies can be in the feature results
169   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
170   for(; aResIter != theFeature->results().cend(); aResIter++) {
171     ResultPtr aResult = (*aResIter);
172     std::shared_ptr<Model_Data> aData = 
173       std::dynamic_pointer_cast<Model_Data>(aResult->data());
174     if (aData.get() != NULL) {
175       const std::set<AttributePtr>& aRefs = aData->refsToMe();
176       std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
177       for(; aRefIt != aRefLast; aRefIt++) {
178         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
179         if (aFeature.get() != NULL)
180           theRefs.insert(aFeature);
181       }
182     }
183   }
184   // the dependencies can be in the feature itself
185   std::shared_ptr<Model_Data> aData = 
186       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
187   if (aData && !aData->refsToMe().empty()) {
188     const std::set<AttributePtr>& aRefs = aData->refsToMe();
189     std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
190     for(; aRefIt != aRefLast; aRefIt++) {
191       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
192       if (aFeature.get() != NULL)
193         theRefs.insert(aFeature);
194     }
195   }
196
197   if (!theRefs.empty() && isSendError) {
198     Events_Error::send(
199       "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
200   }
201 }
202
203 void Model_Objects::removeFeature(FeaturePtr theFeature)
204 {
205   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
206   if (aData && aData->isValid()) {
207     // checking that the sub-element of composite feature is removed: if yes, inform the owner
208     std::set<std::shared_ptr<ModelAPI_Feature> > aRefs;
209     refsToFeature(theFeature, aRefs, false);
210     std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aRefIter = aRefs.begin();
211     for(; aRefIter != aRefs.end(); aRefIter++) {
212       std::shared_ptr<ModelAPI_CompositeFeature> aComposite = 
213         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aRefIter);
214       if (aComposite.get()) {
215         aComposite->removeFeature(theFeature);
216       }
217     }
218     // erase fields
219     theFeature->erase();
220
221     TDF_Label aFeatureLabel = aData->label().Father();
222     if (myFeatures.IsBound(aFeatureLabel))
223       myFeatures.UnBind(aFeatureLabel);
224
225     clearHistory(theFeature);
226
227     static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
228     ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
229     // erase all attributes under the label of feature
230     aFeatureLabel.ForgetAllAttributes();
231     // remove it from the references array
232     RemoveFromRefArray(featuresLabel(), aFeatureLabel);
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       aFeature->setDisabled(false); // by default created feature is enabled (this allows to recreate the results before "setCurrent" is called)
490
491       // event: model is updated
492       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
493     } else {  // nothing is changed, both iterators are incremented
494       aFeature = myFeatures.Find(aFeatureLabel);
495       aKeptFeatures.insert(aFeature);
496       if (theMarkUpdated) {
497         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anUpdateEvent);
498       }
499     }
500   }
501   // update results of the features (after features created because they may be connected, like sketch and sub elements)
502   std::list<FeaturePtr> aComposites; // composites must be updated after their subs (issue 360)
503   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
504   for (; aLabIter2.More(); aLabIter2.Next()) {
505     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
506     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
507       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
508       if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature).get())
509         aComposites.push_back(aFeature);
510       updateResults(aFeature);
511     }
512   }
513   std::list<FeaturePtr>::iterator aComposite = aComposites.begin();
514   for(; aComposite != aComposites.end(); aComposite++) {
515     updateResults(*aComposite);
516   }
517
518   // check all features are checked: if not => it was removed
519   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
520   while (aFIter.More()) {
521     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
522       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
523         FeaturePtr aFeature = aFIter.Value();
524         // event: model is updated
525         //if (aFeature->isInHistory()) {
526         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
527         //}
528         // results of this feature must be redisplayed (hided)
529         // redisplay also removed feature (used for sketch and AISObject)
530         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
531         updateHistory(aFeature);
532         aFeature->erase();
533         // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
534         myFeatures.UnBind(aFIter.Key());
535         // reinitialize iterator because unbind may corrupt the previous order in the map
536         aFIter.Initialize(myFeatures);
537     } else
538       aFIter.Next();
539   }
540
541   if (theUpdateReferences) {
542     synchronizeBackRefs();
543   }
544   if (theMarkUpdated) { // this means there is no control what was modified => remove history cash
545     myHistory.clear();
546   }
547
548   anOwner->executeFeatures() = false;
549   aLoop->activateFlushes(true);
550
551   if (theFlush) {
552     aLoop->flush(aCreateEvent);
553     aLoop->flush(aDeleteEvent);
554     aLoop->flush(anUpdateEvent);
555     aLoop->flush(aRedispEvent);
556     aLoop->flush(aToHideEvent);
557   }
558   anOwner->executeFeatures() = true;
559 }
560
561 void Model_Objects::synchronizeBackRefs()
562 {
563   // keeps the concealed flags of result to catch the change and create created/deleted events
564   std::list<std::pair<ResultPtr, bool> > aConcealed;
565   // first cycle: erase all data about back-references
566   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
567   for(; aFeatures.More(); aFeatures.Next()) {
568     FeaturePtr aFeature = aFeatures.Value();
569     std::shared_ptr<Model_Data> aFData = 
570       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
571     if (aFData) {
572       aFData->eraseBackReferences();
573     }
574     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
575     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
576     for (; aRIter != aResults.cend(); aRIter++) {
577       std::shared_ptr<Model_Data> aResData = 
578         std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
579       if (aResData) {
580         aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
581         aResData->eraseBackReferences();
582       }
583     }
584   }
585
586   // second cycle: set new back-references: only features may have reference, iterate only them
587   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
588   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
589     FeaturePtr aFeature = aFeatures.Value();
590     std::shared_ptr<Model_Data> aFData = 
591       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
592     if (aFData) {
593       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
594       aFData->referencesToObjects(aRefs);
595       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator 
596         aRefsIter = aRefs.begin();
597       for(; aRefsIter != aRefs.end(); aRefsIter++) {
598         std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
599         for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
600           if (*aRefTo) {
601             std::shared_ptr<Model_Data> aRefData = 
602               std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
603             aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
604             // update enable/disable status: the nested status must be equal to the composite
605             CompositeFeaturePtr aComp = 
606               std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
607             if (aComp.get()) {
608               FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>(*aRefTo);
609               if (aReferenced.get()) {
610                 aReferenced->setDisabled(aComp->isDisabled());
611               }
612             }
613           }
614         }
615       }
616     }
617   }
618   std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
619   for(; aCIter != aConcealed.end(); aCIter++) {
620     if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
621       if (aCIter->second) { // was concealed become not => creation event
622         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
623         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
624       } else { // was not concealed become concealed => delete event
625         ModelAPI_EventCreator::get()->sendDeleted(myDoc, aCIter->first->groupName());
626         // redisplay for the viewer (it must be disappeared also)
627         static Events_ID EVENT_DISP = 
628           Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
629         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
630       }
631     }
632   }
633 }
634
635 TDF_Label Model_Objects::resultLabel(
636   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
637 {
638   const std::shared_ptr<Model_Data>& aData = 
639     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
640   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
641 }
642
643 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
644                                  std::shared_ptr<ModelAPI_Result> theResult,
645                                  const int theResultIndex)
646 {
647   theResult->setDoc(myDoc);
648   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
649   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
650     std::stringstream aNewName;
651     aNewName<<theFeatureData->name();
652     if (theResultIndex > 0) // if there are several results, add unique prefix starting from second
653       aNewName<<"_"<<theResultIndex + 1;
654     theResult->data()->setName(aNewName.str());
655   }
656 }
657
658 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
659     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
660 {
661   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
662   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
663   ObjectPtr anOldObject = object(aLab);
664   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
665   if (anOldObject) {
666     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
667   }
668   if (!aResult) {
669     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
670     storeResult(theFeatureData, aResult, theIndex);
671   }
672   return aResult;
673 }
674
675 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
676     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
677 {
678   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
679   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
680   ObjectPtr anOldObject = object(aLab);
681   std::shared_ptr<ModelAPI_ResultBody> aResult;
682   if (anOldObject) {
683     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
684   }
685   if (!aResult) {
686     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
687     storeResult(theFeatureData, aResult, theIndex);
688   }
689   return aResult;
690 }
691
692 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
693     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
694 {
695   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
696   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
697   ObjectPtr anOldObject = object(aLab);
698   std::shared_ptr<ModelAPI_ResultPart> aResult;
699   if (anOldObject) {
700     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
701   }
702   if (!aResult) {
703     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
704     storeResult(theFeatureData, aResult, theIndex);
705   }
706   return aResult;
707 }
708
709 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
710     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
711 {
712   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
713   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
714   ObjectPtr anOldObject = object(aLab);
715   std::shared_ptr<ModelAPI_ResultGroup> aResult;
716   if (anOldObject) {
717     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
718   }
719   if (!aResult) {
720     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
721     storeResult(theFeatureData, aResult, theIndex);
722   }
723   return aResult;
724 }
725
726 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
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_ResultParameter::group().c_str());
731   ObjectPtr anOldObject = object(aLab);
732   std::shared_ptr<ModelAPI_ResultParameter> aResult;
733   if (anOldObject) {
734     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
735   }
736   if (!aResult) {
737     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
738     storeResult(theFeatureData, aResult, theIndex);
739   }
740   return aResult;
741 }
742
743 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
744     const std::shared_ptr<ModelAPI_Result>& theResult)
745 {
746   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
747   if (aData) {
748     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
749     return feature(aFeatureLab);
750   }
751   return FeaturePtr();
752 }
753
754 void Model_Objects::updateResults(FeaturePtr theFeature)
755 {
756   // for not persistent is will be done by parametric updater automatically
757   //if (!theFeature->isPersistentResult()) return;
758   // check the existing results and remove them if there is nothing on the label
759   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
760   while(aResIter != theFeature->results().cend()) {
761     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
762     if (aBody) {
763       if (!aBody->data()->isValid()) { 
764         // found a disappeared result => remove it
765         theFeature->removeResult(aBody);
766         // start iterate from beginning because iterator is corrupted by removing
767         aResIter = theFeature->results().cbegin();
768         continue;
769       }
770     }
771     aResIter++;
772   }
773   // it may be on undo
774   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
775     return;
776   // check that results are presented on all labels
777   int aResSize = theFeature->results().size();
778   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
779   for(; aLabIter.More(); aLabIter.Next()) {
780     // here must be GUID of the feature
781     int aResIndex = aLabIter.Value().Tag() - 1;
782     ResultPtr aNewBody;
783     if (aResSize <= aResIndex) {
784       TDF_Label anArgLab = aLabIter.Value();
785       Handle(TDataStd_Comment) aGroup;
786       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
787         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
788           aNewBody = createBody(theFeature->data(), aResIndex);
789         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
790           //aNewBody = createPart(theFeature->data(), aResIndex); 
791           theFeature->execute(); // create the part result
792           break;
793         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
794           theFeature->execute(); // construction shapes are needed for sketch solver
795           break;
796         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
797           aNewBody = createGroup(theFeature->data(), aResIndex);
798         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
799           theFeature->attributeChanged("expression"); // just produce a value
800           break;
801         } else {
802           Events_Error::send(std::string("Unknown type of result is found in the document:") +
803             TCollection_AsciiString(aGroup->Get()).ToCString());
804         }
805       }
806       if (aNewBody) {
807         theFeature->setResult(aNewBody, aResIndex);
808       }
809     }
810   }
811 }
812
813 ResultPtr Model_Objects::findByName(const std::string theName)
814 {
815   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
816   for(; anObjIter.More(); anObjIter.Next()) {
817     FeaturePtr& aFeature = anObjIter.ChangeValue();
818     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
819       continue;
820     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
821     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
822     for (; aRIter != aResults.cend(); aRIter++) {
823       ResultPtr aRes = *aRIter;
824       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
825           aRes->data()->name() == theName) {
826         return aRes;
827       }
828     }
829   }
830   // not found
831   return ResultPtr();
832 }
833
834 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, const bool theReverse)
835 {
836   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
837   if (aData && aData->isValid()) {
838     TDF_Label aFeatureLabel = aData->label().Father();
839     Handle(TDataStd_ReferenceArray) aRefs;
840     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
841       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
842         if (aRefs->Value(a).IsEqual(aFeatureLabel)) {
843           a += theReverse ? -1 : 1;
844           if (a >= aRefs->Lower() && a <= aRefs->Upper())
845             return feature(aRefs->Value(a));
846           break; // finish iiteration: it's last feature
847         }
848       }
849     }
850   }
851   return FeaturePtr(); // not found, last, or something is wrong
852 }
853
854 FeaturePtr Model_Objects::firstFeature()
855 {
856   Handle(TDataStd_ReferenceArray) aRefs;
857   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
858     return feature(aRefs->Value(aRefs->Lower()));
859   }
860   return FeaturePtr(); // no features at all
861 }
862
863 FeaturePtr Model_Objects::lastFeature()
864 {
865   Handle(TDataStd_ReferenceArray) aRefs;
866   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
867     return feature(aRefs->Value(aRefs->Upper()));
868   }
869   return FeaturePtr(); // no features at all
870 }
871
872 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
873 {
874   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
875
876 }
877 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
878 {
879   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
880 }