Salome HOME
e1636118df3e9d6362dd4cb5ec205a567287bcc4
[modules/shaper.git] / src / Model / Model_Objects.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <Model_Objects.h>
22 #include <Model_Data.h>
23 #include <Model_Document.h>
24 #include <Model_Events.h>
25 #include <Model_Session.h>
26 #include <Model_ResultPart.h>
27 #include <Model_ResultConstruction.h>
28 #include <Model_ResultBody.h>
29 #include <Model_ResultCompSolid.h>
30 #include <Model_ResultGroup.h>
31 #include <Model_ResultField.h>
32 #include <Model_ResultParameter.h>
33 #include <ModelAPI_Validator.h>
34 #include <ModelAPI_CompositeFeature.h>
35 #include <ModelAPI_Tools.h>
36
37 #include <Events_Loop.h>
38 #include <Events_InfoMessage.h>
39
40 #include <TDataStd_Integer.hxx>
41 #include <TDataStd_Comment.hxx>
42 #include <TDF_ChildIDIterator.hxx>
43 #include <TDataStd_ReferenceArray.hxx>
44 #include <TDataStd_HLabelArray1.hxx>
45 #include <TDataStd_Name.hxx>
46 #include <TDF_Reference.hxx>
47 #include <TDF_ChildIDIterator.hxx>
48 #include <TDF_LabelMapHasher.hxx>
49 #include <TDF_LabelMap.hxx>
50 #include <TDF_ListIteratorOfLabelList.hxx>
51
52 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
53
54 // feature sub-labels
55 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
56 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
57
58 ///
59 /// 0:1:2 - where features are located
60 /// 0:1:2:N:1 - data of the feature N
61 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
62
63 Model_Objects::Model_Objects(TDF_Label theMainLab) : myMain(theMainLab)
64 {
65 }
66
67 void Model_Objects::setOwner(DocumentPtr theDoc)
68 {
69   myDoc = theDoc;
70   // update all fields and recreate features and result objects if needed
71   TDF_LabelList aNoUpdated;
72   synchronizeFeatures(aNoUpdated, true, true, true, true);
73   myHistory.clear();
74 }
75
76 Model_Objects::~Model_Objects()
77 {
78   // delete all features of this document
79   Events_Loop* aLoop = Events_Loop::loop();
80   // erase one by one to avoid access from the feature destructor itself from he map
81   // blocks the flush signals to avoid the temporary objects visualization in the viewer
82   // they should not be shown in order to do not lose highlight by erasing them
83   bool isActive = aLoop->activateFlushes(false);
84
85   while(!myFeatures.IsEmpty()) {
86     NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myFeatures);
87     FeaturePtr aFeature = aFeaturesIter.Value();
88     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
89     ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
90     ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
91     aFeature->removeResults(0, false);
92     aFeature->erase();
93     myFeatures.UnBind(aFeaturesIter.Key());
94   }
95   myHistory.clear();
96   aLoop->activateFlushes(isActive);
97   // erase update, because features are destroyed and update should not performed for them anywhere
98   aLoop->eraseMessages(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
99   aLoop->eraseMessages(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
100   // deleted and redisplayed is correctly performed: they know that features are destroyed
101   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
102   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
103
104 }
105
106 /// Appends to the array of references a new referenced label
107 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced, TDF_Label& thePrevLab)
108 {
109   Handle(TDataStd_ReferenceArray) aRefs;
110   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
111     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
112     aRefs->SetValue(0, theReferenced);
113   } else {  // extend array by one more element
114     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
115                                                                         aRefs->Upper() + 1);
116     int aPassedPrev = 0; // prev feature is found and passed
117     if (thePrevLab.IsNull()) { // null means that inserted feature must be the first
118       aNewArray->SetValue(aRefs->Lower(), theReferenced);
119       aPassedPrev = 1;
120     }
121     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
122       aNewArray->SetValue(a + aPassedPrev, aRefs->Value(a));
123       if (!aPassedPrev && aRefs->Value(a).IsEqual(thePrevLab)) {
124         aPassedPrev = 1;
125         aNewArray->SetValue(a + 1, theReferenced);
126       }
127     }
128     if (!aPassedPrev) // not found: unknown situation
129       aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
130     aRefs->SetInternalArray(aNewArray);
131   }
132 }
133
134 void Model_Objects::addFeature(FeaturePtr theFeature, const FeaturePtr theAfterThis)
135 {
136   if (!theFeature->isAction()) {  // do not add action to the data model
137     TDF_Label aFeaturesLab = featuresLabel();
138     TDF_Label aFeatureLab = aFeaturesLab.NewChild();
139     // store feature in the features array: before "initData" because in macro features
140     // in initData it creates new features, appeared later than this
141     TDF_Label aPrevFeateureLab;
142     if (theAfterThis.get()) { // searching for the previous feature label
143       std::shared_ptr<Model_Data> aPrevData =
144         std::dynamic_pointer_cast<Model_Data>(theAfterThis->data());
145       if (aPrevData.get()) {
146         aPrevFeateureLab = aPrevData->label().Father();
147       }
148     }
149     AddToRefArray(aFeaturesLab, aFeatureLab, aPrevFeateureLab);
150
151     // keep the feature ID to restore document later correctly
152     TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
153     myFeatures.Bind(aFeatureLab, theFeature);
154     // must be before the event sending: for OB the feature is already added
155     updateHistory(ModelAPI_Feature::group());
156     // do not change the order:
157     // initData()
158     // sendUpdated()
159     // during python script with fillet constraint feature data should be
160     // initialized before using it in GUI
161
162     // must be after binding to the map because of "Box" macro feature that
163     // creates other features in "initData"
164     initData(theFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
165     // event: feature is added, mist be before "initData" to update OB correctly on Duplicate:
166     // first new part, then the content
167     static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
168     ModelAPI_EventCreator::get()->sendUpdated(theFeature, anEvent);
169   } else { // make feature has not-null data anyway
170     theFeature->setData(Model_Data::invalidData());
171     theFeature->setDoc(myDoc);
172   }
173 }
174
175 /// Appends to the array of references a new referenced label.
176 /// If theIndex is not -1, removes element at this index, not theReferenced.
177 /// \returns the index of removed element
178 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced,
179   const int theIndex = -1)
180 {
181   int aResult = -1;  // no returned
182   Handle(TDataStd_ReferenceArray) aRefs;
183   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
184     if (aRefs->Length() == 1) {  // just erase an array
185       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
186         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
187       }
188       aResult = 0;
189     } else {  // reduce the array
190       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
191                                                                           aRefs->Upper() - 1);
192       int aCount = aRefs->Lower();
193       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
194         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
195           aCount--;
196           aResult = a;
197         } else {
198           aNewArray->SetValue(aCount, aRefs->Value(a));
199         }
200       }
201       aRefs->SetInternalArray(aNewArray);
202     }
203   }
204   return aResult;
205 }
206
207 void Model_Objects::refsToFeature(FeaturePtr theFeature,
208   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
209 {
210   // check the feature: it must have no depended objects on it
211   // the dependencies can be in the feature results
212   std::list<ResultPtr> aResults;
213   ModelAPI_Tools::allResults(theFeature, aResults);
214   std::list<ResultPtr>::const_iterator aResIter = aResults.cbegin();
215   for (; aResIter != aResults.cend(); aResIter++) {
216     ResultPtr aResult = (*aResIter);
217     std::shared_ptr<Model_Data> aData =
218         std::dynamic_pointer_cast<Model_Data>(aResult->data());
219     if (aData.get() != NULL) {
220       const std::set<AttributePtr>& aRefs = aData->refsToMe();
221       std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
222       for (; aRefIt != aRefLast; aRefIt++) {
223         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
224         if (aFeature.get() != NULL)
225           theRefs.insert(aFeature);
226       }
227     }
228   }
229   // the dependencies can be in the feature itself
230   std::shared_ptr<Model_Data> aData =
231       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
232   if (aData.get() && !aData->refsToMe().empty()) {
233     const std::set<AttributePtr>& aRefs = aData->refsToMe();
234     std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
235     for (; aRefIt != aRefLast; aRefIt++) {
236       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
237       if (aFeature.get() != NULL)
238         theRefs.insert(aFeature);
239     }
240   }
241
242   if (!theRefs.empty() && isSendError) {
243     Events_InfoMessage("Model_Objects",
244       "Feature '%1' is used and can not be deleted").arg(theFeature->data()->name()).send();
245   }
246 }
247
248 void Model_Objects::removeFeature(FeaturePtr theFeature)
249 {
250   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
251   if (aData.get() && aData->isValid()) {
252     // checking that the sub-element of composite feature is removed: if yes, inform the owner
253     std::set<std::shared_ptr<ModelAPI_Feature> > aRefs;
254     refsToFeature(theFeature, aRefs, false);
255     std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aRefIter = aRefs.begin();
256     for(; aRefIter != aRefs.end(); aRefIter++) {
257       std::shared_ptr<ModelAPI_CompositeFeature> aComposite =
258         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aRefIter);
259       if (aComposite.get() && aComposite->isSub(theFeature)) {
260         aComposite->removeFeature(theFeature);
261       }
262     }
263     // this must be before erase since theFeature erasing removes all information about
264     // the feature results and groups of results
265     // To reproduce: create sketch, extrusion, remove sketch => constructions tree is not updated
266     clearHistory(theFeature);
267     // erase fields
268     theFeature->erase();
269
270     TDF_Label aFeatureLabel = aData->label().Father();
271     if (myFeatures.IsBound(aFeatureLabel))
272       myFeatures.UnBind(aFeatureLabel);
273
274     static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
275     ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
276     // erase all attributes under the label of feature
277     aFeatureLabel.ForgetAllAttributes();
278     // remove it from the references array
279     RemoveFromRefArray(featuresLabel(), aFeatureLabel);
280     // event: feature is deleted
281     ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
282     updateHistory(ModelAPI_Feature::group());
283   }
284 }
285
286 void Model_Objects::eraseAllFeatures()
287 {
288   static Events_ID kDispEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
289   static const ModelAPI_EventCreator* kCreator = ModelAPI_EventCreator::get();
290   // make all features invalid (like deleted)
291   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
292   for(; aFIter.More(); aFIter.Next()) {
293     FeaturePtr aFeature = aFIter.Value();
294     std::list<ResultPtr> aResList;
295     ModelAPI_Tools::allResults(aFeature, aResList);
296     std::list<ResultPtr>::iterator aRIter = aResList.begin();
297     for(; aRIter != aResList.end(); aRIter++) {
298       ResultPtr aRes = *aRIter;
299       if (aRes && aRes->data()->isValid()) {
300         kCreator->sendDeleted(myDoc, aRes->groupName());
301         kCreator->sendUpdated(aRes, kDispEvent);
302         aRes->setData(aRes->data()->invalidPtr());
303
304       }
305     }
306     kCreator->sendUpdated(aFeature, kDispEvent);
307     aFeature->setData(aFeature->data()->invalidPtr());
308   }
309   kCreator->sendDeleted(myDoc, ModelAPI_Feature::group());
310   myFeatures.Clear(); // just remove features without modification of DS
311   updateHistory(ModelAPI_Feature::group());
312 }
313
314 void Model_Objects::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
315 {
316   TDF_Label aFeaturesLab = featuresLabel();
317   Handle(TDataStd_ReferenceArray) aRefs;
318   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
319     return;
320   TDF_Label anAfterLab, aMovedLab =
321     std::dynamic_pointer_cast<Model_Data>(theMoved->data())->label().Father();
322   if (theAfterThis.get())
323     anAfterLab = std::dynamic_pointer_cast<Model_Data>(theAfterThis->data())->label().Father();
324
325   Handle(TDataStd_HLabelArray1) aNewArray =
326     new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper());
327   int aPassedMovedFrom = 0; // the prev feature location is found and passed
328   int aPassedMovedTo = 0; // the feature is added and this location is passed
329   if (!theAfterThis.get()) { // null means that inserted feature must be the first
330     aNewArray->SetValue(aRefs->Lower(), aMovedLab);
331     aPassedMovedTo = 1;
332   }
333   for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
334     if (aPassedMovedTo == 0 && aRefs->Value(a) == anAfterLab) { // add two
335       aPassedMovedTo++;
336       aNewArray->SetValue(a - aPassedMovedFrom, anAfterLab);
337       if (a + 1 - aPassedMovedFrom <= aRefs->Upper())
338         aNewArray->SetValue(a + 1 - aPassedMovedFrom, aMovedLab);
339     } else if (aPassedMovedFrom == 0 && aRefs->Value(a) == aMovedLab) { // skip
340       aPassedMovedFrom++;
341     } else { // just copy one
342       if (a - aPassedMovedFrom + aPassedMovedTo <= aRefs->Upper())
343         aNewArray->SetValue(a - aPassedMovedFrom + aPassedMovedTo, aRefs->Value(a));
344     }
345   }
346   if (!aPassedMovedFrom || !aPassedMovedTo) {// not found: unknown situation
347     if (!aPassedMovedFrom) {
348       static std::string aMovedFromError("The moved feature is not found");
349       Events_InfoMessage("Model_Objects", aMovedFromError).send();
350     } else {
351       static std::string aMovedToError("The 'after' feature for movement is not found");
352       Events_InfoMessage("Model_Objects", aMovedToError).send();
353     }
354     return;
355   }
356   // store the new array
357   aRefs->SetInternalArray(aNewArray);
358   // update the feature and the history
359   clearHistory(theMoved);
360   // make sure all (selection) attributes of moved feature will be updated
361   static Events_ID kUpdateSelection = Events_Loop::loop()->eventByName(EVENT_UPDATE_SELECTION);
362   ModelAPI_EventCreator::get()->sendUpdated(theMoved, kUpdateSelection, false);
363   ModelAPI_EventCreator::get()->sendReordered(theMoved);
364 }
365
366 void Model_Objects::clearHistory(ObjectPtr theObj)
367 {
368   if (theObj.get()) {
369     const std::string aGroup = theObj->groupName();
370     std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(aGroup);
371     if (aHIter != myHistory.end())
372       myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
373     if (theObj->groupName() == ModelAPI_Feature::group()) { // clear results group of the feature
374       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
375       std::string aResultGroup = featureResultGroup(aFeature);
376       if (!aResultGroup.empty()) {
377         std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter =
378           myHistory.find(aResultGroup);
379         if (aHIter != myHistory.end())
380           myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
381       }
382     }
383   }
384 }
385
386 void Model_Objects::createHistory(const std::string& theGroupID)
387 {
388   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroupID);
389   if (aHIter == myHistory.end()) {
390     std::vector<ObjectPtr> aResult = std::vector<ObjectPtr>();
391     // iterate the array of references and get feature by feature from the array
392     bool isFeature = theGroupID == ModelAPI_Feature::group();
393     Handle(TDataStd_ReferenceArray) aRefs;
394     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
395       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
396         FeaturePtr aFeature = feature(aRefs->Value(a));
397         if (aFeature.get()) {
398           // if feature is in sub-component, remove it from history:
399           // it is in sub-tree of sub-component
400           bool isSub = ModelAPI_Tools::compositeOwner(aFeature).get() != NULL;
401           if (isFeature) { // here may be also disabled features
402             if (!isSub && aFeature->isInHistory()) {
403               aResult.push_back(aFeature);
404             }
405           } else if (!aFeature->isDisabled()) { // iterate all results of not-disabled feature
406             // construction results of sub-features should not be in the tree
407             if (!isSub || theGroupID != ModelAPI_ResultConstruction::group()) {
408               // do not use reference to the list here since results can be changed by "isConcealed"
409               const std::list<std::shared_ptr<ModelAPI_Result> > aResults = aFeature->results();
410               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator
411                 aRIter = aResults.begin();
412               for (; aRIter != aResults.cend(); aRIter++) {
413                 ResultPtr aRes = *aRIter;
414                 if (aRes->groupName() != theGroupID) break; // feature have only same group results
415                 if (!aRes->isDisabled() && aRes->isInHistory() && !aRes->isConcealed()) {
416                   aResult.push_back(*aRIter);
417                 }
418               }
419             }
420           }
421         }
422       }
423     }
424     // to be sure that isConcealed did not update the history (issue 1089) during the iteration
425     if (myHistory.find(theGroupID) == myHistory.end())
426       myHistory[theGroupID] = aResult;
427   }
428 }
429
430 void Model_Objects::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
431 {
432   clearHistory(theObject);
433 }
434
435 void Model_Objects::updateHistory(const std::string theGroup)
436 {
437   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroup);
438   if (aHIter != myHistory.end())
439     myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
440 }
441
442 FeaturePtr Model_Objects::feature(TDF_Label theLabel) const
443 {
444   if (myFeatures.IsBound(theLabel))
445     return myFeatures.Find(theLabel);
446   return FeaturePtr();  // not found
447 }
448
449 ObjectPtr Model_Objects::object(TDF_Label theLabel)
450 {
451   // try feature by label
452   FeaturePtr aFeature = feature(theLabel);
453   if (aFeature.get())
454     return feature(theLabel);
455   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
456   aFeature = feature(aFeatureLabel);
457   bool isSubResult = false;
458   if (!aFeature.get() && aFeatureLabel.Depth() > 1) { // let's suppose this is sub-result of result
459     aFeatureLabel = aFeatureLabel.Father().Father();
460     aFeature = feature(aFeatureLabel);
461     isSubResult = true;
462   }
463   if (aFeature.get()) {
464     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
465     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
466     for (; aRIter != aResults.cend(); aRIter++) {
467       if (isSubResult) {
468         ResultCompSolidPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
469         if (aCompRes.get()) {
470           int aNumSubs = aCompRes->numberOfSubs();
471           for(int a = 0; a < aNumSubs; a++) {
472             ResultPtr aSub = aCompRes->subResult(a);
473             if (aSub.get()) {
474               std::shared_ptr<Model_Data> aSubData = std::dynamic_pointer_cast<Model_Data>(
475                   aSub->data());
476               if (aSubData->label().Father().IsEqual(theLabel))
477                 return aSub;
478             }
479           }
480         }
481       } else {
482         std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
483             (*aRIter)->data());
484         if (aResData->label().Father().IsEqual(theLabel))
485           return *aRIter;
486       }
487     }
488   }
489   return FeaturePtr();  // not found
490 }
491
492 ObjectPtr Model_Objects::object(const std::string& theGroupID, const int theIndex)
493 {
494   if (theIndex == -1)
495     return ObjectPtr();
496   createHistory(theGroupID);
497   return myHistory[theGroupID][theIndex];
498 }
499
500 std::shared_ptr<ModelAPI_Object> Model_Objects::objectByName(
501     const std::string& theGroupID, const std::string& theName)
502 {
503   createHistory(theGroupID);
504   if (theGroupID == ModelAPI_Feature::group()) { // searching among features (in history or not)
505     std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
506     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator anObjIter = allObjs.begin();
507     for(; anObjIter != allObjs.end(); anObjIter++) {
508       if ((*anObjIter)->data()->name() == theName)
509         return *anObjIter;
510     }
511   } else { // searching among results (concealed or not)
512     std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
513     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator anObjIter = allObjs.begin();
514     for(; anObjIter != allObjs.end(); anObjIter++) {
515       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = (*anObjIter)->results();
516       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
517       for (; aRIter != aResults.cend(); aRIter++) {
518         if (aRIter->get() && (*aRIter)->groupName() == theGroupID) {
519           if ((*aRIter)->data()->name() == theName)
520             return *aRIter;
521           ResultCompSolidPtr aCompRes =
522             std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
523           if (aCompRes.get()) {
524             int aNumSubs = aCompRes->numberOfSubs();
525             for(int a = 0; a < aNumSubs; a++) {
526               ResultPtr aSub = aCompRes->subResult(a);
527               if (aSub.get() && aSub->groupName() == theGroupID) {
528                 if (aSub->data()->name() == theName)
529                   return aSub;
530               }
531             }
532           }
533         }
534       }
535     }
536   }
537   // not found
538   return ObjectPtr();
539 }
540
541 const int Model_Objects::index(std::shared_ptr<ModelAPI_Object> theObject)
542 {
543   std::string aGroup = theObject->groupName();
544   createHistory(aGroup);
545   std::vector<ObjectPtr>& allObjs = myHistory[aGroup];
546   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin(); // iterate to search object
547   for(int anIndex = 0; anObjIter != allObjs.end(); anObjIter++, anIndex++) {
548     if ((*anObjIter) == theObject)
549       return anIndex;
550   }
551   // not found
552   return -1;
553 }
554
555 int Model_Objects::size(const std::string& theGroupID)
556 {
557   createHistory(theGroupID);
558   return int(myHistory[theGroupID].size());
559 }
560
561 void Model_Objects::allResults(const std::string& theGroupID, std::list<ResultPtr>& theResults)
562 {
563   // iterate the array of references and get feature by feature from the array
564   Handle(TDataStd_ReferenceArray) aRefs;
565   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
566     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
567       FeaturePtr aFeature = feature(aRefs->Value(a));
568       if (aFeature.get()) {
569         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
570         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
571         for (; aRIter != aResults.cend(); aRIter++) {
572           ResultPtr aRes = *aRIter;
573           if (aRes->groupName() != theGroupID) break; // feature have only same group results
574           // iterate also concealed: ALL RESULTS (for translation parts undo/redo management)
575           //if (aRes->isInHistory() && !aRes->isConcealed()) {
576             theResults.push_back(*aRIter);
577           //}
578         }
579       }
580     }
581   }
582 }
583
584
585 TDF_Label Model_Objects::featuresLabel() const
586 {
587   return myMain.FindChild(TAG_OBJECTS);
588 }
589
590 void Model_Objects::setUniqueName(FeaturePtr theFeature)
591 {
592   if (!theFeature->data()->name().empty())
593     return;  // not needed, name is already defined
594   std::string aName;  // result
595   // first count all features of such kind to start with index = count + 1
596   int aNumObjects = -1; // this feature is already in this map
597   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
598   for (; aFIter.More(); aFIter.Next()) {
599     if (aFIter.Value()->getKind() == theFeature->getKind())
600       aNumObjects++;
601   }
602   // generate candidate name
603   std::stringstream aNameStream;
604   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
605   aName = aNameStream.str();
606   // check this is unique, if not, increase index by 1
607   for (aFIter.Initialize(myFeatures); aFIter.More();) {
608     FeaturePtr aFeature = aFIter.Value();
609     bool isSameName = aFeature->data()->name() == aName;
610     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
611       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
612       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
613       for (; aRIter != aResults.cend(); aRIter++) {
614         isSameName = (*aRIter)->data()->name() == aName;
615       }
616     }
617
618     if (isSameName) {
619       aNumObjects++;
620       std::stringstream aNameStream;
621       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
622       aName = aNameStream.str();
623       // reinitialize iterator to make sure a new name is unique
624       aFIter.Initialize(myFeatures);
625     } else
626       aFIter.Next();
627   }
628   theFeature->data()->setName(aName);
629 }
630
631 void Model_Objects::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
632 {
633   std::shared_ptr<Model_Data> aData(new Model_Data);
634   aData->setLabel(theLab.FindChild(theTag));
635   aData->setObject(theObj);
636   theObj->setDoc(myDoc);
637   theObj->setData(aData);
638   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
639   if (aFeature.get()) {
640     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
641   }
642   theObj->initAttributes();
643 }
644
645 std::shared_ptr<ModelAPI_Feature> Model_Objects::featureById(const int theId)
646 {
647   if (theId > 0) {
648     TDF_Label aLab = featuresLabel().FindChild(theId, Standard_False);
649     return feature(aLab);
650   }
651   return std::shared_ptr<ModelAPI_Feature>(); // not found
652 }
653
654 void Model_Objects::synchronizeFeatures(
655   const TDF_LabelList& theUpdated, const bool theUpdateReferences,
656   const bool theExecuteFeatures, const bool theOpen, const bool theFlush)
657 {
658   Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
659   if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
660     return;
661   // after all updates, sends a message that groups of features were created or updated
662   Events_Loop* aLoop = Events_Loop::loop();
663   static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
664   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
665   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
666   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
667   static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
668   static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
669   bool isActive = aLoop->activateFlushes(false);
670
671   // collect all updated labels map
672   TDF_LabelMap anUpdatedMap;
673   TDF_ListIteratorOfLabelList anUpdatedIter(theUpdated);
674   for(; anUpdatedIter.More(); anUpdatedIter.Next()) {
675     TDF_Label& aFeatureLab = anUpdatedIter.Value();
676     while(aFeatureLab.Depth() > 3)
677       aFeatureLab = aFeatureLab.Father();
678     if (myFeatures.IsBound(aFeatureLab))
679       anUpdatedMap.Add(aFeatureLab);
680   }
681
682   // update all objects by checking are they on labels or not
683   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
684   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
685   for (; aLabIter.More(); aLabIter.Next()) {
686     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
687     FeaturePtr aFeature;
688     if (!myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
689       // create a feature
690       aFeature = std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get())->createFeature(
691         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
692         .ToCString(), anOwner);
693       if (!aFeature.get()) {
694         // somethig is wrong, most probably, the opened document has invalid structure
695         Events_InfoMessage("Model_Objects", "Invalid type of object in the document").send();
696         aLabIter.Value()->Label().ForgetAllAttributes();
697         continue;
698       }
699       aFeature->init();
700       // this must be before "setData" to redo the sketch line correctly
701       myFeatures.Bind(aFeatureLabel, aFeature);
702       aNewFeatures.insert(aFeature);
703       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
704       updateHistory(aFeature);
705
706       // event: model is updated
707       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
708     } else {  // nothing is changed, both iterators are incremented
709       aFeature = myFeatures.Find(aFeatureLabel);
710       aKeptFeatures.insert(aFeature);
711       if (anUpdatedMap.Contains(aFeatureLabel)) {
712         if (!theOpen) { // on abort/undo/redo reinitialize attributes if something is changed
713           std::list<std::shared_ptr<ModelAPI_Attribute> > anAttrs =
714             aFeature->data()->attributes("");
715           std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttr = anAttrs.begin();
716           for(; anAttr != anAttrs.end(); anAttr++)
717             (*anAttr)->reinit();
718         }
719         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anUpdateEvent);
720         if (aFeature->getKind() == "Parameter") {
721           // if parameters are changed, update the results (issue 937)
722           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
723           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
724           for (; aRIter != aResults.cend(); aRIter++) {
725             std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
726             if (aRes->data()->isValid() && !aRes->isDisabled()) {
727               ModelAPI_EventCreator::get()->sendUpdated(aRes, anUpdateEvent);
728             }
729           }
730         }
731       }
732     }
733   }
734
735   // check all features are checked: if not => it was removed
736   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
737   while (aFIter.More()) {
738     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
739       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
740         FeaturePtr aFeature = aFIter.Value();
741         // event: model is updated
742         //if (aFeature->isInHistory()) {
743         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
744         //}
745         // results of this feature must be redisplayed (hided)
746         // redisplay also removed feature (used for sketch and AISObject)
747         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
748         updateHistory(aFeature);
749         aFeature->erase();
750
751         // unbind after the "erase" call: on abort sketch
752         // is removes sub-objects that corrupts aFIter
753         myFeatures.UnBind(aFIter.Key());
754         // reinitialize iterator because unbind may corrupt the previous order in the map
755         aFIter.Initialize(myFeatures);
756     } else
757       aFIter.Next();
758   }
759
760   if (theUpdateReferences) {
761     synchronizeBackRefs();
762   }
763   // update results of the features (after features created because
764   // they may be connected, like sketch and sub elements)
765   // After synchronisation of back references because sketch
766   // must be set in sub-elements before "execute" by updateResults
767   std::set<FeaturePtr> aProcessed; // composites must be updated after their subs (issue 360)
768   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
769   for (; aLabIter2.More(); aLabIter2.Next()) {
770     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
771     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
772       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
773       updateResults(aFeature, aProcessed);
774     }
775   }
776   // the synchronize should be done after updateResults
777   // in order to correct back references of updated results
778   if (theUpdateReferences) {
779     synchronizeBackRefs();
780   }
781   if (!theUpdated.IsEmpty()) {
782     // this means there is no control what was modified => remove history cash
783     myHistory.clear();
784   }
785
786   if (theExecuteFeatures)
787     anOwner->executeFeatures() = false;
788   aLoop->activateFlushes(isActive);
789
790   if (theFlush) {
791     aLoop->flush(aDeleteEvent);
792     // delete should be emitted before create to reacts to aborted feature
793     aLoop->flush(aCreateEvent);
794     aLoop->flush(anUpdateEvent);
795     aLoop->flush(aCreateEvent); // after update of features, there could be results created
796     aLoop->flush(aDeleteEvent); // or deleted
797     aLoop->flush(aRedispEvent);
798     aLoop->flush(aToHideEvent);
799   }
800   if (theExecuteFeatures)
801     anOwner->executeFeatures() = true;
802 }
803
804 /// synchronises back references for the given object basing on the collected data
805 void Model_Objects::synchronizeBackRefsForObject(const std::set<AttributePtr>& theNewRefs,
806   ObjectPtr theObject)
807 {
808   if (!theObject.get() || !theObject->data()->isValid())
809     return; // invalid
810   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theObject->data());
811   // iterate new list to compare with curent
812   std::set<AttributePtr>::iterator aNewIter = theNewRefs.begin();
813   for(; aNewIter != theNewRefs.end(); aNewIter++) {
814     if (aData->refsToMe().find(*aNewIter) == aData->refsToMe().end()) {
815       FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aNewIter)->owner());
816       aData->addBackReference(aRefFeat, (*aNewIter)->id());
817     }
818   }
819   if (theNewRefs.size() != aData->refsToMe().size()) { // some back ref must be removed
820     std::set<AttributePtr>::iterator aCurrentIter = aData->refsToMe().begin();
821     while(aCurrentIter != aData->refsToMe().end()) {
822       if (theNewRefs.find(*aCurrentIter) == theNewRefs.end()) {
823         // for external references from other documents this system
824         // is not working: refs are collected from
825         // different Model_Objects, so before remove check this
826         // external object exists and still referenced
827         bool aLeaveIt = false;
828         if ((*aCurrentIter)->owner().get() && (*aCurrentIter)->owner()->document() != myDoc &&
829             (*aCurrentIter)->owner()->data().get() && (*aCurrentIter)->owner()->data()->isValid()) {
830           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
831           (*aCurrentIter)->owner()->data()->referencesToObjects(aRefs);
832           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> >>>::iterator
833             aRefIter = aRefs.begin();
834           for(; aRefIter != aRefs.end(); aRefIter++) {
835             if ((*aCurrentIter)->id() == aRefIter->first) {
836               std::list<std::shared_ptr<ModelAPI_Object> >::iterator anOIt;
837               for(anOIt = aRefIter->second.begin(); anOIt != aRefIter->second.end(); anOIt++) {
838                 if (*anOIt == theObject) {
839                   aLeaveIt = true;
840                 }
841               }
842             }
843           }
844         }
845         if (!aLeaveIt) {
846           aData->removeBackReference(*aCurrentIter);
847           aCurrentIter = aData->refsToMe().begin(); // reinitialize iteration after delete
848         } else aCurrentIter++;
849       } else aCurrentIter++;
850     }
851   }
852   aData->updateConcealmentFlag();
853 }
854
855 void Model_Objects::synchronizeBackRefs()
856 {
857   // collect all back references in the separated container: to update everything at once,
858   // without additional Concealment switchin on and off: only the final modification
859
860   // referenced (slave) objects to referencing attirbutes
861   std::map<ObjectPtr, std::set<AttributePtr> > allRefs;
862   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
863   for(; aFeatures.More(); aFeatures.Next()) {
864     FeaturePtr aFeature = aFeatures.Value();
865     std::shared_ptr<Model_Data> aFData = std::dynamic_pointer_cast<Model_Data>(aFeature->data());
866     if (aFData.get()) {
867       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
868       aFData->referencesToObjects(aRefs);
869       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIt = aRefs.begin();
870       for(; aRefsIt != aRefs.end(); aRefsIt++) {
871         std::list<ObjectPtr>::iterator aRefTo = aRefsIt->second.begin();
872         for(; aRefTo != aRefsIt->second.end(); aRefTo++) {
873           if (*aRefTo) {
874             std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = allRefs.find(*aRefTo);
875             if (aFound == allRefs.end()) {
876               allRefs[*aRefTo] = std::set<AttributePtr>();
877               aFound = allRefs.find(*aRefTo);
878             }
879             aFound->second.insert(aFeature->data()->attribute(aRefsIt->first));
880           }
881         }
882       }
883     }
884   }
885   // second iteration: just compare back-references with existing in features and results
886   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
887     FeaturePtr aFeature = aFeatures.Value();
888     static std::set<AttributePtr> anEmpty;
889     std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = allRefs.find(aFeature);
890     if (aFound == allRefs.end()) { // not found => erase all back references
891       synchronizeBackRefsForObject(anEmpty, aFeature);
892     } else {
893       synchronizeBackRefsForObject(aFound->second, aFeature);
894       allRefs.erase(aFound); // to check that all refs are counted
895     }
896     // also for results
897     std::list<ResultPtr> aResults;
898     ModelAPI_Tools::allResults(aFeature, aResults);
899     std::list<ResultPtr>::iterator aRIter = aResults.begin();
900     for(; aRIter != aResults.cend(); aRIter++) {
901       aFound = allRefs.find(*aRIter);
902       if (aFound == allRefs.end()) { // not found => erase all back references
903         synchronizeBackRefsForObject(anEmpty, *aRIter);
904       } else {
905         synchronizeBackRefsForObject(aFound->second, *aRIter);
906         allRefs.erase(aFound); // to check that all refs are counted
907       }
908     }
909   }
910   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
911     FeaturePtr aFeature = aFeatures.Value();
912     std::list<ResultPtr> aResults;
913     ModelAPI_Tools::allResults(aFeature, aResults);
914     // update the concealment status for disply in isConcealed of ResultBody
915     std::list<ResultPtr>::iterator aRIter = aResults.begin();
916     for(; aRIter != aResults.cend(); aRIter++) {
917       (*aRIter)->isConcealed();
918     }
919   }
920   // the rest all refs means that feature references to the external document feature:
921   // process also them
922   std::map<ObjectPtr, std::set<AttributePtr> >::iterator anExtIter = allRefs.begin();
923   for(; anExtIter != allRefs.end(); anExtIter++) {
924     synchronizeBackRefsForObject(anExtIter->second, anExtIter->first);
925   }
926 }
927
928 TDF_Label Model_Objects::resultLabel(
929   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
930 {
931   const std::shared_ptr<Model_Data>& aData =
932     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
933   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
934 }
935
936 bool Model_Objects::hasCustomName(DataPtr theFeatureData,
937                                   ResultPtr theResult,
938                                   int theResultIndex,
939                                   std::string& theParentName) const
940 {
941   ResultCompSolidPtr aCompSolidRes =
942       std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theFeatureData->owner());
943   if (aCompSolidRes) {
944     FeaturePtr anOwner = ModelAPI_Feature::feature(theResult->data()->owner());
945
946     // names of sub-solids in CompSolid should be default (for example,
947     // result of boolean operation 'Boolean_1' is a CompSolid which is renamed to 'MyBOOL',
948     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1', 'Boolean_1_2' etc.)
949     std::ostringstream aDefaultName;
950     aDefaultName << anOwner->name();
951     // compute default name of CompSolid (name of feature + index of CompSolid's result)
952     int aCompSolidResultIndex = 0;
953     const std::list<ResultPtr>& aResults = anOwner->results();
954     for (std::list<ResultPtr>::const_iterator anIt = aResults.begin();
955          anIt != aResults.end(); ++anIt, ++aCompSolidResultIndex)
956       if (aCompSolidRes == *anIt)
957         break;
958     aDefaultName << "_" << (aCompSolidResultIndex + 1);
959     theParentName = aDefaultName.str();
960     return false;
961   }
962
963   theParentName = ModelAPI_Tools::getDefaultName(theResult, theResultIndex);
964   return true;
965 }
966
967 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
968                                 std::shared_ptr<ModelAPI_Result> theResult,
969                                 const int theResultIndex)
970 {
971   theResult->init();
972   theResult->setDoc(myDoc);
973   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
974   if (theResult->data()->name().empty()) {
975     // if was not initialized, generate event and set a name
976     std::string aNewName = theFeatureData->name();
977     if (!hasCustomName(theFeatureData, theResult, theResultIndex, aNewName)) {
978       std::stringstream aName;
979       aName << aNewName;
980       // if there are several results (issue #899: any number of result),
981       // add unique prefix starting from second
982       if (theResultIndex > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
983         aName << "_" << theResultIndex + 1;
984       aNewName = aName.str();
985     }
986     theResult->data()->setName(aNewName);
987   }
988 }
989
990 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
991     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
992 {
993   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
994   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
995   ObjectPtr anOldObject = object(aLab);
996   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
997   if (anOldObject.get()) {
998     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
999   }
1000   if (!aResult.get()) {
1001     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1002     storeResult(theFeatureData, aResult, theIndex);
1003   }
1004   return aResult;
1005 }
1006
1007 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
1008     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1009 {
1010   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1011   // for feature create compsolid, but for result sub create body:
1012   // only one level of recursion is supported now
1013   ResultPtr aResultOwner = std::dynamic_pointer_cast<ModelAPI_Result>(theFeatureData->owner());
1014   ObjectPtr anOldObject;
1015   if (aResultOwner.get()) {
1016     TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1017   } else { // in compsolid (higher level result) old object probably may be found
1018     TDataStd_Comment::Set(aLab, ModelAPI_ResultCompSolid::group().c_str());
1019     anOldObject = object(aLab);
1020   }
1021   std::shared_ptr<ModelAPI_ResultBody> aResult;
1022   if (anOldObject.get()) {
1023     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1024   }
1025   if (!aResult.get()) {
1026     // create compsolid anyway; if it is compsolid, it will create sub-bodies internally
1027     if (aResultOwner.get()) {
1028       aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1029     } else {
1030       aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultCompSolid);
1031     }
1032     storeResult(theFeatureData, aResult, theIndex);
1033   }
1034   return aResult;
1035 }
1036
1037 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
1038     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1039 {
1040   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1041   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1042   ObjectPtr anOldObject = object(aLab);
1043   std::shared_ptr<ModelAPI_ResultPart> aResult;
1044   if (anOldObject.get()) {
1045     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1046   }
1047   if (!aResult.get()) {
1048     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1049     storeResult(theFeatureData, aResult, theIndex);
1050   }
1051   return aResult;
1052 }
1053
1054 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
1055     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1056     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1057 {
1058   std::shared_ptr<ModelAPI_ResultPart> aResult = createPart(theFeatureData, theIndex);
1059   aResult->data()->reference(Model_ResultPart::BASE_REF_ID())->setValue(theOrigin);
1060   return aResult;
1061 }
1062
1063 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
1064     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1065 {
1066   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1067   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1068   ObjectPtr anOldObject = object(aLab);
1069   std::shared_ptr<ModelAPI_ResultGroup> aResult;
1070   if (anOldObject.get()) {
1071     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1072   }
1073   if (!aResult.get()) {
1074     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1075     storeResult(theFeatureData, aResult, theIndex);
1076   }
1077   return aResult;
1078 }
1079
1080 std::shared_ptr<ModelAPI_ResultField> Model_Objects::createField(
1081     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1082 {
1083   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1084   TDataStd_Comment::Set(aLab, ModelAPI_ResultField::group().c_str());
1085   ObjectPtr anOldObject = object(aLab);
1086   std::shared_ptr<ModelAPI_ResultField> aResult;
1087   if (anOldObject.get()) {
1088     aResult = std::dynamic_pointer_cast<ModelAPI_ResultField>(anOldObject);
1089   }
1090   if (!aResult.get()) {
1091     aResult = std::shared_ptr<ModelAPI_ResultField>(new Model_ResultField(theFeatureData));
1092     storeResult(theFeatureData, aResult, theIndex);
1093   }
1094   return aResult;
1095 }
1096
1097 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
1098       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1099 {
1100   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1101   TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
1102   ObjectPtr anOldObject = object(aLab);
1103   std::shared_ptr<ModelAPI_ResultParameter> aResult;
1104   if (anOldObject.get()) {
1105     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
1106   }
1107   if (!aResult.get()) {
1108     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
1109     storeResult(theFeatureData, aResult, theIndex);
1110   }
1111   return aResult;
1112 }
1113
1114 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
1115     const std::shared_ptr<ModelAPI_Result>& theResult)
1116 {
1117   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1118   if (aData.get()) {
1119     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1120     FeaturePtr aFeature = feature(aFeatureLab);
1121     if (!aFeature.get() && aFeatureLab.Depth() > 1) { // this may be sub-result of result
1122       aFeatureLab = aFeatureLab.Father().Father();
1123       aFeature = feature(aFeatureLab);
1124     }
1125     return aFeature;
1126   }
1127   return FeaturePtr();
1128 }
1129
1130 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
1131 {
1132   if (theFeature->data()->isValid()) {
1133     TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1134     if (aLabIter.More()) {
1135       TDF_Label anArgLab = aLabIter.Value();
1136       Handle(TDataStd_Comment) aGroup;
1137       if (aLabIter.Value().FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1138         return TCollection_AsciiString(aGroup->Get()).ToCString();
1139       }
1140     }
1141   }
1142   static std::string anEmpty;
1143   return anEmpty; // not found
1144 }
1145
1146 void Model_Objects::updateResults(FeaturePtr theFeature, std::set<FeaturePtr>& theProcessed)
1147 {
1148   if (theProcessed.find(theFeature) != theProcessed.end())
1149     return;
1150   theProcessed.insert(theFeature);
1151   // for composites update subs recursively (sketch elements results are needed for the sketch)
1152   CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
1153   if (aComp.get() && aComp->getKind() != "Part") { // don't go inside of parts sub-features
1154     // update subs of composites first
1155     int aSubNum = aComp->numberOfSubs();
1156     for(int a = 0; a < aSubNum; a++) {
1157       FeaturePtr aSub = aComp->subFeature(a);
1158       updateResults(aComp->subFeature(a), theProcessed);
1159     }
1160   }
1161
1162   // for not persistent is will be done by parametric updater automatically
1163   //if (!theFeature->isPersistentResult()) return;
1164   // check the existing results and remove them if there is nothing on the label
1165   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1166   while(aResIter != theFeature->results().cend()) {
1167     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1168     if (aBody.get()) {
1169       std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(aBody->data());
1170       if (!aData.get() || !aData->isValid() || (!aBody->isDisabled() && aData->isDeleted())) {
1171         // found a disappeared result => remove it
1172         theFeature->eraseResultFromList(aBody);
1173         // start iterate from beginning because iterator is corrupted by removing
1174         aResIter = theFeature->results().cbegin();
1175         continue;
1176       }
1177     }
1178     aResIter++;
1179   }
1180   // it may be on undo
1181   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
1182     return;
1183   // check that results are presented on all labels
1184   int aResSize = int(theFeature->results().size());
1185   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1186   for(; aLabIter.More(); aLabIter.Next()) {
1187     // here must be GUID of the feature
1188     int aResIndex = aLabIter.Value().Tag() - 1;
1189     ResultPtr aNewBody;
1190     if (aResSize <= aResIndex) {
1191       TDF_Label anArgLab = aLabIter.Value();
1192       Handle(TDataStd_Comment) aGroup;
1193       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1194         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str() ||
1195             aGroup->Get() == ModelAPI_ResultCompSolid::group().c_str()) {
1196           aNewBody = createBody(theFeature->data(), aResIndex);
1197         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1198           std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex);
1199           theFeature->setResult(aNewP, aResIndex);
1200           if (!aNewP->partDoc().get())
1201             // create the part result: it is better to restore the previous result if it is possible
1202             theFeature->execute();
1203         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1204           theFeature->execute(); // construction shapes are needed for sketch solver
1205         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1206           aNewBody = createGroup(theFeature->data(), aResIndex);
1207         } else if (aGroup->Get() == ModelAPI_ResultField::group().c_str()) {
1208           aNewBody = createField(theFeature->data(), aResIndex);
1209         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
1210           theFeature->attributeChanged("expression"); // just produce a value
1211         } else {
1212           Events_InfoMessage("Model_Objects", "Unknown type of result is found in the document:")
1213             .arg(TCollection_AsciiString(aGroup->Get()).ToCString()).send();
1214         }
1215       }
1216       if (aNewBody && !aNewBody->data()->isDeleted()) {
1217         theFeature->setResult(aNewBody, aResIndex);
1218       }
1219     }
1220   }
1221 }
1222
1223 ResultPtr Model_Objects::findByName(const std::string theName)
1224 {
1225   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
1226   for(; anObjIter.More(); anObjIter.Next()) {
1227     FeaturePtr& aFeature = anObjIter.ChangeValue();
1228     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
1229       continue;
1230     std::list<ResultPtr> allResults;
1231     ModelAPI_Tools::allResults(aFeature, allResults);
1232     std::list<ResultPtr>::iterator aRIter = allResults.begin();
1233     for (; aRIter != allResults.cend(); aRIter++) {
1234       ResultPtr aRes = *aRIter;
1235       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
1236           aRes->data()->name() == theName) {
1237         return aRes;
1238       }
1239     }
1240   }
1241   // not found
1242   return ResultPtr();
1243 }
1244
1245 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, const bool theReverse)
1246 {
1247   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1248   if (aData.get() && aData->isValid()) {
1249     TDF_Label aFeatureLabel = aData->label().Father();
1250     Handle(TDataStd_ReferenceArray) aRefs;
1251     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1252       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
1253         TDF_Label aCurLab = aRefs->Value(a);
1254         if (aCurLab.IsEqual(aFeatureLabel)) {
1255           a += theReverse ? -1 : 1;
1256           if (a >= aRefs->Lower() && a <= aRefs->Upper())
1257             return feature(aRefs->Value(a));
1258           break; // finish iiteration: it's last feature
1259         }
1260       }
1261     }
1262   }
1263   return FeaturePtr(); // not found, last, or something is wrong
1264 }
1265
1266 FeaturePtr Model_Objects::firstFeature()
1267 {
1268   Handle(TDataStd_ReferenceArray) aRefs;
1269   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1270     return feature(aRefs->Value(aRefs->Lower()));
1271   }
1272   return FeaturePtr(); // no features at all
1273 }
1274
1275 FeaturePtr Model_Objects::lastFeature()
1276 {
1277   Handle(TDataStd_ReferenceArray) aRefs;
1278   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1279     return feature(aRefs->Value(aRefs->Upper()));
1280   }
1281   return FeaturePtr(); // no features at all
1282 }
1283
1284 bool Model_Objects::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
1285 {
1286   std::shared_ptr<Model_Data> aLaterD = std::static_pointer_cast<Model_Data>(theLater->data());
1287   std::shared_ptr<Model_Data> aCurrentD = std::static_pointer_cast<Model_Data>(theCurrent->data());
1288   if (aLaterD.get() && aLaterD->isValid() && aCurrentD.get() && aCurrentD->isValid()) {
1289     TDF_Label aLaterL = aLaterD->label().Father();
1290     TDF_Label aCurrentL = aCurrentD->label().Father();
1291     int aLaterI = -1, aCurentI = -1; // not found yet state
1292     Handle(TDataStd_ReferenceArray) aRefs;
1293     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1294       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
1295         TDF_Label aCurLab = aRefs->Value(a);
1296         if (aCurLab.IsEqual(aLaterL)) {
1297           aLaterI = a;
1298         } else if (aCurLab.IsEqual(aCurrentL)) {
1299           aCurentI = a;
1300         } else continue;
1301         if (aLaterI != -1 && aCurentI != -1) // both are found
1302           return aLaterI > aCurentI;
1303       }
1304     }
1305   }
1306   return false; // not found, or something is wrong
1307 }
1308
1309 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
1310 {
1311   std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
1312   Handle(TDataStd_ReferenceArray) aRefs;
1313   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1314     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
1315       FeaturePtr aFeature = feature(aRefs->Value(a));
1316       if (aFeature.get())
1317         aResult.push_back(aFeature);
1318     }
1319   }
1320   return aResult;
1321 }
1322
1323 int Model_Objects::numInternalFeatures()
1324 {
1325   Handle(TDataStd_ReferenceArray) aRefs;
1326   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1327     return aRefs->Upper() - aRefs->Lower() + 1;
1328   }
1329   return 0; // invalid
1330 }
1331
1332 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
1333 {
1334   Handle(TDataStd_ReferenceArray) aRefs;
1335   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1336     return feature(aRefs->Value(aRefs->Lower() + theIndex));
1337   }
1338   return FeaturePtr(); // invalid
1339 }
1340
1341 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1342 {
1343   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1344
1345 }
1346 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1347 {
1348   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1349 }