Salome HOME
Initial implementation of support of any level of hierarchy in Result Bodies.
[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_ResultBody.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 ResultBodyPtr bodyOwner(const ResultPtr& theSub)
269 {
270   if (theSub.get()) {
271     ObjectPtr aParent = theSub->document()->parent(theSub);
272     if (aParent.get()) {
273       return std::dynamic_pointer_cast<ModelAPI_ResultBody>(aParent);
274     }
275   }
276   return ResultBodyPtr(); // not found
277 }
278
279 int bodyIndex(const ResultPtr& theSub)
280 {
281   int anIndex = -1;
282   ResultBodyPtr aParent = bodyOwner(theSub);
283   if (aParent.get()) {
284     ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theSub);
285     if (aBody.get() && aParent->isSub(aBody, anIndex))
286       return anIndex;
287   }
288   return anIndex; // not found
289 }
290
291 bool hasSubResults(const ResultPtr& theResult)
292 {
293   ResultBodyPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
294   return aCompSolid.get() && aCompSolid->numberOfSubs() > 0;
295 }
296
297 void allSubs(const ResultBodyPtr& theResult, std::list<ResultPtr>& theResults) {
298   // iterate sub-bodies of compsolid
299   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
300   if (aComp.get()) {
301     int aNumSub = aComp->numberOfSubs();
302     for (int a = 0; a < aNumSub; a++) {
303       ResultBodyPtr aSub = aComp->subResult(a);
304       theResults.push_back(aSub);
305       allSubs(aSub, theResults);
306     }
307   }
308 }
309
310 void allResults(const FeaturePtr& theFeature, std::list<ResultPtr>& theResults)
311 {
312   if (!theFeature.get()) // safety: for empty feature no results
313     return;
314   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
315   std::list<ResultPtr>::const_iterator aRIter = aResults.begin();
316   for (; aRIter != aResults.cend(); aRIter++) {
317     theResults.push_back(*aRIter);
318     ResultBodyPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRIter);
319     allSubs(aResult, theResults);
320   }
321 }
322
323 //******************************************************************
324 bool allDocumentsActivated(std::string& theNotActivatedNames)
325 {
326   theNotActivatedNames = "";
327   bool anAllPartActivated = true;
328
329   DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
330   int aSize = aRootDoc->size(ModelAPI_ResultPart::group());
331   for (int i = 0; i < aSize; i++) {
332     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
333     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
334     if (!aPart->isActivated()) {
335       anAllPartActivated = false;
336       if (!theNotActivatedNames.empty())
337         theNotActivatedNames += ", ";
338       theNotActivatedNames += aObject->data()->name().c_str();
339     }
340   }
341   return anAllPartActivated;
342 }
343
344 bool removeFeaturesAndReferences(const std::set<FeaturePtr>& theFeatures,
345                                  const bool theFlushRedisplay,
346                                  const bool theUseComposite,
347                                  const bool theUseRecursion)
348 {
349 #ifdef DEBUG_REMOVE_FEATURES
350   printListInfo(theFeatures, "selection: ");
351 #endif
352
353   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
354   ModelAPI_Tools::findAllReferences(theFeatures, aReferences, theUseComposite, theUseRecursion);
355 #ifdef DEBUG_REMOVE_FEATURES
356   printMapInfo(aReferences, "allDependencies: ");
357 #endif
358
359   std::set<FeaturePtr> aFeaturesRefsTo;
360   ModelAPI_Tools::findRefsToFeatures(theFeatures, aReferences, aFeaturesRefsTo);
361 #ifdef DEBUG_REMOVE_FEATURES
362   printListInfo(aFeaturesRefsTo, "references: ");
363 #endif
364
365   std::set<FeaturePtr> aFeatures = theFeatures;
366   if (!aFeaturesRefsTo.empty())
367     aFeatures.insert(aFeaturesRefsTo.begin(), aFeaturesRefsTo.end());
368 #ifdef DEBUG_REMOVE_FEATURES
369   printListInfo(aFeatures, "removeFeatures: ");
370 #endif
371
372   return ModelAPI_Tools::removeFeatures(aFeatures, false);
373 }
374
375 //***********************************************************************
376 bool removeFeatures(const std::set<FeaturePtr>& theFeatures,
377                     const bool theFlushRedisplay)
378 {
379   bool isDone = false;
380   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
381                                        aLast = theFeatures.end();
382   for (; anIt != aLast; anIt++) {
383     FeaturePtr aFeature = *anIt;
384     if (aFeature.get()) {
385       DocumentPtr aDoc = aFeature->document();
386       // flush REDISPLAY signal after remove feature
387       aDoc->removeFeature(aFeature);
388       isDone = true;
389     }
390   }
391   if (isDone && theFlushRedisplay) {
392     // the redisplay signal should be flushed in order to erase
393     // the feature presentation in the viewer
394     // if should be done after removeFeature() of document
395     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
396   }
397   return true;
398 }
399
400 //***********************************************************************
401 // Fills the references list by all references of the feature from the references map.
402 // This is a recusive method to find references by next found feature in the map of references.
403 // \param theFeature a feature to find references
404 // \param theReferencesMap a map of references
405 // \param theReferences an out container of references
406 void addRefsToFeature(const FeaturePtr& theFeature,
407                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferencesMap,
408                       int theRecLevel,
409                       std::set<FeaturePtr>& theReferences)
410 {
411   if (theRecLevel > RECURSE_TOP_LEVEL)
412     return;
413   theRecLevel++;
414
415   if (theReferencesMap.find(theFeature) == theReferencesMap.end())
416     return; // this feature is not in the selection list, so exists without references to it
417   std::set<FeaturePtr> aMainReferences = theReferencesMap.at(theFeature);
418
419   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
420                                        aLast = aMainReferences.end();
421   for (; anIt != aLast; anIt++) {
422     FeaturePtr aRefFeature = *anIt;
423     if (theReferences.find(aRefFeature) == theReferences.end()) {
424       addRefsToFeature(aRefFeature, theReferencesMap, theRecLevel, theReferences);
425       theReferences.insert(aRefFeature);
426     }
427   }
428 }
429
430 // For each feature from the feature list it searches references to the feature and append them
431 // to the references map. This is a recusive method.
432 // \param theFeature a feature to find references
433 // \param theReferencesMap a map of references
434 // \param theReferences an out container of references
435 void findReferences(const std::set<FeaturePtr>& theFeatures,
436                     std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
437                     const bool theUseComposite, const bool theUseRecursion, int theRecLevel)
438 {
439   if (theRecLevel > RECURSE_TOP_LEVEL)
440     return;
441   theRecLevel++;
442   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
443                                         aLast = theFeatures.end();
444   for (; anIt != aLast; anIt++) {
445     FeaturePtr aFeature = *anIt;
446     if (aFeature.get() && theReferences.find(aFeature) == theReferences.end()) {
447       DocumentPtr aSelFeatureDoc = aFeature->document();
448       std::set<FeaturePtr> aSelRefFeatures;
449       aSelFeatureDoc->refsToFeature(aFeature, aSelRefFeatures, false/*do not emit signals*/);
450       if (theUseComposite) { // do not filter selection
451         theReferences[aFeature] = aSelRefFeatures;
452       }
453       else { // filter references to skip composition features of the current feature
454         std::set<FeaturePtr> aFilteredFeatures;
455         std::set<FeaturePtr>::const_iterator anIt = aSelRefFeatures.begin(),
456                                              aLast = aSelRefFeatures.end();
457         for (; anIt != aLast; anIt++) {
458           FeaturePtr aCFeature = *anIt;
459           CompositeFeaturePtr aComposite =
460             std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCFeature);
461           if (aComposite.get() && aComposite->isSub(aFeature))
462             continue; /// composite of the current feature should be skipped
463           aFilteredFeatures.insert(aCFeature);
464         }
465         theReferences[aFeature] = aFilteredFeatures;
466       }
467       if (theUseRecursion) {
468 #ifdef DEBUG_CYCLING_1550
469         findReferences(aSelRefFeatures, theReferences, theUseComposite,
470                        theUseRecursion, theRecLevel);
471 #else
472         findReferences(theReferences[aFeature], theReferences, theUseComposite, theUseRecursion,
473                        theRecLevel);
474 #endif
475       }
476     }
477   }
478 }
479
480 void findAllReferences(const std::set<FeaturePtr>& theFeatures,
481                        std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
482                        const bool theUseComposite,
483                        const bool theUseRecursion)
484 {
485   // For dependencies, find main_list:
486   // sk_1(ext_1, vertex_1)
487   // ext_1(bool_1, sk_3)
488   // vertex_1()
489   // sk_2(ext_2)
490   // ext_2(bool_2)
491   // sk_3()
492   // Information: bool_1 is not selected, ext_2(bool_2) exists
493   // find all referenced features
494   std::map<FeaturePtr, std::set<FeaturePtr> > aMainList;
495   int aRecLevel = 0;
496   findReferences(theFeatures, aMainList, theUseComposite, theUseRecursion, aRecLevel);
497
498 #ifdef DEBUG_REMOVE_FEATURES
499   printMapInfo(aMainList, "firstDependencies");
500 #endif
501   // find all dependencies for each object:
502   // sk_1(ext_1, vertex_1) + (sk_3, bool_1)
503   // ext_1(bool_1, sk_3)
504   // vertex_1()
505   // sk_2(ext_2) + (bool_1)
506   // ext_2(bool_1)
507   // sk_3()
508   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aMainList.begin(),
509                                                               aMainLast = aMainList.end();
510   for (; aMainIt != aMainLast; aMainIt++) {
511     FeaturePtr aMainListFeature = aMainIt->first;
512
513     //std::string aName = aMainListFeature->name();
514     std::set<FeaturePtr> aMainRefList = aMainIt->second;
515
516 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
517     char aBuf[50];
518     int n = sprintf(aBuf, "%d", aMainRefList.size());
519     std::string aSize(aBuf);
520     std::cout << "_findAllReferences for the Feature: " << getFeatureInfo(aMainListFeature)
521               << ", references size = " << aSize << std::endl;
522 #endif
523     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(),
524                                          aLast = aMainRefList.end();
525     std::set<FeaturePtr> aResultRefList;
526     aResultRefList.insert(aMainRefList.begin(), aMainRefList.end());
527     for (; anIt != aLast; anIt++) {
528       FeaturePtr aFeature = *anIt;
529       int aRecLevel = 0;
530 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
531       std::cout << " Ref: " << getFeatureInfo(aFeature) << std::endl;
532 #endif
533       aRecLevel++;
534       addRefsToFeature(aFeature, aMainList,
535                        aRecLevel, aResultRefList/*aMainRefList*/);
536     }
537     theReferences[aMainListFeature] = aResultRefList;
538   }
539 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
540     std::cout << std::endl;
541 #endif
542
543 #ifdef DEBUG_REMOVE_FEATURES
544   printMapInfo(theReferences, "allDependencies");
545 #endif
546 }
547
548 void findRefsToFeatures(const std::set<FeaturePtr>& theFeatures,
549                         const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
550                         std::set<FeaturePtr>& theFeaturesRefsTo)
551 {
552   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
553                                        aLast = theFeatures.end();
554   for (; anIt != aLast; anIt++) {
555     FeaturePtr aFeature = *anIt;
556     if (theReferences.find(aFeature) == theReferences.end())
557       continue;
558     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
559     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
560     for (; aRefIt != aRefLast; aRefIt++) {
561       FeaturePtr aRefFeature = *aRefIt;
562       CompositeFeaturePtr aComposite =
563         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeature);
564       if (aComposite.get() && aComposite->isSub(aFeature))
565         continue; /// composite of the current feature should not be removed
566
567       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
568           theFeaturesRefsTo.find(aRefFeature) == theFeaturesRefsTo.end()) // it is not added
569         theFeaturesRefsTo.insert(aRefFeature);
570     }
571   }
572 }
573
574 void getConcealedResults(const FeaturePtr& theFeature,
575                          std::list<std::shared_ptr<ModelAPI_Result> >& theResults)
576 {
577   SessionPtr aSession = ModelAPI_Session::get();
578
579   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
580   theFeature->data()->referencesToObjects(aRefs);
581   std::list<std::pair<std::string, std::list<ObjectPtr> > >::const_iterator
582                                                   anIt = aRefs.begin(), aLast = aRefs.end();
583   std::set<ResultPtr> alreadyThere; // to avoid duplications
584   for (; anIt != aLast; anIt++) {
585     if (!aSession->validators()->isConcealed(theFeature->getKind(), anIt->first))
586       continue; // use only concealed attributes
587     std::list<ObjectPtr> anObjects = (*anIt).second;
588     std::list<ObjectPtr>::const_iterator anOIt = anObjects.begin(), anOLast = anObjects.end();
589     for (; anOIt != anOLast; anOIt++) {
590       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(*anOIt);
591       if (aResult && aResult->isConcealed()) {
592         if (alreadyThere.find(aResult) == alreadyThere.end()) // issue 1712, avoid duplicates
593           alreadyThere.insert(aResult);
594         else continue;
595         theResults.push_back(aResult);
596       }
597     }
598   }
599 }
600
601 std::pair<std::string, bool> getDefaultName(const std::shared_ptr<ModelAPI_Result>& theResult)
602 {
603   typedef std::list< std::pair < std::string, std::list<ObjectPtr> > > ListOfReferences;
604
605   SessionPtr aSession = ModelAPI_Session::get();
606
607   ResultBodyPtr anOwnerRes = bodyOwner(theResult);
608   if (anOwnerRes) {
609     // names of sub-solids in CompSolid should be default (for example,
610     // result of boolean operation 'Boolean_1_1' is a CompSolid which is renamed to 'MyBOOL',
611     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1_1', 'Boolean_1_1_2' etc.)
612     std::ostringstream aDefaultName;
613     aDefaultName << getDefaultName(anOwnerRes).first;
614     aDefaultName << "_" << (bodyIndex(theResult) + 1);
615     return std::pair<std::string, bool>(aDefaultName.str(), false);
616   }
617
618   FeaturePtr anOwner = ModelAPI_Feature::feature(theResult->data()->owner());
619   DataPtr aData = anOwner->data();
620
621   ListOfReferences aReferences;
622   aData->referencesToObjects(aReferences);
623
624   // find first result with user-defined name
625   ListOfReferences::const_iterator aFoundRef = aReferences.end();
626   for (ListOfReferences::const_iterator aRefIt = aReferences.begin();
627        aRefIt != aReferences.end(); ++aRefIt) {
628     bool isConcealed = aSession->validators()->isConcealed(anOwner->getKind(), aRefIt->first);
629     bool isMainArg = isConcealed &&
630                      aSession->validators()->isMainArgument(anOwner->getKind(), aRefIt->first);
631     if (isConcealed) {
632       // check the referred object is a Body
633       // (for example, ExtrusionCut has a sketch as a first attribute which is concealing)
634       bool isBody = aRefIt->second.size() > 1 || (aRefIt->second.size() == 1 &&
635                     aRefIt->second.front()->groupName() == ModelAPI_ResultBody::group());
636       if (isBody && (isMainArg || aFoundRef == aReferences.end() ||
637           aData->isPrecedingAttribute(aRefIt->first, aFoundRef->first)))
638         aFoundRef = aRefIt;
639
640       if (isMainArg)
641         break;
642     }
643   }
644   // get the result number in the feature
645   int anIndexInOwner = 0;
646   const std::list<ResultPtr>& anOwnerResults = anOwner->results();
647   std::list<ResultPtr>::const_iterator aResIt = anOwnerResults.cbegin();
648   for(; aResIt != anOwnerResults.cend(); aResIt++) {
649     if(*aResIt == theResult)
650       break;
651     anIndexInOwner++;
652   }
653
654   // find an object which is concealed by theResult
655   if (aFoundRef != aReferences.end() && !aFoundRef->second.empty()) {
656     // store number of references for each object
657     std::map<ResultPtr, int> aNbRefToObject;
658     // search the object by result index
659     std::list<ObjectPtr>::const_iterator anObjIt = aFoundRef->second.begin();
660     int aResultIndex = anIndexInOwner;
661     while (--aResultIndex >= 0) {
662       ResultPtr aCurRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
663       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(aCurRes);
664       if (aParentBody)
665         aCurRes = aParentBody;
666       if (aNbRefToObject.find(aCurRes) == aNbRefToObject.end())
667         aNbRefToObject[aCurRes] = 1;
668       else
669         aNbRefToObject[aCurRes] += 1;
670
671       ++anObjIt;
672       if (anObjIt == aFoundRef->second.end()) {
673         anObjIt = aFoundRef->second.begin();
674         break;
675       }
676     }
677     // check the result is a Body
678     if ((*anObjIt)->groupName() == ModelAPI_ResultBody::group()) {
679       // check the result is part of CompSolid
680       ResultPtr anObjRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
681       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(anObjRes);
682       if (aParentBody)
683         anObjRes = aParentBody;
684
685       // return name of reference result only if it has been renamed by the user,
686       // in other case compose a default name
687       if (anObjRes->data()->hasUserDefinedName()) {
688         std::stringstream aName;
689         aName << anObjRes->data()->name();
690         std::map<ResultPtr, int>::iterator aFound = aNbRefToObject.find(anObjRes);
691         if (aFound != aNbRefToObject.end()) {
692           // to generate unique name, add suffix if there are several results
693           // referring to the same shape
694           aName << "_" << aFound->second + 1;
695         }
696         return std::pair<std::string, bool>(aName.str(), true);
697       }
698     }
699   }
700
701   // compose default name by the name of the feature and the index of result
702   std::stringstream aDefaultName;
703   aDefaultName << anOwner->name();
704   // if there are several results (issue #899: any number of result),
705   // add unique prefix starting from second
706   if (anIndexInOwner > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
707     aDefaultName << "_" << anIndexInOwner + 1;
708   return std::pair<std::string, bool>(aDefaultName.str(), false);
709 }
710
711 } // namespace ModelAPI_Tools