Salome HOME
Improve angle measurement
[modules/shaper.git] / src / ModelAPI / ModelAPI_Tools.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 "ModelAPI_Tools.h"
22 #include <ModelAPI_Session.h>
23 #include <ModelAPI_CompositeFeature.h>
24 #include <ModelAPI_Document.h>
25 #include <ModelAPI_Object.h>
26 #include <ModelAPI_AttributeDouble.h>
27 #include <ModelAPI_ResultCompSolid.h>
28 #include <ModelAPI_ResultParameter.h>
29 #include <ModelAPI_ResultPart.h>
30 #include <ModelAPI_AttributeDocRef.h>
31 #include <ModelAPI_Validator.h>
32 #include <list>
33 #include <map>
34 #include <iostream>
35 #include <sstream>
36
37 #include <Events_Loop.h>
38 #include <ModelAPI_Events.h>
39
40 #define RECURSE_TOP_LEVEL 50
41
42 //#define DEBUG_REMOVE_FEATURES
43 //#define DEBUG_REMOVE_FEATURES_RECURSE
44 //#define DEBUG_CYCLING_1550
45
46 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
47 #include <sstream>
48 std::string getFeatureInfo(FeaturePtr theFeature)
49 {
50   if (!theFeature.get())
51     return "";
52   //std::ostringstream aPtrStr;
53   //aPtrStr << "[" << theFeature.get() << "] ";
54   std::string aFeatureInfo = /*aPtrStr.str() + */theFeature->name();
55   CompositeFeaturePtr aComposite = ModelAPI_Tools::compositeOwner(theFeature);
56   if (aComposite.get()) {
57       aFeatureInfo = aFeatureInfo + "[in " + aComposite->name() + "]";
58   }
59   return aFeatureInfo;
60 }
61 #endif
62
63 #ifdef DEBUG_REMOVE_FEATURES
64 void printMapInfo(const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
65                   const std::string& thePrefix)
66 {
67   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = theMainList.begin(),
68                                                               aMainLast = theMainList.end();
69   std::string anInfo;
70   for (; aMainIt != aMainLast; aMainIt++) {
71     FeaturePtr aMainListFeature = aMainIt->first;
72     std::set<FeaturePtr> aMainRefList = aMainIt->second;
73     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(), aLast = aMainRefList.end();
74     std::string aRefsInfo;
75     for (; anIt != aLast; anIt++) {
76       aRefsInfo += (*anIt)->name().c_str();
77       if (anIt != aLast)
78         aRefsInfo += ", ";
79     }
80     if (!aRefsInfo.empty()) {
81       anInfo = anInfo + aMainListFeature->name().c_str() + ": " + aRefsInfo + "\n";
82     }
83   }
84   std::cout << thePrefix.c_str() << " [feature: references to]: \n" << anInfo.c_str() << std::endl;
85 }
86
87 void printListInfo(const std::set<FeaturePtr>& theMainList,
88                   const std::string& thePrefix)
89 {
90   std::set<FeaturePtr>::const_iterator aMainIt = theMainList.begin(),
91                                        aMainLast = theMainList.end();
92   std::string anInfo;
93   for (; aMainIt != aMainLast; aMainIt++) {
94     FeaturePtr aRefFeature = *aMainIt;
95     anInfo += aRefFeature->name().c_str();
96     if (aMainIt != aMainLast)
97       anInfo += ", ";
98   }
99   std::cout << thePrefix.c_str() << ": " << anInfo.c_str() << std::endl;
100 }
101 #endif
102
103 namespace ModelAPI_Tools {
104
105 std::shared_ptr<GeomAPI_Shape> shape(const ResultPtr& theResult)
106 {
107   return theResult->shape();
108 }
109
110 const char* toString(ModelAPI_ExecState theExecState)
111 {
112   switch (theExecState) {
113   case ModelAPI_StateDone: return "Done";
114   case ModelAPI_StateMustBeUpdated: return "Must be updated";
115   case ModelAPI_StateExecFailed: return "Execution failed";
116   case ModelAPI_StateInvalidArgument: return "Invalid argument";
117   case ModelAPI_StateNothing: return "Empty state";
118   default: return "Unknown ExecState.";
119   }
120 }
121
122 std::string getFeatureError(const FeaturePtr& theFeature)
123 {
124   std::string anError;
125   if (!theFeature.get() || !theFeature->data()->isValid() || theFeature->isAction())
126     return anError;
127
128   // to be removed later, this error should be got from the feature
129   if (theFeature->data()->execState() == ModelAPI_StateDone ||
130       theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
131     return anError;
132
133   // set error indication
134   anError = theFeature->error();
135   if (anError.empty()) {
136     bool isDone = ( theFeature->data()->execState() == ModelAPI_StateDone
137                  || theFeature->data()->execState() == ModelAPI_StateMustBeUpdated );
138     if (!isDone) {
139       anError = toString(theFeature->data()->execState());
140       // If the feature is Composite and error is StateInvalidArgument,
141       // error text should include error of first invalid sub-feature. Otherwise
142       // it is not clear what is the reason of the invalid argument.
143       if (theFeature->data()->execState() == ModelAPI_StateInvalidArgument) {
144         CompositeFeaturePtr aComposite =
145                     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
146         if (aComposite) {
147           for (int i = 0, aSize = aComposite->numberOfSubs(); i < aSize; i++) {
148             FeaturePtr aSubFeature = aComposite->subFeature(i);
149             std::string aSubFeatureError = getFeatureError(aSubFeature);
150             if (!aSubFeatureError.empty()) {
151               anError = anError + " in " + aSubFeature->getKind() + ".\n" + aSubFeatureError;
152               break;
153             }
154           }
155         }
156       }
157     }
158   }
159
160   return anError;
161 }
162
163 ObjectPtr objectByName(const DocumentPtr& theDocument, const std::string& theGroup,
164                        const std::string& theName)
165 {
166   for (int anIndex = 0; anIndex < theDocument->size(theGroup); ++anIndex) {
167     ObjectPtr anObject = theDocument->object(theGroup, anIndex);
168     if (anObject->data()->name() == theName)
169       return anObject;
170   }
171   // not found
172   return ObjectPtr();
173 }
174
175 bool findVariable(const DocumentPtr& theDocument, FeaturePtr theSearcher,
176                   const std::string& theName, double& outValue, ResultParameterPtr& theParam)
177 {
178   ObjectPtr aParamObj = objectByName(theDocument, ModelAPI_ResultParameter::group(), theName);
179   theParam = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aParamObj);
180   if (!theParam.get())
181     return false;
182   // avoid usage of parameters created later than the initial parameter
183
184   if (theSearcher.get()) {
185     FeaturePtr aParamFeat = theDocument->feature(theParam);
186     if (aParamFeat == theSearcher || theDocument->isLater(aParamFeat, theSearcher))
187       return false;
188   }
189   AttributeDoublePtr aValueAttribute = theParam->data()->real(ModelAPI_ResultParameter::VALUE());
190   outValue = aValueAttribute->value();
191   return true;
192 }
193
194 bool findVariable(FeaturePtr theSearcher, const std::string& theName, double& outValue,
195                   ResultParameterPtr& theParam, const DocumentPtr& theDocument)
196 {
197   SessionPtr aSession = ModelAPI_Session::get();
198   std::list<DocumentPtr> aDocList;
199   DocumentPtr aDocument = theDocument.get() ? theDocument : aSession->activeDocument();
200   if (findVariable(aDocument, theSearcher, theName, outValue, theParam))
201     return true;
202   DocumentPtr aRootDocument = aSession->moduleDocument();
203   if (aDocument != aRootDocument) {
204     // any parameters in PartSet is okindependently on the Part position (issu #1504)
205     if (findVariable(aRootDocument, FeaturePtr(), theName, outValue, theParam))
206       return true;
207   }
208   return false;
209 }
210
211 ResultPtr findPartResult(const DocumentPtr& theMain, const DocumentPtr& theSub)
212 {
213   // to optimize and avoid of crash on partset document close
214   // (don't touch the sub-document structure)
215   if (theMain != theSub) {
216     for (int a = theMain->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
217       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
218           theMain->object(ModelAPI_ResultPart::group(), a));
219       if (aPart && aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->value() == theSub) {
220         return aPart;
221       }
222     }
223   }
224   return ResultPtr();
225 }
226
227 FeaturePtr findPartFeature(const DocumentPtr& theMain, const DocumentPtr& theSub)
228 {
229   // to optimize and avoid of crash on partset document close
230   // (don't touch the sub-document structure)
231   if (theMain != theSub) {
232     // iteration from top to bottom to avoid finding the movement documents before the original
233     int aSize = theMain->size(ModelAPI_Feature::group());
234     for (int a = 0; a < aSize; a++) {
235       FeaturePtr aPartFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(
236           theMain->object(ModelAPI_Feature::group(), a));
237       if (aPartFeat.get()) {
238         const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aPartFeat->results();
239         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
240         for(; aRes != aResList.end(); aRes++) {
241           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
242           if (aPart.get()) {
243             if (aPart->isActivated() && aPart->partDoc() == theSub)
244               return aPartFeat;
245           } else break; // if the first is not Part, others are also not
246         }
247       }
248     }
249   }
250   return FeaturePtr();
251 }
252
253 CompositeFeaturePtr compositeOwner(const FeaturePtr& theFeature)
254 {
255   if (theFeature.get() && theFeature->data() && theFeature->data()->isValid()) {
256     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
257     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.begin();
258     for(; aRefIter != aRefs.end(); aRefIter++) {
259       CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>
260         ((*aRefIter)->owner());
261       if (aComp.get() && aComp->data()->isValid() && aComp->isSub(theFeature))
262         return aComp;
263     }
264   }
265   return CompositeFeaturePtr(); // not found
266 }
267
268 ResultCompSolidPtr compSolidOwner(const ResultPtr& theSub)
269 {
270   int anIndex;
271   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theSub);
272   if (aBody.get()) {
273     FeaturePtr aFeatureOwner = aBody->document()->feature(aBody);
274     if (aFeatureOwner.get()) {
275       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
276         aFeatureOwner->results().cbegin();
277       for(; aResIter != aFeatureOwner->results().cend(); aResIter++) {
278         ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aResIter);
279         if (aComp && aComp->isSub(aBody, anIndex))
280           return aComp;
281       }
282     }
283   }
284   return ResultCompSolidPtr(); // not found
285 }
286
287 int compSolidIndex(const ResultPtr& theSub)
288 {
289   int anIndex = -1;
290   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theSub);
291   if (aBody.get()) {
292     FeaturePtr aFeatureOwner = aBody->document()->feature(aBody);
293     if (aFeatureOwner.get()) {
294       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
295         aFeatureOwner->results().cbegin();
296       for(; aResIter != aFeatureOwner->results().cend(); aResIter++) {
297         ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aResIter);
298         if (aComp && aComp->isSub(aBody, anIndex))
299           return anIndex;
300       }
301     }
302   }
303   return anIndex; // not found
304 }
305
306 bool hasSubResults(const ResultPtr& theResult)
307 {
308   ResultCompSolidPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theResult);
309   return aCompSolid.get() && aCompSolid->numberOfSubs() > 0;
310 }
311
312 void allResults(const FeaturePtr& theFeature, std::list<ResultPtr>& theResults)
313 {
314   if (!theFeature.get()) // safety: for empty feature no results
315     return;
316   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
317   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
318   for (; aRIter != aResults.cend(); aRIter++) {
319     theResults.push_back(*aRIter);
320     // iterate sub-bodies of compsolid
321     ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
322     if (aComp.get()) {
323       int aNumSub = aComp->numberOfSubs();
324       for(int a = 0; a < aNumSub; a++) {
325         theResults.push_back(aComp->subResult(a));
326       }
327     }
328   }
329 }
330
331 //******************************************************************
332 bool allDocumentsActivated(std::string& theNotActivatedNames)
333 {
334   theNotActivatedNames = "";
335   bool anAllPartActivated = true;
336
337   DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
338   int aSize = aRootDoc->size(ModelAPI_ResultPart::group());
339   for (int i = 0; i < aSize; i++) {
340     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
341     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
342     if (!aPart->isActivated()) {
343       anAllPartActivated = false;
344       if (!theNotActivatedNames.empty())
345         theNotActivatedNames += ", ";
346       theNotActivatedNames += aObject->data()->name().c_str();
347     }
348   }
349   return anAllPartActivated;
350 }
351
352 bool removeFeaturesAndReferences(const std::set<FeaturePtr>& theFeatures,
353                                  const bool theFlushRedisplay,
354                                  const bool theUseComposite,
355                                  const bool theUseRecursion)
356 {
357 #ifdef DEBUG_REMOVE_FEATURES
358   printListInfo(theFeatures, "selection: ");
359 #endif
360
361   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
362   ModelAPI_Tools::findAllReferences(theFeatures, aReferences, theUseComposite, theUseRecursion);
363 #ifdef DEBUG_REMOVE_FEATURES
364   printMapInfo(aReferences, "allDependencies: ");
365 #endif
366
367   std::set<FeaturePtr> aFeaturesRefsTo;
368   ModelAPI_Tools::findRefsToFeatures(theFeatures, aReferences, aFeaturesRefsTo);
369 #ifdef DEBUG_REMOVE_FEATURES
370   printListInfo(aFeaturesRefsTo, "references: ");
371 #endif
372
373   std::set<FeaturePtr> aFeatures = theFeatures;
374   if (!aFeaturesRefsTo.empty())
375     aFeatures.insert(aFeaturesRefsTo.begin(), aFeaturesRefsTo.end());
376 #ifdef DEBUG_REMOVE_FEATURES
377   printListInfo(aFeatures, "removeFeatures: ");
378 #endif
379
380   return ModelAPI_Tools::removeFeatures(aFeatures, false);
381 }
382
383 //***********************************************************************
384 bool removeFeatures(const std::set<FeaturePtr>& theFeatures,
385                     const bool theFlushRedisplay)
386 {
387   bool isDone = false;
388   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
389                                        aLast = theFeatures.end();
390   for (; anIt != aLast; anIt++) {
391     FeaturePtr aFeature = *anIt;
392     if (aFeature.get()) {
393       DocumentPtr aDoc = aFeature->document();
394       // flush REDISPLAY signal after remove feature
395       aDoc->removeFeature(aFeature);
396       isDone = true;
397     }
398   }
399   if (isDone && theFlushRedisplay) {
400     // the redisplay signal should be flushed in order to erase
401     // the feature presentation in the viewer
402     // if should be done after removeFeature() of document
403     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
404   }
405   return true;
406 }
407
408 //***********************************************************************
409 // Fills the references list by all references of the feature from the references map.
410 // This is a recusive method to find references by next found feature in the map of references.
411 // \param theFeature a feature to find references
412 // \param theReferencesMap a map of references
413 // \param theReferences an out container of references
414 void addRefsToFeature(const FeaturePtr& theFeature,
415                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferencesMap,
416                       std::map<FeaturePtr, std::set<FeaturePtr> >& theProcessedReferences,
417                       int theRecLevel,
418                       std::set<FeaturePtr>& theReferences)
419 {
420   if (theRecLevel > RECURSE_TOP_LEVEL)
421     return;
422   theRecLevel++;
423
424   // if the feature is already processed, get the ready references from the map
425   if (theProcessedReferences.find(theFeature) != theProcessedReferences.end()) {
426     std::set<FeaturePtr> aReferences = theProcessedReferences.at(theFeature);
427     theReferences.insert(aReferences.begin(), aReferences.end());
428     return;
429   }
430
431   if (theReferencesMap.find(theFeature) == theReferencesMap.end())
432     return; // this feature is not in the selection list, so exists without references to it
433   std::set<FeaturePtr> aMainReferences = theReferencesMap.at(theFeature);
434
435   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
436                                        aLast = aMainReferences.end();
437 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
438   std::string aSpacing;
439   for (int i = 0; i < theRecLevel; i++)
440     aSpacing.append(" ");
441 #endif
442
443   for (; anIt != aLast; anIt++) {
444     FeaturePtr aRefFeature = *anIt;
445 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
446   std::cout << aSpacing << " Ref: " << getFeatureInfo(aRefFeature) << std::endl;
447 #endif
448     if (theReferences.find(aRefFeature) == theReferences.end())
449       theReferences.insert(aRefFeature);
450     addRefsToFeature(aRefFeature, theReferencesMap, theProcessedReferences,
451                      theRecLevel, theReferences);
452   }
453 }
454
455 // For each feature from the feature list it searches references to the feature and append them
456 // to the references map. This is a recusive method.
457 // \param theFeature a feature to find references
458 // \param theReferencesMap a map of references
459 // \param theReferences an out container of references
460 void findReferences(const std::set<FeaturePtr>& theFeatures,
461                     std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
462                     const bool theUseComposite, const bool theUseRecursion, int theRecLevel)
463 {
464   if (theRecLevel > RECURSE_TOP_LEVEL)
465     return;
466   theRecLevel++;
467   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
468                                         aLast = theFeatures.end();
469   for (; anIt != aLast; anIt++) {
470     FeaturePtr aFeature = *anIt;
471     if (aFeature.get() && theReferences.find(aFeature) == theReferences.end()) {
472       DocumentPtr aSelFeatureDoc = aFeature->document();
473       std::set<FeaturePtr> aSelRefFeatures;
474       aSelFeatureDoc->refsToFeature(aFeature, aSelRefFeatures, false/*do not emit signals*/);
475       if (theUseComposite) { // do not filter selection
476         theReferences[aFeature] = aSelRefFeatures;
477       }
478       else { // filter references to skip composition features of the current feature
479         std::set<FeaturePtr> aFilteredFeatures;
480         std::set<FeaturePtr>::const_iterator anIt = aSelRefFeatures.begin(),
481                                              aLast = aSelRefFeatures.end();
482         for (; anIt != aLast; anIt++) {
483           FeaturePtr aCFeature = *anIt;
484           CompositeFeaturePtr aComposite =
485             std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCFeature);
486           if (aComposite.get() && aComposite->isSub(aFeature))
487             continue; /// composite of the current feature should be skipped
488           aFilteredFeatures.insert(aCFeature);
489         }
490         theReferences[aFeature] = aFilteredFeatures;
491       }
492       if (theUseRecursion) {
493 #ifdef DEBUG_CYCLING_1550
494         findReferences(aSelRefFeatures, theReferences, theUseComposite,
495                        theUseRecursion, theRecLevel);
496 #else
497         findReferences(theReferences[aFeature], theReferences, theUseComposite, theUseRecursion,
498                        theRecLevel);
499 #endif
500       }
501     }
502   }
503 }
504
505 void findAllReferences(const std::set<FeaturePtr>& theFeatures,
506                        std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
507                        const bool theUseComposite,
508                        const bool theUseRecursion)
509 {
510   // For dependencies, find main_list:
511   // sk_1(ext_1, vertex_1)
512   // ext_1(bool_1, sk_3)
513   // vertex_1()
514   // sk_2(ext_2)
515   // ext_2(bool_2)
516   // sk_3()
517   // Information: bool_1 is not selected, ext_2(bool_2) exists
518   // find all referenced features
519   std::map<FeaturePtr, std::set<FeaturePtr> > aMainList;
520   int aRecLevel = 0;
521   findReferences(theFeatures, aMainList, theUseComposite, theUseRecursion, aRecLevel);
522
523 #ifdef DEBUG_REMOVE_FEATURES
524   printMapInfo(aMainList, "firstDependencies");
525 #endif
526   // find all dependencies for each object:
527   // sk_1(ext_1, vertex_1) + (sk_3, bool_1)
528   // ext_1(bool_1, sk_3)
529   // vertex_1()
530   // sk_2(ext_2) + (bool_1)
531   // ext_2(bool_1)
532   // sk_3()
533   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aMainList.begin(),
534                                                               aMainLast = aMainList.end();
535   for (; aMainIt != aMainLast; aMainIt++) {
536     FeaturePtr aMainListFeature = aMainIt->first;
537
538     //std::string aName = aMainListFeature->name();
539     std::set<FeaturePtr> aMainRefList = aMainIt->second;
540
541 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
542     char aBuf[50];
543     int n = sprintf(aBuf, "%d", aMainRefList.size());
544     std::string aSize(aBuf);
545     std::cout << "_findAllReferences for the Feature: " << getFeatureInfo(aMainListFeature)
546               << ", references size = " << aSize << std::endl;
547 #endif
548     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(),
549                                          aLast = aMainRefList.end();
550     std::set<FeaturePtr> aResultRefList;
551     aResultRefList.insert(aMainRefList.begin(), aMainRefList.end());
552     for (; anIt != aLast; anIt++) {
553       FeaturePtr aFeature = *anIt;
554       int aRecLevel = 0;
555 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
556       std::cout << " Ref: " << getFeatureInfo(aFeature) << std::endl;
557 #endif
558       aRecLevel++;
559       addRefsToFeature(aFeature, aMainList, theReferences,
560                        aRecLevel, aResultRefList/*aMainRefList*/);
561     }
562     theReferences[aMainListFeature] = aResultRefList;
563   }
564 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
565     std::cout << std::endl;
566 #endif
567
568 #ifdef DEBUG_REMOVE_FEATURES
569   printMapInfo(theReferences, "allDependencies");
570 #endif
571 }
572
573 void findRefsToFeatures(const std::set<FeaturePtr>& theFeatures,
574                         const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
575                         std::set<FeaturePtr>& theFeaturesRefsTo)
576 {
577   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
578                                        aLast = theFeatures.end();
579   for (; anIt != aLast; anIt++) {
580     FeaturePtr aFeature = *anIt;
581     if (theReferences.find(aFeature) == theReferences.end())
582       continue;
583     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
584     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
585     for (; aRefIt != aRefLast; aRefIt++) {
586       FeaturePtr aRefFeature = *aRefIt;
587       CompositeFeaturePtr aComposite =
588         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeature);
589       if (aComposite.get() && aComposite->isSub(aFeature))
590         continue; /// composite of the current feature should not be removed
591
592       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
593           theFeaturesRefsTo.find(aRefFeature) == theFeaturesRefsTo.end()) // it is not added
594         theFeaturesRefsTo.insert(aRefFeature);
595     }
596   }
597 }
598
599 void getConcealedResults(const FeaturePtr& theFeature,
600                          std::list<std::shared_ptr<ModelAPI_Result> >& theResults)
601 {
602   SessionPtr aSession = ModelAPI_Session::get();
603
604   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
605   theFeature->data()->referencesToObjects(aRefs);
606   std::list<std::pair<std::string, std::list<ObjectPtr> > >::const_iterator
607                                                   anIt = aRefs.begin(), aLast = aRefs.end();
608   std::set<ResultPtr> alreadyThere; // to avoid duplications
609   for (; anIt != aLast; anIt++) {
610     if (!aSession->validators()->isConcealed(theFeature->getKind(), anIt->first))
611       continue; // use only concealed attributes
612     std::list<ObjectPtr> anObjects = (*anIt).second;
613     std::list<ObjectPtr>::const_iterator anOIt = anObjects.begin(), anOLast = anObjects.end();
614     for (; anOIt != anOLast; anOIt++) {
615       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(*anOIt);
616       if (aResult && aResult->isConcealed()) {
617         if (alreadyThere.find(aResult) == alreadyThere.end()) // issue 1712, avoid duplicates
618           alreadyThere.insert(aResult);
619         else continue;
620         theResults.push_back(aResult);
621       }
622     }
623   }
624 }
625
626 std::pair<std::string, bool> getDefaultName(
627     const std::shared_ptr<ModelAPI_Result>& theResult,
628     const int theResultIndex)
629 {
630   typedef std::list< std::pair < std::string, std::list<ObjectPtr> > > ListOfReferences;
631
632   SessionPtr aSession = ModelAPI_Session::get();
633   FeaturePtr anOwner = ModelAPI_Feature::feature(theResult->data()->owner());
634
635   ResultCompSolidPtr aCompSolidRes = compSolidOwner(theResult);
636   if (aCompSolidRes) {
637     // names of sub-solids in CompSolid should be default (for example,
638     // result of boolean operation 'Boolean_1_1' is a CompSolid which is renamed to 'MyBOOL',
639     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1_1', 'Boolean_1_1_2' etc.)
640     std::ostringstream aDefaultName;
641     aDefaultName << anOwner->name();
642     // compute default name of CompSolid (name of feature + index of CompSolid's result)
643     int aCompSolidResultIndex = 0;
644     const std::list<ResultPtr>& aResults = anOwner->results();
645     for (std::list<ResultPtr>::const_iterator anIt = aResults.begin();
646          anIt != aResults.end(); ++anIt, ++aCompSolidResultIndex)
647       if (aCompSolidRes == *anIt)
648         break;
649     aDefaultName << "_" << (aCompSolidResultIndex + 1) << "_" << (theResultIndex + 1);
650     return std::pair<std::string, bool>(aDefaultName.str(), false);
651   }
652
653   DataPtr aData = anOwner->data();
654
655   ListOfReferences aReferences;
656   aData->referencesToObjects(aReferences);
657
658   // find first result with user-defined name
659   ListOfReferences::const_iterator aFoundRef = aReferences.end();
660   for (ListOfReferences::const_iterator aRefIt = aReferences.begin();
661        aRefIt != aReferences.end(); ++aRefIt) {
662     bool isConcealed = aSession->validators()->isConcealed(anOwner->getKind(), aRefIt->first);
663     bool isMainArg = isConcealed &&
664                      aSession->validators()->isMainArgument(anOwner->getKind(), aRefIt->first);
665     if (isConcealed) {
666       // check the referred object is a Body
667       // (for example, ExtrusionCut has a sketch as a first attribute which is concealing)
668       bool isBody = aRefIt->second.size() > 1 || (aRefIt->second.size() == 1 &&
669                     aRefIt->second.front()->groupName() == ModelAPI_ResultBody::group());
670       if (isBody && (isMainArg || aFoundRef == aReferences.end() ||
671           aData->isPrecedingAttribute(aRefIt->first, aFoundRef->first)))
672         aFoundRef = aRefIt;
673
674       if (isMainArg)
675         break;
676     }
677   }
678
679   // find an object which is concealed by theResult
680   if (aFoundRef != aReferences.end() && !aFoundRef->second.empty()) {
681     // store number of references for each object
682     std::map<ResultPtr, int> aNbRefToObject;
683     // search the object by result index
684     std::list<ObjectPtr>::const_iterator anObjIt = aFoundRef->second.begin();
685     int aResultIndex = theResultIndex;
686     while (--aResultIndex >= 0) {
687       ResultPtr aCurRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
688       ResultCompSolidPtr aParentCompSolid = ModelAPI_Tools::compSolidOwner(aCurRes);
689       if (aParentCompSolid)
690         aCurRes = aParentCompSolid;
691       if (aNbRefToObject.find(aCurRes) == aNbRefToObject.end())
692         aNbRefToObject[aCurRes] = 1;
693       else
694         aNbRefToObject[aCurRes] += 1;
695
696       ++anObjIt;
697       if (anObjIt == aFoundRef->second.end()) {
698         anObjIt = aFoundRef->second.begin();
699         break;
700       }
701     }
702     // check the result is a Body
703     if ((*anObjIt)->groupName() == ModelAPI_ResultBody::group()) {
704       // check the result is part of CompSolid
705       ResultPtr anObjRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
706       ResultCompSolidPtr aParentCompSolid = ModelAPI_Tools::compSolidOwner(anObjRes);
707       if (aParentCompSolid)
708         anObjRes = aParentCompSolid;
709
710       // return name of reference result only if it has been renamed by the user,
711       // in other case compose a default name
712       if (anObjRes->data()->hasUserDefinedName()) {
713         std::stringstream aName;
714         aName << anObjRes->data()->name();
715         std::map<ResultPtr, int>::iterator aFound = aNbRefToObject.find(anObjRes);
716         if (aFound != aNbRefToObject.end()) {
717           // to generate unique name, add suffix if there are several results
718           // referring to the same shape
719           aName << "_" << aFound->second + 1;
720         }
721         return std::pair<std::string, bool>(aName.str(), true);
722       }
723     }
724   }
725
726   // compose default name by the name of the feature and the index of result
727   std::stringstream aDefaultName;
728   aDefaultName << anOwner->name();
729   // if there are several results (issue #899: any number of result),
730   // add unique prefix starting from second
731   if (theResultIndex > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
732     aDefaultName << "_" << theResultIndex + 1;
733   return std::pair<std::string, bool>(aDefaultName.str(), false);
734 }
735
736 std::string getDefaultName(const ResultPtr& theResult)
737 {
738   FeaturePtr anOwner = ModelAPI_Feature::feature(theResult->data()->owner());
739
740   // names of sub-solids in CompSolid should be default (for example,
741   // result of boolean operation 'Boolean_1_1' is a CompSolid which is renamed to 'MyBOOL',
742   // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1_1', 'Boolean_1_1_2' etc.)
743   std::ostringstream aDefaultName;
744   aDefaultName << anOwner->name();
745
746   ResultPtr aResToSearch = theResult;
747   ResultCompSolidPtr aCompSolidRes = compSolidOwner(theResult);
748   if (aCompSolidRes)
749     aResToSearch = aCompSolidRes;
750
751   // obtain index of result
752   int aResIndex = 1;
753   const std::list<ResultPtr>& aResults = anOwner->results();
754   for (std::list<ResultPtr>::const_iterator anIt = aResults.begin();
755        anIt != aResults.end(); ++anIt, ++aResIndex)
756     if (aResToSearch == *anIt)
757       break;
758
759   // compute default name of CompSolid (name of feature + index of CompSolid's result)
760   aDefaultName << "_" << aResIndex;
761
762   if (aCompSolidRes) {
763     // obtain index of result in compsolid and compose a default name
764     int aNbSubs = aCompSolidRes->numberOfSubs();
765     for (int anIndex = 0; anIndex < aNbSubs; ++anIndex)
766       if (aCompSolidRes->subResult(anIndex) == theResult) {
767         aDefaultName << "_" << (anIndex + 1);
768         break;
769       }
770   }
771
772   return aDefaultName.str();
773 }
774
775 } // namespace ModelAPI_Tools