Salome HOME
Fix compilation warnings
[modules/shaper.git] / src / ModelAPI / ModelAPI_Tools.cpp
1 // Copyright (C) 2014-2021  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 email : webmaster.salome@opencascade.com
18 //
19
20 #include <ModelAPI_AttributeBoolean.h>
21 #include <ModelAPI_AttributeDocRef.h>
22 #include <ModelAPI_AttributeDouble.h>
23 #include <ModelAPI_AttributeIntArray.h>
24 #include <ModelAPI_AttributeSelectionList.h>
25 #include <ModelAPI_CompositeFeature.h>
26 #include <ModelAPI_Document.h>
27 #include <ModelAPI_Events.h>
28 #include <ModelAPI_Object.h>
29 #include <ModelAPI_ResultBody.h>
30 #include <ModelAPI_ResultConstruction.h>
31 #include <ModelAPI_ResultGroup.h>
32 #include <ModelAPI_ResultParameter.h>
33 #include <ModelAPI_ResultPart.h>
34 #include <ModelAPI_Session.h>
35 #include "ModelAPI_Tools.h"
36 #include <ModelAPI_Validator.h>
37
38 #include <Config_Translator.h>
39 #include <Events_Loop.h>
40 #include <Locale_Convert.h>
41
42 #include <GeomAPI_ShapeHierarchy.h>
43 #include <GeomAPI_ShapeIterator.h>
44
45 #include <algorithm>
46 #include <iostream>
47 #include <list>
48 #include <map>
49 #include <sstream>
50 #include <vector>
51 #include <array>
52
53 #define RECURSE_TOP_LEVEL 50
54
55 //#define DEBUG_REMOVE_FEATURES
56 //#define DEBUG_REMOVE_FEATURES_RECURSE
57 //#define DEBUG_CYCLING_1550
58
59 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
60 #include <sstream>
61 std::string getFeatureInfo(FeaturePtr theFeature)
62 {
63   if (!theFeature.get())
64     return "";
65   //std::ostringstream aPtrStr;
66   //aPtrStr << "[" << theFeature.get() << "] ";
67   std::string aFeatureInfo = /*aPtrStr.str() + */theFeature->name();
68   CompositeFeaturePtr aComposite = ModelAPI_Tools::compositeOwner(theFeature);
69   if (aComposite.get()) {
70       aFeatureInfo = aFeatureInfo + "[in " + aComposite->name() + "]";
71   }
72   return aFeatureInfo;
73 }
74 #endif
75
76 #ifdef DEBUG_REMOVE_FEATURES
77 void printMapInfo(const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
78                   const std::string& thePrefix)
79 {
80   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = theMainList.begin(),
81                                                               aMainLast = theMainList.end();
82   std::string anInfo;
83   for (; aMainIt != aMainLast; aMainIt++) {
84     FeaturePtr aMainListFeature = aMainIt->first;
85     std::set<FeaturePtr> aMainRefList = aMainIt->second;
86     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(), aLast = aMainRefList.end();
87     std::string aRefsInfo;
88     for (; anIt != aLast; anIt++) {
89       aRefsInfo += (*anIt)->name().c_str();
90       if (anIt != aLast)
91         aRefsInfo += ", ";
92     }
93     if (!aRefsInfo.empty()) {
94       anInfo = anInfo + aMainListFeature->name().c_str() + ": " + aRefsInfo + "\n";
95     }
96   }
97   std::cout << thePrefix.c_str() << " [feature: references to]: \n" << anInfo.c_str() << std::endl;
98 }
99
100 void printListInfo(const std::set<FeaturePtr>& theMainList,
101                   const std::string& thePrefix)
102 {
103   std::set<FeaturePtr>::const_iterator aMainIt = theMainList.begin(),
104                                        aMainLast = theMainList.end();
105   std::string anInfo;
106   for (; aMainIt != aMainLast; aMainIt++) {
107     FeaturePtr aRefFeature = *aMainIt;
108     anInfo += aRefFeature->name().c_str();
109     if (aMainIt != aMainLast)
110       anInfo += ", ";
111   }
112   std::cout << thePrefix.c_str() << ": " << anInfo.c_str() << std::endl;
113 }
114 #endif
115
116 namespace ModelAPI_Tools {
117
118 std::shared_ptr<GeomAPI_Shape> shape(const ResultPtr& theResult)
119 {
120   return theResult->shape();
121 }
122
123 // LCOV_EXCL_START
124 const char* toString(ModelAPI_ExecState theExecState)
125 {
126   switch (theExecState) {
127   case ModelAPI_StateDone: return "Done";
128   case ModelAPI_StateMustBeUpdated: return "Must be updated";
129   case ModelAPI_StateExecFailed: return "Execution failed";
130   case ModelAPI_StateInvalidArgument: return "Invalid argument";
131   case ModelAPI_StateNothing: return "Empty state";
132   default: return "Unknown ExecState.";
133   }
134 }
135
136 std::string getFeatureError(const FeaturePtr& theFeature)
137 {
138   std::string anError;
139   if (!theFeature.get() || !theFeature->data()->isValid() || theFeature->isAction())
140     return anError;
141
142   // to be removed later, this error should be got from the feature
143   if (theFeature->data()->execState() == ModelAPI_StateDone ||
144       theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
145     return anError;
146
147   // set error indication
148   anError = theFeature->error();
149   if (anError.empty()) {
150     bool isDone = ( theFeature->data()->execState() == ModelAPI_StateDone
151                  || theFeature->data()->execState() == ModelAPI_StateMustBeUpdated );
152     if (!isDone) {
153       anError = toString(theFeature->data()->execState());
154       // If the feature is Composite and error is StateInvalidArgument,
155       // error text should include error of first invalid sub-feature. Otherwise
156       // it is not clear what is the reason of the invalid argument.
157       if (theFeature->data()->execState() == ModelAPI_StateInvalidArgument) {
158         CompositeFeaturePtr aComposite =
159                     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
160         if (aComposite) {
161           bool aHasSubError = false;
162           for (int i = 0, aSize = aComposite->numberOfSubs(); i < aSize; i++) {
163             FeaturePtr aSubFeature = aComposite->subFeature(i);
164             std::string aSubFeatureError = getFeatureError(aSubFeature);
165             if (!aSubFeatureError.empty()) {
166               anError = anError + " in " + aSubFeature->getKind() + ".\n" + aSubFeatureError;
167               aHasSubError = true;
168               break;
169             }
170           }
171           if (!aHasSubError) { // #24260: error not in the sub-features, but in the argument
172             if (aComposite->getKind() == "Sketch" &&
173                 aComposite->selection("External")->isInvalid()) {
174               std::string aMsg = "The sketch base plane is invalid, ";
175               aMsg += "please push 'Change sketch plane' button to reselect it.";
176               anError = Config_Translator::translate(aComposite->getKind(), aMsg);
177             }
178           }
179         }
180       }
181     }
182   }
183
184   return anError;
185 }
186 // LCOV_EXCL_STOP
187
188 ObjectPtr objectByName(const DocumentPtr& theDocument, const std::string& theGroup,
189                        const std::wstring& theName)
190 {
191   for (int anIndex = 0; anIndex < theDocument->size(theGroup); ++anIndex) {
192     ObjectPtr anObject = theDocument->object(theGroup, anIndex);
193     if (anObject->data()->name() == theName)
194       return anObject;
195   }
196   // not found
197   return ObjectPtr();
198 }
199
200 bool findVariable(const DocumentPtr& theDocument, FeaturePtr theSearcher,
201                   const std::wstring& theName, double& outValue, ResultParameterPtr& theParam)
202 {
203   ObjectPtr aParamObj = objectByName(theDocument, ModelAPI_ResultParameter::group(), theName);
204   theParam = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aParamObj);
205   if (!theParam.get())
206     return false;
207   // avoid usage of parameters created later than the initial parameter
208
209   if (theSearcher.get()) {
210     FeaturePtr aParamFeat = theDocument->feature(theParam);
211     if (aParamFeat == theSearcher || theDocument->isLater(aParamFeat, theSearcher))
212       return false;
213   }
214   AttributeDoublePtr aValueAttribute = theParam->data()->real(ModelAPI_ResultParameter::VALUE());
215   outValue = aValueAttribute->value();
216   return true;
217 }
218
219 bool findVariable(FeaturePtr theSearcher, const std::wstring& theName, double& outValue,
220                   ResultParameterPtr& theParam, const DocumentPtr& theDocument)
221 {
222   SessionPtr aSession = ModelAPI_Session::get();
223   std::list<DocumentPtr> aDocList;
224   DocumentPtr aDocument = theDocument.get() ? theDocument : aSession->activeDocument();
225   if (findVariable(aDocument, theSearcher, theName, outValue, theParam))
226     return true;
227   DocumentPtr aRootDocument = aSession->moduleDocument();
228   if (aDocument != aRootDocument) {
229     // any parameters in PartSet is okindependently on the Part position (issu #1504)
230     if (findVariable(aRootDocument, FeaturePtr(), theName, outValue, theParam))
231       return true;
232   }
233   return false;
234 }
235
236 ResultPtr findPartResult(const DocumentPtr& theMain, const DocumentPtr& theSub)
237 {
238   // to optimize and avoid of crash on partset document close
239   // (don't touch the sub-document structure)
240   if (theMain != theSub) {
241     for (int a = theMain->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
242       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
243           theMain->object(ModelAPI_ResultPart::group(), a));
244       if (aPart && aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->value() == theSub) {
245         return aPart;
246       }
247     }
248   }
249   return ResultPtr();
250 }
251
252 FeaturePtr findPartFeature(const DocumentPtr& theMain, const DocumentPtr& theSub)
253 {
254   // to optimize and avoid of crash on partset document close
255   // (don't touch the sub-document structure)
256   if (theMain != theSub) {
257     // iteration from top to bottom to avoid finding the movement documents before the original
258     int aSize = theMain->size(ModelAPI_Feature::group());
259     for (int a = 0; a < aSize; a++) {
260       FeaturePtr aPartFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(
261           theMain->object(ModelAPI_Feature::group(), a));
262       if (aPartFeat.get()) {
263         const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aPartFeat->results();
264         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
265         for(; aRes != aResList.end(); aRes++) {
266           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
267           if (aPart.get()) {
268             if (aPart->isActivated() && aPart->partDoc() == theSub)
269               return aPartFeat;
270           } else break; // if the first is not Part, others are also not
271         }
272       }
273     }
274   }
275   return FeaturePtr();
276 }
277
278 CompositeFeaturePtr compositeOwner(const FeaturePtr& theFeature)
279 {
280   if (theFeature.get() && theFeature->data() && theFeature->data()->isValid()) {
281     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
282     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.begin();
283     for(; aRefIter != aRefs.end(); aRefIter++) {
284       CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>
285         ((*aRefIter)->owner());
286       if (aComp.get() && aComp->data()->isValid() && aComp->isSub(theFeature))
287         return aComp;
288     }
289   }
290   return CompositeFeaturePtr(); // not found
291 }
292
293 ResultBodyPtr bodyOwner(const ResultPtr& theSub, const bool theRoot)
294 {
295   if (theSub.get()) {
296     ObjectPtr aParent = theSub->document()->parent(theSub);
297     if (aParent.get()) {
298       if (theRoot) { // try to find parent of parent
299         ResultPtr aResultParent = std::dynamic_pointer_cast<ModelAPI_Result>(aParent);
300         ResultBodyPtr aGrandParent = bodyOwner(aResultParent, true);
301         if (aGrandParent.get())
302           aParent = aGrandParent;
303       }
304       return std::dynamic_pointer_cast<ModelAPI_ResultBody>(aParent);
305     }
306   }
307   return ResultBodyPtr(); // not found
308 }
309
310 int bodyIndex(const ResultPtr& theSub)
311 {
312   int anIndex = -1;
313   ResultBodyPtr aParent = bodyOwner(theSub);
314   if (aParent.get()) {
315     ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theSub);
316     if (aBody.get() && aParent->isSub(aBody, anIndex))
317       return anIndex;
318   }
319   return anIndex; // not found
320 }
321
322 bool hasSubResults(const ResultPtr& theResult)
323 {
324   ResultBodyPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
325   return aCompSolid.get() && aCompSolid->numberOfSubs() > 0;
326 }
327
328 void allSubs(const ResultBodyPtr& theResult, std::list<ResultPtr>& theResults,
329              const bool theLowerOnly) {
330   // iterate sub-bodies of compsolid
331   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
332   if (aComp.get()) {
333     int aNumSub = aComp->numberOfSubs();
334     for (int a = 0; a < aNumSub; a++) {
335       ResultBodyPtr aSub = aComp->subResult(a);
336       if (!theLowerOnly || aSub->numberOfSubs() == 0)
337         theResults.push_back(aSub);
338       allSubs(aSub, theResults);
339     }
340   }
341 }
342
343 void allResults(const FeaturePtr& theFeature, std::list<ResultPtr>& theResults)
344 {
345   if (!theFeature.get()) // safety: for empty feature no results
346     return;
347   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
348   std::list<ResultPtr>::const_iterator aRIter = aResults.begin();
349   for (; aRIter != aResults.cend(); aRIter++) {
350     theResults.push_back(*aRIter);
351     ResultBodyPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRIter);
352     allSubs(aResult, theResults);
353   }
354 }
355
356 //******************************************************************
357 bool allDocumentsActivated(std::wstring& theNotActivatedNames)
358 {
359   theNotActivatedNames = L"";
360   bool anAllPartActivated = true;
361
362   DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
363   int aSize = aRootDoc->size(ModelAPI_ResultPart::group());
364   for (int i = 0; i < aSize; i++) {
365     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
366     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
367     if (!aPart->isActivated()) {
368       anAllPartActivated = false;
369       if (!theNotActivatedNames.empty())
370         theNotActivatedNames += L", ";
371       theNotActivatedNames += aObject->data()->name().c_str();
372     }
373   }
374   return anAllPartActivated;
375 }
376
377 bool removeFeaturesAndReferences(const std::set<FeaturePtr>& theFeatures,
378                                  const bool /*theFlushRedisplay*/,
379                                  const bool theUseComposite,
380                                  const bool theUseRecursion)
381 {
382 #ifdef DEBUG_REMOVE_FEATURES
383   printListInfo(theFeatures, "selection: ");
384 #endif
385
386   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
387   ModelAPI_Tools::findAllReferences(theFeatures, aReferences, theUseComposite, theUseRecursion);
388 #ifdef DEBUG_REMOVE_FEATURES
389   printMapInfo(aReferences, "allDependencies: ");
390 #endif
391
392   std::set<FeaturePtr> aFeaturesRefsTo;
393   ModelAPI_Tools::findRefsToFeatures(theFeatures, aReferences, aFeaturesRefsTo);
394 #ifdef DEBUG_REMOVE_FEATURES
395   printListInfo(aFeaturesRefsTo, "references: ");
396 #endif
397
398   std::set<FeaturePtr> aFeatures = theFeatures;
399   if (!aFeaturesRefsTo.empty())
400     aFeatures.insert(aFeaturesRefsTo.begin(), aFeaturesRefsTo.end());
401 #ifdef DEBUG_REMOVE_FEATURES
402   printListInfo(aFeatures, "removeFeatures: ");
403 #endif
404
405   return ModelAPI_Tools::removeFeatures(aFeatures, false);
406 }
407
408 //***********************************************************************
409 bool removeFeatures(const std::set<FeaturePtr>& theFeatures,
410                     const bool theFlushRedisplay)
411 {
412   bool isDone = false;
413   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
414                                        aLast = theFeatures.end();
415   for (; anIt != aLast; anIt++) {
416     FeaturePtr aFeature = *anIt;
417     if (aFeature.get()) {
418       DocumentPtr aDoc = aFeature->document();
419       // flush REDISPLAY signal after remove feature
420       aDoc->removeFeature(aFeature);
421       isDone = true;
422     }
423   }
424   if (isDone && theFlushRedisplay) {
425     // the redisplay signal should be flushed in order to erase
426     // the feature presentation in the viewer
427     // if should be done after removeFeature() of document
428     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
429   }
430   return true;
431 }
432
433 //***********************************************************************
434 // Fills the references list by all references of the feature from the references map.
435 // This is a recusive method to find references by next found feature in the map of references.
436 // \param theFeature a feature to find references
437 // \param theReferencesMap a map of references
438 // \param theReferences an out container of references
439 void addRefsToFeature(const FeaturePtr& theFeature,
440                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferencesMap,
441                       int theRecLevel,
442                       std::set<FeaturePtr>& theReferences)
443 {
444   if (theRecLevel > RECURSE_TOP_LEVEL)
445     return;
446   theRecLevel++;
447
448   if (theReferencesMap.find(theFeature) == theReferencesMap.end())
449     return; // this feature is not in the selection list, so exists without references to it
450   std::set<FeaturePtr> aMainReferences = theReferencesMap.at(theFeature);
451
452   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
453                                        aLast = aMainReferences.end();
454   for (; anIt != aLast; anIt++) {
455     FeaturePtr aRefFeature = *anIt;
456     if (theReferences.find(aRefFeature) == theReferences.end()) {
457       addRefsToFeature(aRefFeature, theReferencesMap, theRecLevel, theReferences);
458       theReferences.insert(aRefFeature);
459     }
460   }
461 }
462
463 // For each feature from the feature list it searches references to the feature and append them
464 // to the references map. This is a recusive method.
465 // \param theFeature a feature to find references
466 // \param theReferencesMap a map of references
467 // \param theReferences an out container of references
468 void findReferences(const std::set<FeaturePtr>& theFeatures,
469                     std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
470                     const bool theUseComposite, const bool theUseRecursion, int theRecLevel)
471 {
472   if (theRecLevel > RECURSE_TOP_LEVEL)
473     return;
474   theRecLevel++;
475   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
476                                         aLast = theFeatures.end();
477   for (; anIt != aLast; anIt++) {
478     FeaturePtr aFeature = *anIt;
479     if (aFeature.get() && theReferences.find(aFeature) == theReferences.end()) {
480       DocumentPtr aSelFeatureDoc = aFeature->document();
481       std::set<FeaturePtr> aSelRefFeatures;
482       aSelFeatureDoc->refsToFeature(aFeature, aSelRefFeatures, false/*do not emit signals*/);
483       if (theUseComposite) { // do not filter selection
484         theReferences[aFeature] = aSelRefFeatures;
485       }
486       else { // filter references to skip composition features of the current feature
487         std::set<FeaturePtr> aFilteredFeatures;
488         std::set<FeaturePtr>::const_iterator aRefIt = aSelRefFeatures.begin(),
489                                              aRefLast = aSelRefFeatures.end();
490         for (; aRefIt != aRefLast; aRefIt++) {
491           FeaturePtr aCFeature = *aRefIt;
492           CompositeFeaturePtr aComposite =
493             std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCFeature);
494           if (aComposite.get() && aComposite->isSub(aFeature))
495             continue; /// composite of the current feature should be skipped
496           aFilteredFeatures.insert(aCFeature);
497         }
498         theReferences[aFeature] = aFilteredFeatures;
499       }
500       if (theUseRecursion) {
501 #ifdef DEBUG_CYCLING_1550
502         findReferences(aSelRefFeatures, theReferences, theUseComposite,
503                        theUseRecursion, theRecLevel);
504 #else
505         findReferences(theReferences[aFeature], theReferences, theUseComposite, theUseRecursion,
506                        theRecLevel);
507 #endif
508       }
509     }
510   }
511 }
512
513 void findAllReferences(const std::set<FeaturePtr>& theFeatures,
514                        std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
515                        const bool theUseComposite,
516                        const bool theUseRecursion)
517 {
518   // For dependencies, find main_list:
519   // sk_1(ext_1, vertex_1)
520   // ext_1(bool_1, sk_3)
521   // vertex_1()
522   // sk_2(ext_2)
523   // ext_2(bool_2)
524   // sk_3()
525   // Information: bool_1 is not selected, ext_2(bool_2) exists
526   // find all referenced features
527   std::map<FeaturePtr, std::set<FeaturePtr> > aMainList;
528   int aRecLevel = 0;
529   findReferences(theFeatures, aMainList, theUseComposite, theUseRecursion, aRecLevel);
530
531 #ifdef DEBUG_REMOVE_FEATURES
532   printMapInfo(aMainList, "firstDependencies");
533 #endif
534   // find all dependencies for each object:
535   // sk_1(ext_1, vertex_1) + (sk_3, bool_1)
536   // ext_1(bool_1, sk_3)
537   // vertex_1()
538   // sk_2(ext_2) + (bool_1)
539   // ext_2(bool_1)
540   // sk_3()
541   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aMainList.begin(),
542                                                               aMainLast = aMainList.end();
543   for (; aMainIt != aMainLast; aMainIt++) {
544     FeaturePtr aMainListFeature = aMainIt->first;
545
546     //std::string aName = aMainListFeature->name();
547     std::set<FeaturePtr> aMainRefList = aMainIt->second;
548
549 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
550     char aBuf[50];
551     int n = sprintf(aBuf, "%d", aMainRefList.size());
552     std::string aSize(aBuf);
553     std::cout << "_findAllReferences for the Feature: " << getFeatureInfo(aMainListFeature)
554               << ", references size = " << aSize << std::endl;
555 #endif
556     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(),
557                                          aLast = aMainRefList.end();
558     std::set<FeaturePtr> aResultRefList;
559     aResultRefList.insert(aMainRefList.begin(), aMainRefList.end());
560     for (; anIt != aLast; anIt++) {
561       FeaturePtr aFeature = *anIt;
562       aRecLevel = 0;
563 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
564       std::cout << " Ref: " << getFeatureInfo(aFeature) << std::endl;
565 #endif
566       aRecLevel++;
567       addRefsToFeature(aFeature, aMainList,
568                        aRecLevel, aResultRefList/*aMainRefList*/);
569     }
570     theReferences[aMainListFeature] = aResultRefList;
571   }
572 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
573     std::cout << std::endl;
574 #endif
575
576 #ifdef DEBUG_REMOVE_FEATURES
577   printMapInfo(theReferences, "allDependencies");
578 #endif
579 }
580
581 void findRefsToFeatures(const std::set<FeaturePtr>& theFeatures,
582                         const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
583                         std::set<FeaturePtr>& theFeaturesRefsTo)
584 {
585   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
586                                        aLast = theFeatures.end();
587   for (; anIt != aLast; anIt++) {
588     FeaturePtr aFeature = *anIt;
589     if (theReferences.find(aFeature) == theReferences.end())
590       continue;
591     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
592     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
593     for (; aRefIt != aRefLast; aRefIt++) {
594       FeaturePtr aRefFeature = *aRefIt;
595       CompositeFeaturePtr aComposite =
596         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeature);
597       if (aComposite.get() && aComposite->isSub(aFeature))
598         continue; /// composite of the current feature should not be removed
599
600       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
601           theFeaturesRefsTo.find(aRefFeature) == theFeaturesRefsTo.end()) // it is not added
602         theFeaturesRefsTo.insert(aRefFeature);
603     }
604   }
605 }
606
607 void getConcealedResults(const FeaturePtr& theFeature,
608                          std::list<std::shared_ptr<ModelAPI_Result> >& theResults)
609 {
610   SessionPtr aSession = ModelAPI_Session::get();
611
612   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
613   theFeature->data()->referencesToObjects(aRefs);
614   std::list<std::pair<std::string, std::list<ObjectPtr> > >::const_iterator
615                                                   anIt = aRefs.begin(), aLast = aRefs.end();
616   std::set<ResultPtr> alreadyThere; // to avoid duplications
617   for (; anIt != aLast; anIt++) {
618     if (!aSession->validators()->isConcealed(theFeature->getKind(), anIt->first))
619       continue; // use only concealed attributes
620     std::list<ObjectPtr> anObjects = (*anIt).second;
621     std::list<ObjectPtr>::const_iterator anOIt = anObjects.begin(), anOLast = anObjects.end();
622     for (; anOIt != anOLast; anOIt++) {
623       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(*anOIt);
624       if (aResult && aResult->isConcealed()) {
625         if (alreadyThere.find(aResult) == alreadyThere.end()) // issue 1712, avoid duplicates
626           alreadyThere.insert(aResult);
627         else continue;
628         theResults.push_back(aResult);
629       }
630     }
631   }
632 }
633
634 std::pair<std::wstring, bool> getDefaultName(const std::shared_ptr<ModelAPI_Result>& theResult,
635                                              const bool theInherited,
636                                              const bool theRecursive)
637 {
638   typedef std::list< std::pair < std::string, std::list<ObjectPtr> > > ListOfReferences;
639
640   SessionPtr aSession = ModelAPI_Session::get();
641
642   ResultBodyPtr anOwnerRes = bodyOwner(theResult);
643   if (anOwnerRes) {
644     // names of sub-solids in CompSolid should be default (for example,
645     // result of boolean operation 'Boolean_1_1' is a CompSolid which is renamed to 'MyBOOL',
646     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1_1', 'Boolean_1_1_2' etc.)
647     std::wostringstream aDefaultName;
648     aDefaultName << getDefaultName(anOwnerRes).first;
649     aDefaultName << "_" << (bodyIndex(theResult) + 1);
650     return std::pair<std::wstring, bool>(aDefaultName.str(), false);
651   }
652
653   FeaturePtr anOwner = ModelAPI_Feature::feature(theResult->data()->owner());
654   DataPtr aData = anOwner->data();
655
656   ListOfReferences aReferences;
657   // find first result with user-defined name
658   ListOfReferences::const_iterator aFoundRef = aReferences.end();
659   if (theInherited) {
660     aData->referencesToObjects(aReferences);
661
662     for (ListOfReferences::const_iterator aRefIt = aReferences.begin();
663          aRefIt != aReferences.end(); ++aRefIt) {
664       bool isConcealed = aSession->validators()->isConcealed(anOwner->getKind(), aRefIt->first);
665       bool isMainArg = isConcealed &&
666                        aSession->validators()->isMainArgument(anOwner->getKind(), aRefIt->first);
667       if (isConcealed) {
668         // check the referred object is a Body
669         // (for example, ExtrusionCut has a sketch as a first attribute which is concealing)
670         bool isBody = aRefIt->second.size() > 1 || (aRefIt->second.size() == 1 &&
671                       aRefIt->second.front().get() &&
672                       aRefIt->second.front()->groupName() == ModelAPI_ResultBody::group());
673         if (isBody && (isMainArg || aFoundRef == aReferences.end() ||
674             aData->isPrecedingAttribute(aRefIt->first, aFoundRef->first)))
675           aFoundRef = aRefIt;
676
677         if (isMainArg)
678           break;
679       }
680     }
681   }
682   // get the result number in the feature
683   int anIndexInOwner = 0;
684   const std::list<ResultPtr>& anOwnerResults = anOwner->results();
685   std::list<ResultPtr>::const_iterator aResIt = anOwnerResults.cbegin();
686   for(; aResIt != anOwnerResults.cend(); aResIt++) {
687     if(*aResIt == theResult)
688       break;
689     anIndexInOwner++;
690   }
691
692   // find an object which is concealed by theResult
693   if (aFoundRef != aReferences.end() && !aFoundRef->second.empty()) {
694     // store number of references for each object
695     std::map<ResultPtr, int> aNbRefToObject;
696     // search the object by result index
697     std::list<ObjectPtr>::const_iterator anObjIt = aFoundRef->second.begin();
698     int aResultIndex = anIndexInOwner;
699     while (--aResultIndex >= 0) {
700       ResultPtr aCurRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
701       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(aCurRes);
702       if (aParentBody)
703         aCurRes = aParentBody;
704       if (aNbRefToObject.find(aCurRes) == aNbRefToObject.end())
705         aNbRefToObject[aCurRes] = 1;
706       else
707         aNbRefToObject[aCurRes] += 1;
708
709       ++anObjIt;
710       if (anObjIt == aFoundRef->second.end()) {
711         anObjIt = aFoundRef->second.begin();
712         break;
713       }
714     }
715     // check the result is a Body
716     if (anObjIt->get() && (*anObjIt)->groupName() == ModelAPI_ResultBody::group()) {
717       // check the result is part of CompSolid
718       ResultPtr anObjRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
719       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(anObjRes);
720       if (aParentBody)
721         anObjRes = aParentBody;
722
723       // return name of reference result only if it has been renamed by the user,
724       // in other case compose a default name
725       if (anObjRes->data()->hasUserDefinedName() ||
726           (theRecursive && anObjRes->data()->name() != getDefaultName(anObjRes).first)) {
727         std::wstringstream aName;
728         aName << anObjRes->data()->name();
729         std::map<ResultPtr, int>::iterator aFound = aNbRefToObject.find(anObjRes);
730         if (aFound != aNbRefToObject.end()) {
731           // to generate unique name, add suffix if there are several results
732           // referring to the same shape
733           aName << "_" << aFound->second + 1;
734         }
735         return std::pair<std::wstring, bool>(aName.str(), true);
736       }
737     }
738   }
739
740   // compose default name by the name of the feature and the index of result
741   std::wstringstream aDefaultName;
742   aDefaultName << anOwner->name();
743   // if there are several results (issue #899: any number of result),
744   // add unique prefix starting from second
745   if (anIndexInOwner > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
746     aDefaultName << "_" << anIndexInOwner + 1;
747   return std::pair<std::wstring, bool>(aDefaultName.str(), false);
748 }
749
750 std::set<FeaturePtr> getParents(const FeaturePtr& theFeature)
751 {
752   std::set<FeaturePtr> aParents;
753   for (FeaturePtr aCurFeat = theFeature; aCurFeat; ) {
754     CompositeFeaturePtr aFoundComposite;
755     const std::set<AttributePtr>& aRefs = aCurFeat->data()->refsToMe();
756     for (std::set<AttributePtr>::const_iterator anIt = aRefs.begin();
757       anIt != aRefs.end(); ++anIt) {
758       FeaturePtr aF = ModelAPI_Feature::feature((*anIt)->owner());
759       aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aF);
760       if (aFoundComposite && aFoundComposite->isSub(aCurFeat))
761         break;
762       else
763         aFoundComposite = CompositeFeaturePtr();
764     }
765
766     if (aFoundComposite) {
767       aParents.insert(aFoundComposite);
768       aCurFeat = aFoundComposite;
769     }
770     else {
771       // add the part containing high-level feature
772       SessionPtr aSession = ModelAPI_Session::get();
773       DocumentPtr aPartSetDoc = aSession->moduleDocument();
774       std::list<FeaturePtr> aPartSetFeatures = aPartSetDoc->allFeatures();
775       for (std::list<FeaturePtr>::const_iterator anIt = aPartSetFeatures.begin();
776         anIt != aPartSetFeatures.end(); ++anIt) {
777         aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
778         if (aFoundComposite && aFoundComposite->isSub(aCurFeat)) {
779           aParents.insert(aFoundComposite);
780           break;
781         }
782       }
783
784       aCurFeat = FeaturePtr();
785     }
786   }
787   return aParents;
788 }
789
790 void fillShapeHierarchy(const GeomShapePtr& theShape,
791                         const ResultPtr& theContext,
792                         GeomAPI_ShapeHierarchy& theHierarchy)
793 {
794   ResultBodyPtr aResCompSolidPtr = ModelAPI_Tools::bodyOwner(theContext);
795   if (aResCompSolidPtr.get()) {
796     std::shared_ptr<GeomAPI_Shape> aContextShape = aResCompSolidPtr->shape();
797     if (aContextShape->shapeType() <= GeomAPI_Shape::COMPSOLID) {
798       theHierarchy.addParent(theShape, aContextShape);
799       fillShapeHierarchy(aContextShape, aResCompSolidPtr, theHierarchy);
800     }
801   }
802 }
803
804
805 void removeResults(const std::list<ResultPtr>& theResults)
806 {
807   // collect all documents where the results must be removed
808   std::map<DocumentPtr, std::list<ResultPtr> > aDocs;
809
810   std::list<ResultPtr>::const_iterator aResIter = theResults.cbegin();
811   for(; aResIter != theResults.cend(); aResIter++) {
812     DocumentPtr aDoc = (*aResIter)->document();
813     if (!aDocs.count(aDoc))
814       aDocs[aDoc] = std::list<ResultPtr>();
815     aDocs[aDoc].push_back(*aResIter);
816   }
817   // create a "remove" feature in each doc
818   std::map<DocumentPtr, std::list<ResultPtr> >::iterator aDoc = aDocs.begin();
819   for(; aDoc != aDocs.end(); aDoc++) {
820     FeaturePtr aRemove = aDoc->first->addFeature("RemoveResults");
821     if (aRemove) {
822       for(aResIter = aDoc->second.cbegin(); aResIter != aDoc->second.cend(); aResIter++)
823         aRemove->selectionList("results")->append(*aResIter, GeomShapePtr());
824     }
825   }
826 }
827
828 // used by GUI only
829 // LCOV_EXCL_START
830
831 //**************************************************************
832 void setDeflection(ResultPtr theResult, const double theDeflection)
833 {
834   if (!theResult.get())
835     return;
836
837   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
838   if (aDeflectionAttr.get() != NULL) {
839     aDeflectionAttr->setValue(theDeflection);
840   }
841 }
842
843 double getDeflection(const std::shared_ptr<ModelAPI_Result>& theResult)
844 {
845   double aDeflection = -1;
846   // get deflection from the attribute of the result
847   if (theResult.get() != NULL &&
848     theResult->data()->attribute(ModelAPI_Result::DEFLECTION_ID()).get() != NULL) {
849     AttributeDoublePtr aDoubleAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
850     if (aDoubleAttr.get() && aDoubleAttr->isInitialized()) {
851       double aValue = aDoubleAttr->value();
852       if (aValue > 0) /// zero value should not be used as a deflection(previous studies)
853         aDeflection = aDoubleAttr->value();
854     }
855   }
856   return aDeflection;
857 }
858
859 //******************************************************
860 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
861 {
862   if (!theResult.get())
863     return;
864
865   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
866   if (aColorAttr.get() != NULL) {
867     if (!aColorAttr->size()) {
868       aColorAttr->setSize(3);
869     }
870     aColorAttr->setValue(0, theColor[0]);
871     aColorAttr->setValue(1, theColor[1]);
872     aColorAttr->setValue(2, theColor[2]);
873   }
874 }
875
876 void getColor(const std::shared_ptr<ModelAPI_Result>& theResult, std::vector<int>& theColor)
877 {
878   theColor.clear();
879   // get color from the attribute of the result
880   if (theResult.get() != NULL &&
881     theResult->data()->attribute(ModelAPI_Result::COLOR_ID()).get() != NULL) {
882     AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
883     if (aColorAttr.get() && aColorAttr->size()) {
884       theColor.push_back(aColorAttr->value(0));
885       theColor.push_back(aColorAttr->value(1));
886       theColor.push_back(aColorAttr->value(2));
887     }
888   }
889 }
890
891 //******************************************************
892 void getIsoLines(const std::shared_ptr<ModelAPI_Result>& theResult,
893   bool& isVisible, std::vector<int>& theNbLines)
894 {
895   theNbLines.clear();
896   isVisible = false;
897   if (!theResult.get())
898     return;
899   if (theResult->groupName() == ModelAPI_ResultConstruction::group()) {
900     theNbLines.push_back(0);
901     theNbLines.push_back(0);
902   }
903   else {
904     // get color from the attribute of the result
905     AttributeIntArrayPtr aAttr = theResult->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
906     if (aAttr.get()) {
907       if (aAttr->size()) {
908         theNbLines.push_back(aAttr->value(0));
909         theNbLines.push_back(aAttr->value(1));
910       }
911     }
912     AttributeBooleanPtr aBoolAttr =
913       theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
914     if (aBoolAttr.get()) {
915       isVisible = aBoolAttr->value();
916     }
917   }
918 }
919
920 //******************************************************
921 void setIsoLines(ResultPtr theResult, const std::vector<int>& theIso)
922 {
923   if (!theResult.get())
924     return;
925
926   AttributeIntArrayPtr aAttr = theResult->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
927   if (aAttr.get() != NULL) {
928     if (!aAttr->size()) {
929       aAttr->setSize(2);
930     }
931     aAttr->setValue(0, theIso[0]);
932     aAttr->setValue(1, theIso[1]);
933   }
934 }
935
936 //******************************************************
937 void showIsoLines(std::shared_ptr<ModelAPI_Result> theResult, bool theShow)
938 {
939   if (!theResult.get())
940     return;
941
942   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
943   if (aAttr.get() != NULL) {
944     aAttr->setValue(theShow);
945   }
946 }
947
948 //******************************************************
949 bool isShownIsoLines(std::shared_ptr<ModelAPI_Result> theResult)
950 {
951   if (!theResult.get())
952     return false;
953
954   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
955   if (aAttr.get() != NULL) {
956     return aAttr->value();
957   }
958   return false;
959 }
960
961 //**************************************************************
962 void setTransparency(ResultPtr theResult, double theTransparency)
963 {
964   if (!theResult.get())
965     return;
966
967   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
968   if (anAttribute.get() != NULL) {
969     anAttribute->setValue(theTransparency);
970   }
971 }
972
973 double getTransparency(const std::shared_ptr<ModelAPI_Result>& theResult)
974 {
975   double aTransparency = -1;
976   // get transparency from the attribute of the result
977   if (theResult.get() != NULL &&
978     theResult->data()->attribute(ModelAPI_Result::TRANSPARENCY_ID()).get() != NULL) {
979     AttributeDoublePtr aDoubleAttr = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
980     if (aDoubleAttr.get() && aDoubleAttr->isInitialized()) {
981       aTransparency = aDoubleAttr->value();
982     }
983   }
984   return aTransparency;
985 }
986
987 void copyVisualizationAttrs(
988   std::shared_ptr<ModelAPI_Result> theSource, std::shared_ptr<ModelAPI_Result> theDest)
989 {
990   // color
991   AttributeIntArrayPtr aSourceColor = theSource->data()->intArray(ModelAPI_Result::COLOR_ID());
992   if (aSourceColor.get() && aSourceColor->isInitialized() && aSourceColor->size()) {
993     AttributeIntArrayPtr aDestColor = theDest->data()->intArray(ModelAPI_Result::COLOR_ID());
994     if (aDestColor.get()) {
995       aDestColor->setSize(aSourceColor->size());
996       for(int a = 0; a < aSourceColor->size(); a++)
997         aDestColor->setValue(a, aSourceColor->value(a));
998     }
999   }
1000   // Iso-lines
1001   AttributeIntArrayPtr aSource = theSource->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
1002   if (aSource.get() && aSource->isInitialized() && aSource->size()) {
1003     AttributeIntArrayPtr aDest = theDest->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
1004     if (aDest.get()) {
1005       aDest->setSize(aSource->size());
1006       for(int a = 0; a < aSource->size(); a++)
1007         aDest->setValue(a, aSource->value(a));
1008     }
1009   }
1010   // deflection
1011   AttributeDoublePtr aSourceDefl = theSource->data()->real(ModelAPI_Result::DEFLECTION_ID());
1012   if (aSourceDefl.get() && aSourceDefl->isInitialized()) {
1013     AttributeDoublePtr aDestDefl = theDest->data()->real(ModelAPI_Result::DEFLECTION_ID());
1014     if (aDestDefl.get()) {
1015       aDestDefl->setValue(aSourceDefl->value());
1016     }
1017   }
1018   // transparency
1019   AttributeDoublePtr aSourceTransp = theSource->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1020   if (aSourceTransp.get() && aSourceTransp->isInitialized()) {
1021     AttributeDoublePtr aDestTransp = theDest->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1022     if (aDestTransp.get()) {
1023       aDestTransp->setValue(aSourceTransp->value());
1024     }
1025   }
1026 }
1027
1028 std::list<FeaturePtr> referencedFeatures(
1029   std::shared_ptr<ModelAPI_Result> theTarget, const std::string& theFeatureKind,
1030   const bool theSortResults)
1031 {
1032   std::set<FeaturePtr> aResSet; // collect in the set initially to avoid duplicates
1033   std::list<ResultPtr> allSubRes;
1034   allSubRes.push_back(theTarget);
1035   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theTarget);
1036   if (aBody.get())
1037     allSubs(aBody, allSubRes);
1038   std::list<ResultPtr>::iterator aSub = allSubRes.begin();
1039   for(; aSub != allSubRes.end(); aSub++) {
1040     const std::set<AttributePtr>& aRefs = (*aSub)->data()->refsToMe();
1041     std::set<AttributePtr>::const_iterator aRef = aRefs.cbegin();
1042     for(; aRef != aRefs.cend(); aRef++) {
1043       FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1044       if (aFeat.get() && (theFeatureKind.empty() || aFeat->getKind() == theFeatureKind))
1045         aResSet.insert(aFeat);
1046     }
1047   }
1048   // add also feature of the target that may be referenced as a whole
1049   FeaturePtr aTargetFeature = theTarget->document()->feature(theTarget);
1050   const std::set<AttributePtr>& aRefs = aTargetFeature->data()->refsToMe();
1051   std::set<AttributePtr>::const_iterator aRef = aRefs.cbegin();
1052   for(; aRef != aRefs.cend(); aRef++) {
1053     FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1054     if (aFeat.get() && (theFeatureKind.empty() || aFeat->getKind() == theFeatureKind))
1055       aResSet.insert(aFeat);
1056   }
1057   // check also Group-operations that may refer to groups - add them for theFeatureKind "Group"
1058   if (theFeatureKind == "Group") {
1059     std::set<FeaturePtr> aGroupOperations;
1060     for(bool aNeedIterate = true; aNeedIterate; ) {
1061       std::set<FeaturePtr>::iterator aResIter = aResSet.begin();
1062       for(; aResIter != aResSet.end(); aResIter++) {
1063         std::list<ResultPtr>::const_iterator aGroupRes = (*aResIter)->results().cbegin();
1064         for(; aGroupRes != (*aResIter)->results().cend(); aGroupRes++) {
1065           const std::set<AttributePtr>& aGroupRefs = (*aGroupRes)->data()->refsToMe();
1066           std::set<AttributePtr>::const_iterator aRefIt = aGroupRefs.cbegin();
1067           for(; aRefIt != aGroupRefs.cend(); aRefIt++) {
1068             FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
1069             if (aFeat.get() && !aGroupOperations.count(aFeat) && !aFeat->results().empty() &&
1070                 aFeat->firstResult()->groupName() == ModelAPI_ResultGroup::group()) {
1071               // iterate results of this group operation because it may be without theTarget shape
1072               GeomShapePtr aTargetShape = theTarget->shape();
1073               bool anIsIn = false;
1074               std::list<ResultPtr>::const_iterator anOpRes = aFeat->results().cbegin();
1075               for(; anOpRes != aFeat->results().cend() && !anIsIn; anOpRes++) {
1076                 GeomShapePtr anOpShape = (*anOpRes)->shape();
1077                 if (!anOpShape.get() || anOpShape->isNull())
1078                   continue;
1079                 for(GeomAPI_ShapeIterator aSubIt(anOpShape); aSubIt.more(); aSubIt.next()) {
1080                   if (aTargetShape->isSubShape(aSubIt.current(), false)) {
1081                     anIsIn = true;
1082                     break;
1083                   }
1084                 }
1085               }
1086               if (anIsIn)
1087                 aGroupOperations.insert(aFeat);
1088             }
1089           }
1090         }
1091       }
1092       // insert all new group operations into result and if they are, check for next dependencies
1093       aNeedIterate = false;
1094       std::set<FeaturePtr>::iterator aGroupOpIter = aGroupOperations.begin();
1095       for(; aGroupOpIter != aGroupOperations.end(); aGroupOpIter++) {
1096         if (aResSet.find(*aGroupOpIter) == aResSet.end()) {
1097           aResSet.insert(*aGroupOpIter);
1098           aNeedIterate = true;
1099         }
1100       }
1101     }
1102   }
1103
1104   std::list<FeaturePtr> aResList;
1105   std::set<FeaturePtr>::iterator aResIter = aResSet.begin();
1106   for(; aResIter != aResSet.end(); aResIter++) {
1107     if (theSortResults) { // sort results by creation-order
1108       std::list<FeaturePtr>::iterator aListIter = aResList.begin();
1109       for(; aListIter != aResList.end(); aListIter++) {
1110         if ((*aResIter)->document()->isLater(*aListIter, *aResIter))
1111           break;
1112       }
1113       if (aListIter == aResList.end()) // goes to the end
1114         aResList.push_back(*aResIter);
1115       else
1116         aResList.insert(aListIter, *aResIter);
1117     } else //just push to the end unsorted
1118       aResList.push_back(*aResIter);
1119   }
1120   return aResList;
1121 }
1122
1123 void setValues(std::vector<int>& theRGB, const int theRed, const int theGreen, const int theBlue)
1124 {
1125   theRGB.push_back(theRed);
1126   theRGB.push_back(theGreen);
1127   theRGB.push_back(theBlue);
1128 }
1129
1130 std::vector<int> HSVtoRGB(int theH, int theS, int theV)
1131 {
1132   std::vector<int> aRGB;
1133   if (theH < 0 || theH > 360 ||
1134       theS < 0 || theS > 100 ||
1135       theV < 0 || theV > 100)
1136     return aRGB;
1137
1138   int aHi = (int)theH/60;
1139   double aV = theV;
1140   double aVmin = (100 - theS)*theV/100;
1141   double anA = (theV - aVmin)* (theH % 60) / 60;
1142   double aVinc = aVmin + anA;
1143   double aVdec = theV - anA;
1144   double aPercentToValue = 255./100;
1145   int aV_int    = (int)(aV*aPercentToValue);
1146   int aVinc_int = (int)(aVinc*aPercentToValue);
1147   int aVmin_int = (int)(aVmin*aPercentToValue);
1148   int aVdec_int = (int)(aVdec*aPercentToValue);
1149
1150   switch(aHi) {
1151     case 0: setValues(aRGB, aV_int,    aVinc_int, aVmin_int); break;
1152     case 1: setValues(aRGB, aVdec_int, aV_int,    aVmin_int); break;
1153     case 2: setValues(aRGB, aVmin_int, aV_int,    aVinc_int); break;
1154     case 3: setValues(aRGB, aVmin_int, aVdec_int, aV_int); break;
1155     case 4: setValues(aRGB, aVinc_int, aVmin_int, aV_int); break;
1156     case 5: setValues(aRGB, aV_int,    aVmin_int, aVdec_int); break;
1157     default: break;
1158   }
1159   return aRGB;
1160 }
1161
1162 std::array<std::vector<int>, 10> myColorTab = {
1163   std::vector<int> {255, 0, 0},
1164   std::vector<int> {0, 255, 0},
1165   std::vector<int> {0, 0, 255},
1166   std::vector<int> {255, 255, 0},
1167   std::vector<int> {0, 255, 255},
1168   std::vector<int> {255, 0, 255},
1169   std::vector<int> {255, 94, 0},
1170   std::vector<int> {132, 255, 0},
1171   std::vector<int> {132, 0, 255},
1172   std::vector<int> {0, 0, 0},
1173 };
1174
1175 void findRandomColor(std::vector<int>& theValues, bool theReset)
1176 {
1177   static size_t i = 0;
1178   static std::vector<std::vector<int>> usedGeneratedColor;
1179
1180   // True when disabling auto-color
1181   if ( theReset ) {
1182     i = 0;
1183     return;
1184   }
1185
1186   theValues.clear();
1187   if (i < myColorTab.size()) {
1188     theValues = myColorTab[i++];
1189   } else {
1190       int timeout = 0;
1191       std::vector<int> aHSVColor;
1192       std::vector<int> aRGBColor;
1193       do {
1194         aHSVColor = {rand() % 360 , rand() % (100 - 50 + 1) + 50, rand() % (100 - 50 + 1) + 50};
1195         aRGBColor = HSVtoRGB(aHSVColor[0], aHSVColor[1], aHSVColor[2]);
1196         timeout++;
1197       } while (
1198         timeout < 20 &&
1199         std::find(usedGeneratedColor.begin(), usedGeneratedColor.end(), aHSVColor)
1200         != usedGeneratedColor.end() &&
1201         std::find(myColorTab.begin(), myColorTab.end(), aRGBColor) != myColorTab.end());
1202       usedGeneratedColor.push_back(aHSVColor);
1203       theValues = aRGBColor;
1204   }
1205 }
1206
1207 // LCOV_EXCL_STOP
1208
1209 } // namespace ModelAPI_Tools