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