Salome HOME
bf2a2e65750bd665c52c7e01b3abe5131a9cfd64
[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_ResultCompSolid.h>
16 #include <Model_ResultGroup.h>
17 #include <Model_ResultParameter.h>
18 #include <ModelAPI_Validator.h>
19 #include <ModelAPI_CompositeFeature.h>
20 #include <ModelAPI_Tools.h>
21
22 #include <Events_Loop.h>
23 #include <Events_Error.h>
24
25 #include <TDataStd_Integer.hxx>
26 #include <TDataStd_Comment.hxx>
27 #include <TDF_ChildIDIterator.hxx>
28 #include <TDataStd_ReferenceArray.hxx>
29 #include <TDataStd_HLabelArray1.hxx>
30 #include <TDataStd_Name.hxx>
31 #include <TDF_Reference.hxx>
32 #include <TDF_ChildIDIterator.hxx>
33 #include <TDF_LabelMapHasher.hxx>
34 #include <TDF_LabelMap.hxx>
35 #include <TDF_ListIteratorOfLabelList.hxx>
36
37 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
38
39 // feature sub-labels
40 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
41 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
42
43 ///
44 /// 0:1:2 - where features are located
45 /// 0:1:2:N:1 - data of the feature N
46 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
47
48 Model_Objects::Model_Objects(TDF_Label theMainLab) : myMain(theMainLab)
49 {
50 }
51
52 void Model_Objects::setOwner(DocumentPtr theDoc)
53 {
54   myDoc = theDoc;
55   // update all fields and recreate features and result objects if needed
56   TDF_LabelList aNoUpdated;
57   synchronizeFeatures(aNoUpdated, true, true);
58   myHistory.clear();
59 }
60
61 Model_Objects::~Model_Objects()
62 {
63   // delete all features of this document
64   Events_Loop* aLoop = Events_Loop::loop();
65   // erase one by one to avoid access from the feature destructor itself from he map
66   // blocks the flush signals to avoid the temporary objects visualization in the viewer
67   // they should not be shown in order to do not lose highlight by erasing them
68   bool isActive = aLoop->activateFlushes(false);
69
70   while(!myFeatures.IsEmpty()) {
71     NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myFeatures);
72     FeaturePtr aFeature = aFeaturesIter.Value();
73     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
74     ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
75     ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
76     aFeature->removeResults(0, false);
77     //aFeature->eraseResults();
78     aFeature->erase();
79     myFeatures.UnBind(aFeaturesIter.Key());
80   }
81   aLoop->activateFlushes(isActive);
82   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
83   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
84
85 }
86
87 /// Appends to the array of references a new referenced label
88 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced, TDF_Label& thePrevLab)
89 {
90   Handle(TDataStd_ReferenceArray) aRefs;
91   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
92     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
93     aRefs->SetValue(0, theReferenced);
94   } else {  // extend array by one more element
95     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
96                                                                         aRefs->Upper() + 1);
97     int aPassedPrev = 0; // prev feature is found and passed
98     if (thePrevLab.IsNull()) { // null means that inserted feature must be the first
99       aNewArray->SetValue(aRefs->Lower(), theReferenced);
100       aPassedPrev = 1;
101     }
102     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
103       aNewArray->SetValue(a + aPassedPrev, aRefs->Value(a));
104       if (!aPassedPrev && aRefs->Value(a).IsEqual(thePrevLab)) {
105         aPassedPrev = 1;
106         aNewArray->SetValue(a + 1, theReferenced);
107       }
108     }
109     if (!aPassedPrev) // not found: unknown situation
110       aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
111     aRefs->SetInternalArray(aNewArray);
112   }
113 }
114
115 void Model_Objects::addFeature(FeaturePtr theFeature, const FeaturePtr theAfterThis)
116 {
117   if (!theFeature->isAction()) {  // do not add action to the data model
118     TDF_Label aFeaturesLab = featuresLabel();
119     TDF_Label aFeatureLab = aFeaturesLab.NewChild();
120     // store feature in the features array: before "initData" because in macro features
121     // in initData it creates new features, appeared later than this
122     TDF_Label aPrevFeateureLab;
123     if (theAfterThis.get()) { // searching for the previous feature label
124       std::shared_ptr<Model_Data> aPrevData = 
125         std::dynamic_pointer_cast<Model_Data>(theAfterThis->data());
126       if (aPrevData.get()) {
127         aPrevFeateureLab = aPrevData->label().Father();
128       }
129     }
130     AddToRefArray(aFeaturesLab, aFeatureLab, aPrevFeateureLab);
131
132     // keep the feature ID to restore document later correctly
133     TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
134     myFeatures.Bind(aFeatureLab, theFeature);
135     // must be after binding to the map because of "Box" macro feature that 
136     // creates other features in "initData"
137     initData(theFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
138     // event: feature is added
139     static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
140     ModelAPI_EventCreator::get()->sendUpdated(theFeature, anEvent);
141     theFeature->setDisabled(false); // by default created feature is enabled
142     updateHistory(ModelAPI_Feature::group());
143   } else { // make feature has not-null data anyway
144     theFeature->setData(Model_Data::invalidData());
145     theFeature->setDoc(myDoc);
146   }
147 }
148
149 /// Appends to the array of references a new referenced label.
150 /// If theIndex is not -1, removes element at this index, not theReferenced.
151 /// \returns the index of removed element
152 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, 
153   const int theIndex = -1)
154 {
155   int aResult = -1;  // no returned
156   Handle(TDataStd_ReferenceArray) aRefs;
157   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
158     if (aRefs->Length() == 1) {  // just erase an array
159       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
160         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
161       }
162       aResult = 0;
163     } else {  // reduce the array
164       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
165                                                                           aRefs->Upper() - 1);
166       int aCount = aRefs->Lower();
167       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
168         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
169           aCount--;
170           aResult = a;
171         } else {
172           aNewArray->SetValue(aCount, aRefs->Value(a));
173         }
174       }
175       aRefs->SetInternalArray(aNewArray);
176     }
177   }
178   return aResult;
179 }
180
181 void Model_Objects::refsToFeature(FeaturePtr theFeature,
182   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
183 {
184   // check the feature: it must have no depended objects on it
185   // the dependencies can be in the feature results
186   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
187   for(; aResIter != theFeature->results().cend(); aResIter++) {
188     ResultPtr aResult = (*aResIter);
189     std::shared_ptr<Model_Data> aData = 
190       std::dynamic_pointer_cast<Model_Data>(aResult->data());
191     if (aData.get() != NULL) {
192       const std::set<AttributePtr>& aRefs = aData->refsToMe();
193       std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
194       for(; aRefIt != aRefLast; aRefIt++) {
195         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
196         if (aFeature.get() != NULL)
197           theRefs.insert(aFeature);
198       }
199     }
200   }
201   // the dependencies can be in the feature itself
202   std::shared_ptr<Model_Data> aData = 
203       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
204   if (aData && !aData->refsToMe().empty()) {
205     const std::set<AttributePtr>& aRefs = aData->refsToMe();
206     std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
207     for(; aRefIt != aRefLast; aRefIt++) {
208       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
209       if (aFeature.get() != NULL)
210         theRefs.insert(aFeature);
211     }
212   }
213
214   if (!theRefs.empty() && isSendError) {
215     Events_Error::send(
216       "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
217   }
218 }
219
220 void Model_Objects::removeFeature(FeaturePtr theFeature)
221 {
222   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
223   if (aData && aData->isValid()) {
224     // checking that the sub-element of composite feature is removed: if yes, inform the owner
225     std::set<std::shared_ptr<ModelAPI_Feature> > aRefs;
226     refsToFeature(theFeature, aRefs, false);
227     std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aRefIter = aRefs.begin();
228     for(; aRefIter != aRefs.end(); aRefIter++) {
229       std::shared_ptr<ModelAPI_CompositeFeature> aComposite = 
230         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aRefIter);
231       if (aComposite.get()) {
232         aComposite->removeFeature(theFeature);
233       }
234     }
235     // this must be before erase since theFeature erasing removes all information about
236     // the feature results and groups of results
237     // To reproduce: create sketch, extrusion, remove sketch => constructions tree is not updated
238     clearHistory(theFeature);
239     // erase fields
240     theFeature->erase();
241
242     TDF_Label aFeatureLabel = aData->label().Father();
243     if (myFeatures.IsBound(aFeatureLabel))
244       myFeatures.UnBind(aFeatureLabel);
245
246     static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
247     ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
248     // erase all attributes under the label of feature
249     aFeatureLabel.ForgetAllAttributes();
250     // remove it from the references array
251     RemoveFromRefArray(featuresLabel(), aFeatureLabel);
252     // event: feature is deleted
253     ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
254     // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
255     Events_Loop::loop()->flush(EVENT_DISP);
256     updateHistory(ModelAPI_Feature::group());
257   }
258 }
259
260 void Model_Objects::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
261 {
262   TDF_Label aFeaturesLab = featuresLabel();
263   Handle(TDataStd_ReferenceArray) aRefs;
264   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
265     return;
266   TDF_Label anAfterLab, aMovedLab = 
267     std::dynamic_pointer_cast<Model_Data>(theMoved->data())->label().Father();
268   if (theAfterThis.get())
269     anAfterLab = std::dynamic_pointer_cast<Model_Data>(theAfterThis->data())->label().Father();
270
271   Handle(TDataStd_HLabelArray1) aNewArray = 
272     new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper());
273   int aPassedMovedFrom = 0; // the prev feature location is found and passed
274   int aPassedMovedTo = 0; // the feature is added and this location is passed
275   if (!theAfterThis.get()) { // null means that inserted feature must be the first
276     aNewArray->SetValue(aRefs->Lower(), aMovedLab);
277     aPassedMovedTo = 1;
278   }
279   for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
280     if (aPassedMovedTo == 0 && aRefs->Value(a) == anAfterLab) { // add two
281       aPassedMovedTo++;
282       aNewArray->SetValue(a - aPassedMovedFrom, anAfterLab);
283       if (a + 1 - aPassedMovedFrom <= aRefs->Upper())
284         aNewArray->SetValue(a + 1 - aPassedMovedFrom, aMovedLab);
285     } else if (aPassedMovedFrom == 0 && aRefs->Value(a) == aMovedLab) { // skip
286       aPassedMovedFrom++;
287     } else { // just copy one
288       if (a - aPassedMovedFrom + aPassedMovedTo <= aRefs->Upper())
289         aNewArray->SetValue(a - aPassedMovedFrom + aPassedMovedTo, aRefs->Value(a));
290     }
291   }
292   if (!aPassedMovedFrom || !aPassedMovedTo) {// not found: unknown situation
293     if (!aPassedMovedFrom) {
294       static std::string aMovedFromError("The moved feature is not found");
295       Events_Error::send(aMovedFromError);
296     } else {
297       static std::string aMovedToError("The 'after' feature for movement is not found");
298       Events_Error::send(aMovedToError);
299     }
300     return;
301   }
302   // store the new array
303   aRefs->SetInternalArray(aNewArray);
304   // update the feature and the history
305   clearHistory(theMoved);
306   // make sure all (selection) attributes of moved feature will be updated
307   theMoved->data()->setUpdateID(0);
308   static Events_ID EVENT_UPD = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
309   ModelAPI_EventCreator::get()->sendUpdated(theMoved, EVENT_UPD);
310   ModelAPI_EventCreator::get()->sendReordered(theMoved->document(), theMoved->groupName());
311 }
312
313 void Model_Objects::clearHistory(ObjectPtr theObj)
314 {
315   if (theObj) {
316     const std::string aGroup = theObj->groupName();
317     std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(aGroup);
318     if (aHIter != myHistory.end())
319       myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
320     if (theObj->groupName() == ModelAPI_Feature::group()) { // clear results group of the feature
321       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
322       std::string aResultGroup = featureResultGroup(aFeature);
323       if (!aResultGroup.empty()) {
324         std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = 
325           myHistory.find(aResultGroup);
326         if (aHIter != myHistory.end())
327           myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
328       }
329     }
330   }
331 }
332
333 void Model_Objects::createHistory(const std::string& theGroupID)
334 {
335   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroupID);
336   if (aHIter == myHistory.end()) {
337     myHistory[theGroupID] = std::vector<ObjectPtr>();
338     std::vector<ObjectPtr>& aResult = myHistory[theGroupID];
339     // iterate the array of references and get feature by feature from the array
340     bool isFeature = theGroupID == ModelAPI_Feature::group();
341     Handle(TDataStd_ReferenceArray) aRefs;
342     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
343       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
344         FeaturePtr aFeature = feature(aRefs->Value(a));
345         if (aFeature.get()) {
346           // if feature is in sub-component, remove it from history: it is in sub-tree of sub-component
347           if (!ModelAPI_Tools::compositeOwner(aFeature).get()) {
348             if (isFeature) { // here may be also disabled features
349               if (aFeature->isInHistory()) {
350                 aResult.push_back(aFeature);
351               }
352             } else if (!aFeature->isDisabled()) { // iterate all results of not-disabled feature
353               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
354               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
355               for (; aRIter != aResults.cend(); aRIter++) {
356                 ResultPtr aRes = *aRIter;
357                 if (aRes->groupName() != theGroupID) break; // feature have only same group results
358                 if (!aRes->isDisabled() && aRes->isInHistory() && !aRes->isConcealed()) {
359                   aResult.push_back(*aRIter);
360                 }
361               }
362             }
363           }
364         }
365       }
366     }
367   }
368 }
369
370 void Model_Objects::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
371 {
372   clearHistory(theObject);
373 }
374
375 void Model_Objects::updateHistory(const std::string theGroup)
376 {
377   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroup);
378   if (aHIter != myHistory.end())
379     myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
380 }
381
382 FeaturePtr Model_Objects::feature(TDF_Label theLabel) const
383 {
384   if (myFeatures.IsBound(theLabel))
385     return myFeatures.Find(theLabel);
386   return FeaturePtr();  // not found
387 }
388
389 ObjectPtr Model_Objects::object(TDF_Label theLabel)
390 {
391   // try feature by label
392   FeaturePtr aFeature = feature(theLabel);
393   if (aFeature)
394     return feature(theLabel);
395   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
396   aFeature = feature(aFeatureLabel);
397   bool isSubResult = false;
398   if (!aFeature.get() && aFeatureLabel.Depth() > 1) { // let's suppose this is sub-result of result
399     aFeatureLabel = aFeatureLabel.Father().Father();
400     aFeature = feature(aFeatureLabel);
401     isSubResult = true;
402   }
403   if (aFeature) {
404     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
405     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
406     for (; aRIter != aResults.cend(); aRIter++) {
407       if (isSubResult) {
408         ResultCompSolidPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
409         if (aCompRes) {
410           int aNumSubs = aCompRes->numberOfSubs();
411           for(int a = 0; a < aNumSubs; a++) {
412             ResultPtr aSub = aCompRes->subResult(a);
413             if (aSub.get()) {
414               std::shared_ptr<Model_Data> aSubData = std::dynamic_pointer_cast<Model_Data>(
415                   aSub->data());
416               if (aSubData->label().Father().IsEqual(theLabel))
417                 return aSub;
418             }
419           }
420         }
421       } else {
422         std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
423             (*aRIter)->data());
424         if (aResData->label().Father().IsEqual(theLabel))
425           return *aRIter;
426       }
427     }
428   }
429   return FeaturePtr();  // not found
430 }
431
432 ObjectPtr Model_Objects::object(const std::string& theGroupID, const int theIndex)
433 {
434   if (theIndex == -1)
435     return ObjectPtr();
436   createHistory(theGroupID);
437   return myHistory[theGroupID][theIndex];
438 }
439
440 std::shared_ptr<ModelAPI_Object> Model_Objects::objectByName(
441     const std::string& theGroupID, const std::string& theName)
442 {
443   createHistory(theGroupID);
444   std::vector<ObjectPtr>& allObjs = myHistory[theGroupID];
445   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin();
446   for(; anObjIter != allObjs.end(); anObjIter++) {
447     if ((*anObjIter)->data()->name() == theName)
448       return *anObjIter;
449   }
450   // not found
451   return ObjectPtr();
452 }
453
454 const int Model_Objects::index(std::shared_ptr<ModelAPI_Object> theObject)
455 {
456   std::string aGroup = theObject->groupName();
457   createHistory(aGroup);
458   std::vector<ObjectPtr>& allObjs = myHistory[aGroup];
459   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin(); // iterate to search object
460   for(int anIndex = 0; anObjIter != allObjs.end(); anObjIter++, anIndex++) {
461     if ((*anObjIter) == theObject)
462       return anIndex;
463   }
464   // not found
465   return -1;
466 }
467
468 int Model_Objects::size(const std::string& theGroupID)
469 {
470   createHistory(theGroupID);
471   return myHistory[theGroupID].size();
472 }
473
474 void Model_Objects::allResults(const std::string& theGroupID, std::list<ResultPtr>& theResults)
475 {
476   // iterate the array of references and get feature by feature from the array
477   Handle(TDataStd_ReferenceArray) aRefs;
478   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
479     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
480       FeaturePtr aFeature = feature(aRefs->Value(a));
481       if (aFeature.get()) {
482         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
483         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
484         for (; aRIter != aResults.cend(); aRIter++) {
485           ResultPtr aRes = *aRIter;
486           if (aRes->groupName() != theGroupID) break; // feature have only same group results
487           // iterate also concealed: ALL RESULTS (for translation parts undo/redo management)
488           //if (aRes->isInHistory() && !aRes->isConcealed()) {
489             theResults.push_back(*aRIter);
490           //}
491         }
492       }
493     }
494   }
495 }
496
497
498 TDF_Label Model_Objects::featuresLabel() const
499 {
500   return myMain.FindChild(TAG_OBJECTS);
501 }
502
503 void Model_Objects::setUniqueName(FeaturePtr theFeature)
504 {
505   if (!theFeature->data()->name().empty())
506     return;  // not needed, name is already defined
507   std::string aName;  // result
508   // first count all features of such kind to start with index = count + 1
509   int aNumObjects = -1; // this feature is already in this map
510   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
511   for (; aFIter.More(); aFIter.Next()) {
512     if (aFIter.Value()->getKind() == theFeature->getKind())
513       aNumObjects++;
514   }
515   // generate candidate name
516   std::stringstream aNameStream;
517   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
518   aName = aNameStream.str();
519   // check this is unique, if not, increase index by 1
520   for (aFIter.Initialize(myFeatures); aFIter.More();) {
521     FeaturePtr aFeature = aFIter.Value();
522     bool isSameName = aFeature->data()->name() == aName;
523     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
524       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
525       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
526       for (; aRIter != aResults.cend(); aRIter++) {
527         isSameName = (*aRIter)->data()->name() == aName;
528       }
529     }
530     if (isSameName) {
531       aNumObjects++;
532       std::stringstream aNameStream;
533       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
534       aName = aNameStream.str();
535       // reinitialize iterator to make sure a new name is unique
536       aFIter.Initialize(myFeatures);
537     } else
538       aFIter.Next();
539   }
540   theFeature->data()->setName(aName);
541 }
542
543 void Model_Objects::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
544 {
545   std::shared_ptr<Model_Data> aData(new Model_Data);
546   aData->setLabel(theLab.FindChild(theTag));
547   aData->setObject(theObj);
548   theObj->setDoc(myDoc);
549   theObj->setData(aData);
550   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
551   if (aFeature) {
552     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
553   }
554   theObj->initAttributes();
555 }
556
557 void Model_Objects::synchronizeFeatures(
558   const TDF_LabelList& theUpdated, const bool theUpdateReferences, const bool theFlush)
559 {
560   Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
561   if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
562     return;
563   // after all updates, sends a message that groups of features were created or updated
564   Events_Loop* aLoop = Events_Loop::loop();
565   static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
566   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
567   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
568   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
569   static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
570   static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
571   bool isActive = aLoop->activateFlushes(false);
572
573   // collect all updated labels map
574   TDF_LabelMap anUpdatedMap;
575   TDF_ListIteratorOfLabelList anUpdatedIter(theUpdated);
576   for(; anUpdatedIter.More(); anUpdatedIter.Next()) {
577     TDF_Label& aFeatureLab = anUpdatedIter.Value();
578     while(aFeatureLab.Depth() > 3)
579       aFeatureLab = aFeatureLab.Father();
580     if (myFeatures.IsBound(aFeatureLab))
581       anUpdatedMap.Add(aFeatureLab);
582   }
583
584   // update all objects by checking are they on labels or not
585   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
586   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
587   for (; aLabIter.More(); aLabIter.Next()) {
588     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
589     FeaturePtr aFeature;
590     if (!myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
591       // create a feature
592       aFeature = std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get())->createFeature(
593         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
594         .ToCString(), anOwner);
595       if (!aFeature) {  // somethig is wrong, most probably, the opened document has invalid structure
596         Events_Error::send("Invalid type of object in the document");
597         aLabIter.Value()->Label().ForgetAllAttributes();
598         continue;
599       }
600       // this must be before "setData" to redo the sketch line correctly
601       myFeatures.Bind(aFeatureLabel, aFeature);
602       aNewFeatures.insert(aFeature);
603       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
604       updateHistory(aFeature);
605       aFeature->setDisabled(false); // by default created feature is enabled (this allows to recreate the results before "setCurrent" is called)
606
607       // event: model is updated
608       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
609     } else {  // nothing is changed, both iterators are incremented
610       aFeature = myFeatures.Find(aFeatureLabel);
611       aKeptFeatures.insert(aFeature);
612       if (anUpdatedMap.Contains(aFeatureLabel)) {
613         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anUpdateEvent);
614       }
615     }
616   }
617
618   // check all features are checked: if not => it was removed
619   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
620   while (aFIter.More()) {
621     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
622       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
623         FeaturePtr aFeature = aFIter.Value();
624         // event: model is updated
625         //if (aFeature->isInHistory()) {
626         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
627         //}
628         // results of this feature must be redisplayed (hided)
629         // redisplay also removed feature (used for sketch and AISObject)
630         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
631         updateHistory(aFeature);
632         aFeature->erase();
633         // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
634         myFeatures.UnBind(aFIter.Key());
635         // reinitialize iterator because unbind may corrupt the previous order in the map
636         aFIter.Initialize(myFeatures);
637     } else
638       aFIter.Next();
639   }
640
641   if (theUpdateReferences) {
642     synchronizeBackRefs();
643   }
644   // update results of the features (after features created because they may be connected, like sketch and sub elements)
645   // After synchronisation of back references because sketch must be set in sub-elements before "execute" by updateResults
646   std::list<FeaturePtr> aComposites; // composites must be updated after their subs (issue 360)
647   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
648   for (; aLabIter2.More(); aLabIter2.Next()) {
649     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
650     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
651       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
652       if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature).get())
653         aComposites.push_back(aFeature);
654       updateResults(aFeature);
655     }
656   }
657   std::list<FeaturePtr>::iterator aComposite = aComposites.begin();
658   for(; aComposite != aComposites.end(); aComposite++) {
659     updateResults(*aComposite);
660   }
661
662   // the synchronize should be done after updateResults in order to correct back references of updated results
663   if (theUpdateReferences) {
664     synchronizeBackRefs();
665   }
666   if (!theUpdated.IsEmpty()) { // this means there is no control what was modified => remove history cash
667     myHistory.clear();
668   }
669
670   anOwner->executeFeatures() = false;
671   aLoop->activateFlushes(isActive);
672
673   if (theFlush) {
674     aLoop->flush(aCreateEvent);
675     aLoop->flush(aDeleteEvent);
676     aLoop->flush(anUpdateEvent);
677     aLoop->flush(aCreateEvent); // after update of features, there could be results created
678     aLoop->flush(aDeleteEvent); // or deleted
679     aLoop->flush(aRedispEvent);
680     aLoop->flush(aToHideEvent);
681   }
682   anOwner->executeFeatures() = true;
683 }
684
685 void Model_Objects::synchronizeBackRefs()
686 {
687   // keeps the concealed flags of result to catch the change and create created/deleted events
688   std::list<std::pair<ResultPtr, bool> > aConcealed;
689   // first cycle: erase all data about back-references
690   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
691   for(; aFeatures.More(); aFeatures.Next()) {
692     FeaturePtr aFeature = aFeatures.Value();
693     std::shared_ptr<Model_Data> aFData = 
694       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
695     if (aFData) {
696       aFData->eraseBackReferences();
697     }
698     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
699     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
700     for (; aRIter != aResults.cend(); aRIter++) {
701       std::shared_ptr<Model_Data> aResData = 
702         std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
703       if (aResData.get()) {
704         aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
705         aResData->eraseBackReferences();
706       }
707       // iterate sub-bodies of compsolid
708       ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
709       if (aComp.get()) {
710         int aNumSub = aComp->numberOfSubs();
711         for(int a = 0; a < aNumSub; a++) {
712           ResultPtr aSub = aComp->subResult(a);
713           std::shared_ptr<Model_Data> aResData = 
714             std::dynamic_pointer_cast<Model_Data>(aSub->data());
715           if (aResData.get()) {
716             aConcealed.push_back(std::pair<ResultPtr, bool>(aSub, aSub->isConcealed()));
717             aResData->eraseBackReferences();
718           }
719         }
720       }
721     }
722   }
723
724   // second cycle: set new back-references: only features may have reference, iterate only them
725   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
726   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
727     FeaturePtr aFeature = aFeatures.Value();
728     std::shared_ptr<Model_Data> aFData = 
729       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
730     if (aFData) {
731       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
732       aFData->referencesToObjects(aRefs);
733       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator 
734         aRefsIter = aRefs.begin();
735       for(; aRefsIter != aRefs.end(); aRefsIter++) {
736         std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
737         for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
738           if (*aRefTo) {
739             std::shared_ptr<Model_Data> aRefData = 
740               std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
741             aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
742             // update enable/disable status: the nested status must be equal to the composite
743             CompositeFeaturePtr aComp = 
744               std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
745             if (aComp.get()) {
746               FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>(*aRefTo);
747               if (aReferenced.get()) {
748                 aReferenced->setDisabled(aComp->isDisabled());
749               }
750             }
751           }
752         }
753       }
754     }
755   }
756   std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
757   for(; aCIter != aConcealed.end(); aCIter++) {
758     if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
759       if (aCIter->second) { // was concealed become not => creation event
760         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
761         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
762       } else { // was not concealed become concealed => delete event
763         ModelAPI_EventCreator::get()->sendDeleted(myDoc, aCIter->first->groupName());
764         // redisplay for the viewer (it must be disappeared also)
765         static Events_ID EVENT_DISP = 
766           Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
767         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
768       }
769     }
770   }
771 }
772
773 TDF_Label Model_Objects::resultLabel(
774   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
775 {
776   const std::shared_ptr<Model_Data>& aData = 
777     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
778   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
779 }
780
781 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
782                                  std::shared_ptr<ModelAPI_Result> theResult,
783                                  const int theResultIndex)
784 {
785   theResult->setDoc(myDoc);
786   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
787   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
788     std::stringstream aNewName;
789     aNewName<<theFeatureData->name();
790     // if there are several results (issue #899: any number of result), add unique prefix starting from second
791     if (theResultIndex > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
792       aNewName<<"_"<<theResultIndex + 1;
793     theResult->data()->setName(aNewName.str());
794   }
795 }
796
797 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
798     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
799 {
800   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
801   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
802   ObjectPtr anOldObject = object(aLab);
803   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
804   if (anOldObject) {
805     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
806   }
807   if (!aResult) {
808     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
809     storeResult(theFeatureData, aResult, theIndex);
810   }
811   return aResult;
812 }
813
814 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
815     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
816 {
817   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
818   // for feature create compsolid, but for result sub create body: 
819   // only one level of recursion is supported now
820   ResultPtr aResultOwner = std::dynamic_pointer_cast<ModelAPI_Result>(theFeatureData->owner());
821   ObjectPtr anOldObject;
822   if (aResultOwner.get()) {
823     TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
824   } else { // in compsolid (higher level result) old object probably may be found
825     TDataStd_Comment::Set(aLab, ModelAPI_ResultCompSolid::group().c_str());
826     anOldObject = object(aLab);
827   }
828   std::shared_ptr<ModelAPI_ResultBody> aResult;
829   if (anOldObject) {
830     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
831   }
832   if (!aResult) {
833     // create compsolid anyway; if it is compsolid, it will create sub-bodies internally
834     if (aResultOwner.get()) {
835       aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
836     } else {
837       aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultCompSolid);
838     }
839     storeResult(theFeatureData, aResult, theIndex);
840   }
841   return aResult;
842 }
843
844 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
845     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
846 {
847   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
848   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
849   ObjectPtr anOldObject = object(aLab);
850   std::shared_ptr<ModelAPI_ResultPart> aResult;
851   if (anOldObject) {
852     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
853   }
854   if (!aResult) {
855     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
856     storeResult(theFeatureData, aResult, theIndex);
857   }
858   return aResult;
859 }
860
861 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
862     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
863     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
864 {
865   std::shared_ptr<ModelAPI_ResultPart> aResult = createPart(theFeatureData, theIndex);
866   aResult->data()->reference(Model_ResultPart::BASE_REF_ID())->setValue(theOrigin);
867   return aResult;
868 }
869
870 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
871     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
872 {
873   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
874   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
875   ObjectPtr anOldObject = object(aLab);
876   std::shared_ptr<ModelAPI_ResultGroup> aResult;
877   if (anOldObject) {
878     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
879   }
880   if (!aResult) {
881     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
882     storeResult(theFeatureData, aResult, theIndex);
883   }
884   return aResult;
885 }
886
887 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
888       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
889 {
890   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
891   TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
892   ObjectPtr anOldObject = object(aLab);
893   std::shared_ptr<ModelAPI_ResultParameter> aResult;
894   if (anOldObject) {
895     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
896   }
897   if (!aResult) {
898     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
899     storeResult(theFeatureData, aResult, theIndex);
900   }
901   return aResult;
902 }
903
904 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
905     const std::shared_ptr<ModelAPI_Result>& theResult)
906 {
907   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
908   if (aData) {
909     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
910     FeaturePtr aFeature = feature(aFeatureLab);
911     if (!aFeature.get() && aFeatureLab.Depth() > 1) { // this may be sub-result of result
912       aFeatureLab = aFeatureLab.Father().Father();
913       aFeature = feature(aFeatureLab);
914     }
915     return aFeature;
916   }
917   return FeaturePtr();
918 }
919
920 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
921 {
922   if (theFeature->data()->isValid()) {
923     TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
924     if (aLabIter.More()) {
925       TDF_Label anArgLab = aLabIter.Value();
926       Handle(TDataStd_Comment) aGroup;
927       if (aLabIter.Value().FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
928         return TCollection_AsciiString(aGroup->Get()).ToCString();
929       }
930     }
931   }
932   static std::string anEmpty;
933   return anEmpty; // not found
934 }
935
936 void Model_Objects::updateResults(FeaturePtr theFeature)
937 {
938   // for not persistent is will be done by parametric updater automatically
939   //if (!theFeature->isPersistentResult()) return;
940   // check the existing results and remove them if there is nothing on the label
941   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
942   while(aResIter != theFeature->results().cend()) {
943     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
944     if (aBody.get()) {
945       std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(aBody->data());
946       if (!aData.get() || !aData->isValid() || (!aBody->isDisabled() && aData->isDeleted())) { 
947         // found a disappeared result => remove it
948         theFeature->eraseResultFromList(aBody);
949         // start iterate from beginning because iterator is corrupted by removing
950         aResIter = theFeature->results().cbegin();
951         continue;
952       }
953     }
954     aResIter++;
955   }
956   // it may be on undo
957   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
958     return;
959   // check that results are presented on all labels
960   int aResSize = theFeature->results().size();
961   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
962   for(; aLabIter.More(); aLabIter.Next()) {
963     // here must be GUID of the feature
964     int aResIndex = aLabIter.Value().Tag() - 1;
965     ResultPtr aNewBody;
966     if (aResSize <= aResIndex) {
967       TDF_Label anArgLab = aLabIter.Value();
968       Handle(TDataStd_Comment) aGroup;
969       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
970         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str() || 
971             aGroup->Get() == ModelAPI_ResultCompSolid::group().c_str()) {
972           aNewBody = createBody(theFeature->data(), aResIndex);
973         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
974           std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex); 
975           theFeature->setResult(aNewP, aResIndex);
976           if (!aNewP->partDoc().get())
977             theFeature->execute(); // create the part result: it is better to restore the previous result if it is possible
978           break;
979         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
980           theFeature->execute(); // construction shapes are needed for sketch solver
981           break;
982         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
983           aNewBody = createGroup(theFeature->data(), aResIndex);
984         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
985           theFeature->attributeChanged("expression"); // just produce a value
986           break;
987         } else {
988           Events_Error::send(std::string("Unknown type of result is found in the document:") +
989             TCollection_AsciiString(aGroup->Get()).ToCString());
990         }
991       }
992       if (aNewBody && !aNewBody->data()->isDeleted()) {
993         theFeature->setResult(aNewBody, aResIndex);
994       }
995     }
996   }
997 }
998
999 ResultPtr Model_Objects::findByName(const std::string theName)
1000 {
1001   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
1002   for(; anObjIter.More(); anObjIter.Next()) {
1003     FeaturePtr& aFeature = anObjIter.ChangeValue();
1004     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
1005       continue;
1006     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
1007     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
1008     for (; aRIter != aResults.cend(); aRIter++) {
1009       ResultPtr aRes = *aRIter;
1010       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
1011           aRes->data()->name() == theName) {
1012         return aRes;
1013       }
1014     }
1015   }
1016   // not found
1017   return ResultPtr();
1018 }
1019
1020 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, const bool theReverse)
1021 {
1022   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1023   if (aData && aData->isValid()) {
1024     TDF_Label aFeatureLabel = aData->label().Father();
1025     Handle(TDataStd_ReferenceArray) aRefs;
1026     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1027       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
1028         TDF_Label aCurLab = aRefs->Value(a);
1029         if (aCurLab.IsEqual(aFeatureLabel)) {
1030           a += theReverse ? -1 : 1;
1031           if (a >= aRefs->Lower() && a <= aRefs->Upper())
1032             return feature(aRefs->Value(a));
1033           break; // finish iiteration: it's last feature
1034         }
1035       }
1036     }
1037   }
1038   return FeaturePtr(); // not found, last, or something is wrong
1039 }
1040
1041 FeaturePtr Model_Objects::firstFeature()
1042 {
1043   Handle(TDataStd_ReferenceArray) aRefs;
1044   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1045     return feature(aRefs->Value(aRefs->Lower()));
1046   }
1047   return FeaturePtr(); // no features at all
1048 }
1049
1050 FeaturePtr Model_Objects::lastFeature()
1051 {
1052   Handle(TDataStd_ReferenceArray) aRefs;
1053   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1054     return feature(aRefs->Value(aRefs->Upper()));
1055   }
1056   return FeaturePtr(); // no features at all
1057 }
1058
1059 bool Model_Objects::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
1060 {
1061   std::shared_ptr<Model_Data> aLaterD = std::static_pointer_cast<Model_Data>(theLater->data());
1062   std::shared_ptr<Model_Data> aCurrentD = std::static_pointer_cast<Model_Data>(theCurrent->data());
1063   if (aLaterD && aLaterD->isValid() && aCurrentD && aCurrentD->isValid()) {
1064     TDF_Label aLaterL = aLaterD->label().Father();
1065     TDF_Label aCurrentL = aCurrentD->label().Father();
1066     int aLaterI = -1, aCurentI = -1; // not found yet state
1067     Handle(TDataStd_ReferenceArray) aRefs;
1068     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1069       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
1070         TDF_Label aCurLab = aRefs->Value(a);
1071         if (aCurLab.IsEqual(aLaterL)) {
1072           aLaterI = a;
1073         } else if (aCurLab.IsEqual(aCurrentL)) {
1074           aCurentI = a;
1075         } else continue;
1076         if (aLaterI != -1 && aCurentI != -1) // both are found
1077           return aLaterI > aCurentI;
1078       }
1079     }
1080   }
1081   return false; // not found, or something is wrong
1082 }
1083
1084 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
1085 {
1086   std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
1087   Handle(TDataStd_ReferenceArray) aRefs;
1088   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1089     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
1090       FeaturePtr aFeature = feature(aRefs->Value(a));
1091       if (aFeature.get())
1092         aResult.push_back(aFeature);
1093     }
1094   }
1095   return aResult;
1096 }
1097
1098 int Model_Objects::numInternalFeatures()
1099 {
1100   Handle(TDataStd_ReferenceArray) aRefs;
1101   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1102     return aRefs->Upper() - aRefs->Lower() + 1;
1103   }
1104   return 0; // invalid
1105 }
1106
1107 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
1108 {
1109   Handle(TDataStd_ReferenceArray) aRefs;
1110   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1111     return feature(aRefs->Value(aRefs->Lower() + theIndex));
1112   }
1113   return FeaturePtr(); // invalid
1114 }
1115
1116 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1117 {
1118   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1119
1120 }
1121 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1122 {
1123   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1124 }