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