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