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