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