Salome HOME
Updated copyright comment
[modules/shaper.git] / src / ModelAPI / ModelAPI_Tools.cpp
1 // Copyright (C) 2014-2024  CEA, EDF
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 <GeomAlgoAPI_MakeShape.h>
44 #include <GeomAPI_ShapeHierarchy.h>
45 #include <GeomAPI_ShapeIterator.h>
46 #include <GeomAPI_ShapeExplorer.h>
47
48 #include <algorithm>
49 #include <iostream>
50 #include <list>
51 #include <map>
52 #include <sstream>
53 #include <vector>
54 #include <array>
55
56 #define RECURSE_TOP_LEVEL 50
57
58 //#define DEBUG_REMOVE_FEATURES
59 //#define DEBUG_REMOVE_FEATURES_RECURSE
60 //#define DEBUG_CYCLING_1550
61
62 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
63 #include <sstream>
64 std::string getFeatureInfo(FeaturePtr theFeature)
65 {
66   if (!theFeature.get())
67     return "";
68   //std::ostringstream aPtrStr;
69   //aPtrStr << "[" << theFeature.get() << "] ";
70   std::string aFeatureInfo = /*aPtrStr.str() + */theFeature->name();
71   CompositeFeaturePtr aComposite = ModelAPI_Tools::compositeOwner(theFeature);
72   if (aComposite.get()) {
73       aFeatureInfo = aFeatureInfo + "[in " + aComposite->name() + "]";
74   }
75   return aFeatureInfo;
76 }
77 #endif
78
79 #ifdef DEBUG_REMOVE_FEATURES
80 void printMapInfo(const std::map<FeaturePtr, std::set<FeaturePtr> >& theMainList,
81                   const std::string& thePrefix)
82 {
83   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = theMainList.begin(),
84                                                               aMainLast = theMainList.end();
85   std::string anInfo;
86   for (; aMainIt != aMainLast; aMainIt++) {
87     FeaturePtr aMainListFeature = aMainIt->first;
88     std::set<FeaturePtr> aMainRefList = aMainIt->second;
89     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(), aLast = aMainRefList.end();
90     std::string aRefsInfo;
91     for (; anIt != aLast; anIt++) {
92       aRefsInfo += (*anIt)->name().c_str();
93       if (anIt != aLast)
94         aRefsInfo += ", ";
95     }
96     if (!aRefsInfo.empty()) {
97       anInfo = anInfo + aMainListFeature->name().c_str() + ": " + aRefsInfo + "\n";
98     }
99   }
100   std::cout << thePrefix.c_str() << " [feature: references to]: \n" << anInfo.c_str() << std::endl;
101 }
102
103 void printListInfo(const std::set<FeaturePtr>& theMainList,
104                   const std::string& thePrefix)
105 {
106   std::set<FeaturePtr>::const_iterator aMainIt = theMainList.begin(),
107                                        aMainLast = theMainList.end();
108   std::string anInfo;
109   for (; aMainIt != aMainLast; aMainIt++) {
110     FeaturePtr aRefFeature = *aMainIt;
111     anInfo += aRefFeature->name().c_str();
112     if (aMainIt != aMainLast)
113       anInfo += ", ";
114   }
115   std::cout << thePrefix.c_str() << ": " << anInfo.c_str() << std::endl;
116 }
117 #endif
118
119 namespace ModelAPI_Tools {
120
121 std::shared_ptr<GeomAPI_Shape> shape(const ResultPtr& theResult)
122 {
123   return theResult->shape();
124 }
125
126 // LCOV_EXCL_START
127 const char* toString(ModelAPI_ExecState theExecState)
128 {
129   switch (theExecState) {
130   case ModelAPI_StateDone: return "Done";
131   case ModelAPI_StateMustBeUpdated: return "Must be updated";
132   case ModelAPI_StateExecFailed: return "Execution failed";
133   case ModelAPI_StateInvalidArgument: return "Invalid argument";
134   case ModelAPI_StateNothing: return "Empty state";
135   default: return "Unknown ExecState.";
136   }
137 }
138
139 std::string getFeatureError(const FeaturePtr& theFeature)
140 {
141   std::string anError;
142   if (!theFeature.get() || !theFeature->data()->isValid() || theFeature->isAction())
143     return anError;
144
145   // to be removed later, this error should be got from the feature
146   if (theFeature->data()->execState() == ModelAPI_StateDone ||
147       theFeature->data()->execState() == ModelAPI_StateMustBeUpdated)
148     return anError;
149
150   // set error indication
151   anError = theFeature->error();
152   if (anError.empty()) {
153     bool isDone = ( theFeature->data()->execState() == ModelAPI_StateDone
154                  || theFeature->data()->execState() == ModelAPI_StateMustBeUpdated );
155     if (!isDone) {
156       anError = toString(theFeature->data()->execState());
157       // If the feature is Composite and error is StateInvalidArgument,
158       // error text should include error of first invalid sub-feature. Otherwise
159       // it is not clear what is the reason of the invalid argument.
160       if (theFeature->data()->execState() == ModelAPI_StateInvalidArgument) {
161         CompositeFeaturePtr aComposite =
162                     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
163         if (aComposite) {
164           bool aHasSubError = false;
165           for (int i = 0, aSize = aComposite->numberOfSubs(); i < aSize; i++) {
166             FeaturePtr aSubFeature = aComposite->subFeature(i);
167             std::string aSubFeatureError = getFeatureError(aSubFeature);
168             if (!aSubFeatureError.empty()) {
169               anError = anError + " in " + aSubFeature->getKind() + ".\n" + aSubFeatureError;
170               aHasSubError = true;
171               break;
172             }
173           }
174           if (!aHasSubError) { // #24260: error not in the sub-features, but in the argument
175             if (aComposite->getKind() == "Sketch" &&
176                 aComposite->selection("External")->isInvalid()) {
177               std::string aMsg = "The sketch base plane is invalid, ";
178               aMsg += "please push 'Change sketch plane' button to reselect it.";
179               anError = Config_Translator::translate(aComposite->getKind(), aMsg);
180             }
181           }
182         }
183       }
184     }
185   }
186
187   return anError;
188 }
189 // LCOV_EXCL_STOP
190
191 ObjectPtr objectByName(const DocumentPtr& theDocument, const std::string& theGroup,
192                        const std::wstring& theName)
193 {
194   for (int anIndex = 0; anIndex < theDocument->size(theGroup); ++anIndex) {
195     ObjectPtr anObject = theDocument->object(theGroup, anIndex);
196     if (anObject->data()->name() == theName)
197       return anObject;
198   }
199   // not found
200   return ObjectPtr();
201 }
202
203 //==================================================================================================
204 void loadModifiedShapes(ResultBodyPtr theResultBody,
205                         const ListOfShape& theBaseShapes,
206                         const ListOfShape& theTools,
207                         const GeomMakeShapePtr& theMakeShape,
208                         const GeomShapePtr theResultShape,
209                         const std::string& theNamePrefix)
210 {
211   theResultBody->storeModified(theBaseShapes, theResultShape, theMakeShape);
212
213   ListOfShape aShapes = theBaseShapes;
214   ListOfShape::const_iterator aToolIter = theTools.cbegin();
215   for (; aToolIter != theTools.cend(); aToolIter++)
216     aShapes.push_back(*aToolIter);
217
218   for (ListOfShape::const_iterator anIter = aShapes.begin(); anIter != aShapes.end(); ++anIter)
219   {
220     theResultBody->loadModifiedShapes(theMakeShape, *anIter, GeomAPI_Shape::VERTEX, theNamePrefix);
221     theResultBody->loadModifiedShapes(theMakeShape, *anIter, GeomAPI_Shape::EDGE, theNamePrefix);
222     theResultBody->loadModifiedShapes(theMakeShape, *anIter, GeomAPI_Shape::FACE, theNamePrefix);
223   }
224 }
225
226 //==================================================================================================
227 void loadModifiedShapes(ResultBodyPtr theResultBody,
228                         const GeomShapePtr& theBaseShape,
229                         const GeomMakeShapePtr& theMakeShape,
230                         const std::string theName)
231 {
232   switch (theBaseShape->shapeType()) {
233   case GeomAPI_Shape::COMPOUND: {
234     for (GeomAPI_ShapeIterator anIt(theBaseShape); anIt.more(); anIt.next())
235     {
236       loadModifiedShapes(theResultBody,
237         anIt.current(),
238         theMakeShape,
239         theName);
240     }
241     break;
242   }
243   case GeomAPI_Shape::COMPSOLID:
244   case GeomAPI_Shape::SOLID:
245   case GeomAPI_Shape::SHELL: {
246     theResultBody->loadModifiedShapes(theMakeShape,
247       theBaseShape,
248       GeomAPI_Shape::FACE,
249       theName);
250   }
251   case GeomAPI_Shape::FACE:
252   case GeomAPI_Shape::WIRE: {
253     theResultBody->loadModifiedShapes(theMakeShape,
254       theBaseShape,
255       GeomAPI_Shape::EDGE,
256       theName);
257   }
258   case GeomAPI_Shape::EDGE: {
259     theResultBody->loadModifiedShapes(theMakeShape,
260       theBaseShape,
261       GeomAPI_Shape::VERTEX,
262       theName);
263   }
264   default: // [to avoid compilation warning]
265     break;
266   }
267 }
268
269 //==================================================================================================
270 void loadDeletedShapes(ResultBodyPtr theResultBody,
271                       const GeomShapePtr theBaseShape,
272                       const ListOfShape& theTools,
273                       const GeomMakeShapePtr& theMakeShape,
274                       const GeomShapePtr theResultShapesCompound)
275 {
276   ListOfShape aShapes = theTools;
277   if (theBaseShape.get())
278     aShapes.push_front(theBaseShape);
279
280   for (ListOfShape::const_iterator anIter = aShapes.begin(); anIter != aShapes.end(); anIter++)
281   {
282     theResultBody->loadDeletedShapes(theMakeShape,
283       *anIter,
284       GeomAPI_Shape::VERTEX,
285       theResultShapesCompound);
286     theResultBody->loadDeletedShapes(theMakeShape,
287       *anIter,
288       GeomAPI_Shape::EDGE,
289       theResultShapesCompound);
290     theResultBody->loadDeletedShapes(theMakeShape,
291       *anIter,
292       GeomAPI_Shape::FACE,
293       theResultShapesCompound);
294     // store information about deleted solids because of unittest TestBooleanCommon_SolidsHistory
295     // on OCCT 7.4.0 : common produces modified compsolid, so, move to the end for removed solids
296     // starts to produce whole compsolid
297     theResultBody->loadDeletedShapes(theMakeShape,
298       *anIter,
299       GeomAPI_Shape::SOLID,
300       theResultShapesCompound);
301   }
302 }
303
304 //==================================================================================================
305 void loadDeletedShapes(std::vector<ResultBaseAlgo>& theResultBaseAlgoList,
306                         const ListOfShape& theTools,
307                         const GeomShapePtr theResultShapesCompound)
308 {
309   for (std::vector<ResultBaseAlgo>::iterator anIt = theResultBaseAlgoList.begin();
310     anIt != theResultBaseAlgoList.end();
311     ++anIt)
312   {
313     ResultBaseAlgo& aRCA = *anIt;
314     loadDeletedShapes(aRCA.resultBody,
315       aRCA.baseShape,
316       theTools,
317       aRCA.makeShape,
318       theResultShapesCompound);
319   }
320 }
321
322 bool findVariable(const DocumentPtr& theDocument, FeaturePtr theSearcher,
323                   const std::wstring& theName, double& outValue, ResultParameterPtr& theParam)
324 {
325   ObjectPtr aParamObj = objectByName(theDocument, ModelAPI_ResultParameter::group(), theName);
326   theParam = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(aParamObj);
327   if (!theParam.get())
328     return false;
329   // avoid usage of parameters created later than the initial parameter
330
331   if (theSearcher.get()) {
332     FeaturePtr aParamFeat = theDocument->feature(theParam);
333     if (aParamFeat == theSearcher || theDocument->isLater(aParamFeat, theSearcher))
334       return false;
335   }
336   AttributeDoublePtr aValueAttribute = theParam->data()->real(ModelAPI_ResultParameter::VALUE());
337   outValue = aValueAttribute->value();
338   return true;
339 }
340
341 bool findVariable(FeaturePtr theSearcher, const std::wstring& theName, double& outValue,
342                   ResultParameterPtr& theParam, const DocumentPtr& theDocument)
343 {
344   SessionPtr aSession = ModelAPI_Session::get();
345   std::list<DocumentPtr> aDocList;
346   DocumentPtr aDocument = theDocument.get() ? theDocument : aSession->activeDocument();
347   if (findVariable(aDocument, theSearcher, theName, outValue, theParam))
348     return true;
349   DocumentPtr aRootDocument = aSession->moduleDocument();
350   if (aDocument != aRootDocument) {
351     // any parameters in PartSet is okindependently on the Part position (issu #1504)
352     if (findVariable(aRootDocument, FeaturePtr(), theName, outValue, theParam))
353       return true;
354   }
355   return false;
356 }
357
358 static void cacheSubresults(const ResultBodyPtr& theTopLevelResult,
359                             std::set<ResultPtr>& theCashedResults)
360 {
361   std::list<ResultPtr> aResults;
362   ModelAPI_Tools::allSubs(theTopLevelResult, aResults, false);
363   for (std::list<ResultPtr>::iterator aR = aResults.begin(); aR != aResults.end(); ++aR) {
364     theCashedResults.insert(*aR);
365   }
366 }
367
368 bool isInResults(AttributeSelectionListPtr theSelection,
369                  const std::list<ResultPtr>& theResults,
370                  std::set<ResultPtr>& theCashedResults)
371 {
372   // collect all results into a cashed set
373   if (theCashedResults.empty()) {
374     std::list<ResultPtr>::const_iterator aRes = theResults.cbegin();
375     for(; aRes != theResults.cend(); aRes++) {
376       if (theCashedResults.count(*aRes))
377         continue;
378       else
379         theCashedResults.insert(*aRes);
380
381       if ((*aRes)->groupName() == ModelAPI_ResultBody::group()) {
382         ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRes);
383         cacheSubresults(aResBody, theCashedResults);
384       } else if ((*aRes)->groupName() == ModelAPI_ResultPart::group()) { // all results of the part
385         ResultPartPtr aResPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
386         DocumentPtr aPartDoc = aResPart->partDoc();
387         if (!aPartDoc.get() || !aPartDoc->isOpened()) { // document is not accessible
388           return false;
389         }
390         int aBodyCount = aPartDoc->size(ModelAPI_ResultBody::group());
391         for (int aBodyIndex = 0; aBodyIndex < aBodyCount; ++aBodyIndex) {
392           ResultBodyPtr aResBody =
393             std::dynamic_pointer_cast<ModelAPI_ResultBody>(
394               aPartDoc->object(ModelAPI_ResultBody::group(), aBodyIndex));
395           if (aResBody.get()) {
396             theCashedResults.insert(aResBody);
397             cacheSubresults(aResBody, theCashedResults);
398           }
399         }
400       }
401     }
402   }
403   // if context is in results, return true
404   for(int a = 0; a < theSelection->size(); a++) {
405     AttributeSelectionPtr anAttr = theSelection->value(a);
406     ResultPtr aContext = anAttr->context();
407     // check is it group selected for groups BOP
408     if (aContext.get() && aContext->groupName() == ModelAPI_ResultGroup::group()) {
409       // it is impossible by used results check which result is used in this group result,
410       // so check the results shapes is it in results of this document or not
411       FeaturePtr aSelFeature =
412         std::dynamic_pointer_cast<ModelAPI_Feature>(theSelection->owner());
413       if (!aSelFeature.get() || aSelFeature->results().empty())
414         continue;
415       GeomShapePtr aGroupResShape = aSelFeature->firstResult()->shape();
416
417       std::set<ResultPtr>::iterator allResultsIter = theCashedResults.begin();
418       for(; allResultsIter != theCashedResults.end(); allResultsIter++) {
419         GeomShapePtr aResultShape = (*allResultsIter)->shape();
420
421         GeomAPI_Shape::ShapeType aType =
422           GeomAPI_Shape::shapeTypeByStr(theSelection->selectionType());
423         GeomAPI_ShapeExplorer aGroupResExp(aGroupResShape, aType);
424         for(; aGroupResExp.more(); aGroupResExp.next()) {
425           if (aResultShape->isSubShape(aGroupResExp.current(), false))
426             return true; // at least one shape of the group is in the used results
427         }
428       }
429     }
430     ResultBodyPtr aSelected = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anAttr->context());
431     if (!aSelected.get()) { // try to get selected feature and all its results
432       FeaturePtr aContextFeature = anAttr->contextFeature();
433       if (aContextFeature.get() && !aContextFeature->results().empty()) {
434         const std::list<ResultPtr>& allResluts = aContextFeature->results();
435         std::list<ResultPtr>::const_iterator aResIter = allResluts.cbegin();
436         for(; aResIter != allResluts.cend(); aResIter++) {
437           if (aResIter->get() && theCashedResults.count(*aResIter))
438             return true;
439         }
440       }
441     } else if (aSelected.get() && theCashedResults.count(aSelected))
442       return true;
443   }
444   return false;
445 }
446
447 ResultPtr findPartResult(const DocumentPtr& theMain, const DocumentPtr& theSub)
448 {
449   // to optimize and avoid of crash on partset document close
450   // (don't touch the sub-document structure)
451   if (theMain != theSub) {
452     for (int a = theMain->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
453       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
454           theMain->object(ModelAPI_ResultPart::group(), a));
455       if (aPart && aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->value() == theSub) {
456         return aPart;
457       }
458     }
459   }
460   return ResultPtr();
461 }
462
463 FeaturePtr findPartFeature(const DocumentPtr& theMain, const DocumentPtr& theSub)
464 {
465   // to optimize and avoid of crash on partset document close
466   // (don't touch the sub-document structure)
467   if (theMain != theSub) {
468     // iteration from top to bottom to avoid finding the movement documents before the original
469     int aSize = theMain->size(ModelAPI_Feature::group());
470     for (int a = 0; a < aSize; a++) {
471       FeaturePtr aPartFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(
472           theMain->object(ModelAPI_Feature::group(), a));
473       if (aPartFeat.get()) {
474         const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aPartFeat->results();
475         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
476         for(; aRes != aResList.end(); aRes++) {
477           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRes);
478           if (aPart.get()) {
479             if (aPart->isActivated() && aPart->partDoc() == theSub)
480               return aPartFeat;
481           } else break; // if the first is not Part, others are also not
482         }
483       }
484     }
485   }
486   return FeaturePtr();
487 }
488
489 CompositeFeaturePtr compositeOwner(const FeaturePtr& theFeature)
490 {
491   if (theFeature.get() && theFeature->data() && theFeature->data()->isValid()) {
492     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
493     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.begin();
494     for(; aRefIter != aRefs.end(); aRefIter++) {
495       CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>
496         ((*aRefIter)->owner());
497       if (aComp.get() && aComp->data()->isValid() && aComp->isSub(theFeature))
498         return aComp;
499     }
500   }
501   return CompositeFeaturePtr(); // not found
502 }
503
504 ResultBodyPtr bodyOwner(const ResultPtr& theSub, const bool theRoot)
505 {
506   if (theSub.get()) {
507     ObjectPtr aParent = theSub->document()->parent(theSub);
508     if (aParent.get()) {
509       if (theRoot) { // try to find parent of parent
510         ResultPtr aResultParent = std::dynamic_pointer_cast<ModelAPI_Result>(aParent);
511         ResultBodyPtr aGrandParent = bodyOwner(aResultParent, true);
512         if (aGrandParent.get())
513           aParent = aGrandParent;
514       }
515       return std::dynamic_pointer_cast<ModelAPI_ResultBody>(aParent);
516     }
517   }
518   return ResultBodyPtr(); // not found
519 }
520
521 int bodyIndex(const ResultPtr& theSub)
522 {
523   int anIndex = -1;
524   ResultBodyPtr aParent = bodyOwner(theSub);
525   if (aParent.get()) {
526     ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theSub);
527     if (aBody.get() && aParent->isSub(aBody, anIndex))
528       return anIndex;
529   }
530   return anIndex; // not found
531 }
532
533 bool hasSubResults(const ResultPtr& theResult)
534 {
535   ResultBodyPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
536   return aCompSolid.get() && aCompSolid->numberOfSubs() > 0;
537 }
538
539 void allSubs(const ResultBodyPtr& theResult, std::list<ResultPtr>& theResults,
540              const bool theLowerOnly) {
541   // iterate sub-bodies of compsolid
542   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
543   if (aComp.get()) {
544     int aNumSub = aComp->numberOfSubs();
545     for (int a = 0; a < aNumSub; a++) {
546       ResultBodyPtr aSub = aComp->subResult(a);
547       if (!theLowerOnly || aSub->numberOfSubs() == 0)
548         theResults.push_back(aSub);
549       allSubs(aSub, theResults);
550     }
551   }
552 }
553
554 void allResults(const FeaturePtr& theFeature, std::list<ResultPtr>& theResults)
555 {
556   if (!theFeature.get()) // safety: for empty feature no results
557     return;
558   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
559   std::list<ResultPtr>::const_iterator aRIter = aResults.begin();
560   for (; aRIter != aResults.cend(); aRIter++) {
561     theResults.push_back(*aRIter);
562     ResultBodyPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRIter);
563     allSubs(aResult, theResults);
564   }
565 }
566
567 //******************************************************************
568 bool allDocumentsActivated(std::wstring& theNotActivatedNames)
569 {
570   theNotActivatedNames = L"";
571   bool anAllPartActivated = true;
572
573   DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
574   int aSize = aRootDoc->size(ModelAPI_ResultPart::group());
575   for (int i = 0; i < aSize; i++) {
576     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
577     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
578     if (!aPart->isActivated()) {
579       anAllPartActivated = false;
580       if (!theNotActivatedNames.empty())
581         theNotActivatedNames += L", ";
582       theNotActivatedNames += aObject->data()->name().c_str();
583     }
584   }
585   return anAllPartActivated;
586 }
587
588 bool removeFeaturesAndReferences(const std::set<FeaturePtr>& theFeatures,
589                                  const bool /*theFlushRedisplay*/,
590                                  const bool theUseComposite,
591                                  const bool theUseRecursion)
592 {
593 #ifdef DEBUG_REMOVE_FEATURES
594   printListInfo(theFeatures, "selection: ");
595 #endif
596
597   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
598   ModelAPI_Tools::findAllReferences(theFeatures, aReferences, theUseComposite, theUseRecursion);
599 #ifdef DEBUG_REMOVE_FEATURES
600   printMapInfo(aReferences, "allDependencies: ");
601 #endif
602
603   std::set<FeaturePtr> aFeaturesRefsTo;
604   ModelAPI_Tools::findRefsToFeatures(theFeatures, aReferences, aFeaturesRefsTo);
605 #ifdef DEBUG_REMOVE_FEATURES
606   printListInfo(aFeaturesRefsTo, "references: ");
607 #endif
608
609   std::set<FeaturePtr> aFeatures = theFeatures;
610   if (!aFeaturesRefsTo.empty())
611     aFeatures.insert(aFeaturesRefsTo.begin(), aFeaturesRefsTo.end());
612 #ifdef DEBUG_REMOVE_FEATURES
613   printListInfo(aFeatures, "removeFeatures: ");
614 #endif
615
616   return ModelAPI_Tools::removeFeatures(aFeatures, false);
617 }
618
619 //***********************************************************************
620 bool removeFeatures(const std::set<FeaturePtr>& theFeatures,
621                     const bool theFlushRedisplay)
622 {
623   bool isDone = false;
624   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
625                                        aLast = theFeatures.end();
626   for (; anIt != aLast; anIt++) {
627     FeaturePtr aFeature = *anIt;
628     if (aFeature.get()) {
629       DocumentPtr aDoc = aFeature->document();
630       // flush REDISPLAY signal after remove feature
631       aDoc->removeFeature(aFeature);
632       isDone = true;
633     }
634   }
635   if (isDone && theFlushRedisplay) {
636     // the redisplay signal should be flushed in order to erase
637     // the feature presentation in the viewer
638     // if should be done after removeFeature() of document
639     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
640   }
641   return true;
642 }
643
644 //***********************************************************************
645 // Fills the references list by all references of the feature from the references map.
646 // This is a recusive method to find references by next found feature in the map of references.
647 // \param theFeature a feature to find references
648 // \param theReferencesMap a map of references
649 // \param theReferences an out container of references
650 void addRefsToFeature(const FeaturePtr& theFeature,
651                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferencesMap,
652                       int theRecLevel,
653                       std::set<FeaturePtr>& theReferences)
654 {
655   if (theRecLevel > RECURSE_TOP_LEVEL)
656     return;
657   theRecLevel++;
658
659   if (theReferencesMap.find(theFeature) == theReferencesMap.end())
660     return; // this feature is not in the selection list, so exists without references to it
661   std::set<FeaturePtr> aMainReferences = theReferencesMap.at(theFeature);
662
663   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
664                                        aLast = aMainReferences.end();
665   for (; anIt != aLast; anIt++) {
666     FeaturePtr aRefFeature = *anIt;
667     if (theReferences.find(aRefFeature) == theReferences.end()) {
668       addRefsToFeature(aRefFeature, theReferencesMap, theRecLevel, theReferences);
669       theReferences.insert(aRefFeature);
670     }
671   }
672 }
673
674 // For each feature from the feature list it searches references to the feature and append them
675 // to the references map. This is a recusive method.
676 // \param theFeature a feature to find references
677 // \param theReferencesMap a map of references
678 // \param theReferences an out container of references
679 void findReferences(const std::set<FeaturePtr>& theFeatures,
680                     std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
681                     const bool theUseComposite, const bool theUseRecursion, int theRecLevel)
682 {
683   if (theRecLevel > RECURSE_TOP_LEVEL)
684     return;
685   theRecLevel++;
686   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
687                                         aLast = theFeatures.end();
688   for (; anIt != aLast; anIt++) {
689     FeaturePtr aFeature = *anIt;
690     if (aFeature.get() && theReferences.find(aFeature) == theReferences.end()) {
691       DocumentPtr aSelFeatureDoc = aFeature->document();
692       std::set<FeaturePtr> aSelRefFeatures;
693       aSelFeatureDoc->refsToFeature(aFeature, aSelRefFeatures, false/*do not emit signals*/);
694       if (theUseComposite) { // do not filter selection
695         theReferences[aFeature] = aSelRefFeatures;
696       }
697       else { // filter references to skip composition features of the current feature
698         std::set<FeaturePtr> aFilteredFeatures;
699         std::set<FeaturePtr>::const_iterator aRefIt = aSelRefFeatures.begin(),
700                                              aRefLast = aSelRefFeatures.end();
701         for (; aRefIt != aRefLast; aRefIt++) {
702           FeaturePtr aCFeature = *aRefIt;
703           CompositeFeaturePtr aComposite =
704             std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCFeature);
705           if (aComposite.get() && aComposite->isSub(aFeature))
706             continue; /// composite of the current feature should be skipped
707           aFilteredFeatures.insert(aCFeature);
708         }
709         theReferences[aFeature] = aFilteredFeatures;
710       }
711       if (theUseRecursion) {
712 #ifdef DEBUG_CYCLING_1550
713         findReferences(aSelRefFeatures, theReferences, theUseComposite,
714                        theUseRecursion, theRecLevel);
715 #else
716         findReferences(theReferences[aFeature], theReferences, theUseComposite, theUseRecursion,
717                        theRecLevel);
718 #endif
719       }
720     }
721   }
722 }
723
724 void findAllReferences(const std::set<FeaturePtr>& theFeatures,
725                        std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
726                        const bool theUseComposite,
727                        const bool theUseRecursion)
728 {
729   // For dependencies, find main_list:
730   // sk_1(ext_1, vertex_1)
731   // ext_1(bool_1, sk_3)
732   // vertex_1()
733   // sk_2(ext_2)
734   // ext_2(bool_2)
735   // sk_3()
736   // Information: bool_1 is not selected, ext_2(bool_2) exists
737   // find all referenced features
738   std::map<FeaturePtr, std::set<FeaturePtr> > aMainList;
739   int aRecLevel = 0;
740   findReferences(theFeatures, aMainList, theUseComposite, theUseRecursion, aRecLevel);
741
742 #ifdef DEBUG_REMOVE_FEATURES
743   printMapInfo(aMainList, "firstDependencies");
744 #endif
745   // find all dependencies for each object:
746   // sk_1(ext_1, vertex_1) + (sk_3, bool_1)
747   // ext_1(bool_1, sk_3)
748   // vertex_1()
749   // sk_2(ext_2) + (bool_1)
750   // ext_2(bool_1)
751   // sk_3()
752   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aMainList.begin(),
753                                                               aMainLast = aMainList.end();
754   for (; aMainIt != aMainLast; aMainIt++) {
755     FeaturePtr aMainListFeature = aMainIt->first;
756
757     //std::string aName = aMainListFeature->name();
758     std::set<FeaturePtr> aMainRefList = aMainIt->second;
759
760 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
761     char aBuf[50];
762     int n = sprintf(aBuf, "%d", aMainRefList.size());
763     std::string aSize(aBuf);
764     std::cout << "_findAllReferences for the Feature: " << getFeatureInfo(aMainListFeature)
765               << ", references size = " << aSize << std::endl;
766 #endif
767     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(),
768                                          aLast = aMainRefList.end();
769     std::set<FeaturePtr> aResultRefList;
770     aResultRefList.insert(aMainRefList.begin(), aMainRefList.end());
771     for (; anIt != aLast; anIt++) {
772       FeaturePtr aFeature = *anIt;
773       aRecLevel = 0;
774 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
775       std::cout << " Ref: " << getFeatureInfo(aFeature) << std::endl;
776 #endif
777       aRecLevel++;
778       addRefsToFeature(aFeature, aMainList,
779                        aRecLevel, aResultRefList/*aMainRefList*/);
780     }
781     theReferences[aMainListFeature] = aResultRefList;
782   }
783 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
784     std::cout << std::endl;
785 #endif
786
787 #ifdef DEBUG_REMOVE_FEATURES
788   printMapInfo(theReferences, "allDependencies");
789 #endif
790 }
791
792 void findRefsToFeatures(const std::set<FeaturePtr>& theFeatures,
793                         const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
794                         std::set<FeaturePtr>& theFeaturesRefsTo)
795 {
796   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
797                                        aLast = theFeatures.end();
798   for (; anIt != aLast; anIt++) {
799     FeaturePtr aFeature = *anIt;
800     if (theReferences.find(aFeature) == theReferences.end())
801       continue;
802     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
803     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
804     for (; aRefIt != aRefLast; aRefIt++) {
805       FeaturePtr aRefFeature = *aRefIt;
806       CompositeFeaturePtr aComposite =
807         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeature);
808       if (aComposite.get() && aComposite->isSub(aFeature))
809         continue; /// composite of the current feature should not be removed
810
811       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
812           theFeaturesRefsTo.find(aRefFeature) == theFeaturesRefsTo.end()) // it is not added
813         theFeaturesRefsTo.insert(aRefFeature);
814     }
815   }
816 }
817
818 void getConcealedResults(const FeaturePtr& theFeature,
819                          std::list<std::shared_ptr<ModelAPI_Result> >& theResults)
820 {
821   SessionPtr aSession = ModelAPI_Session::get();
822
823   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
824   theFeature->data()->referencesToObjects(aRefs);
825   std::list<std::pair<std::string, std::list<ObjectPtr> > >::const_iterator
826                                                   anIt = aRefs.begin(), aLast = aRefs.end();
827   std::set<ResultPtr> alreadyThere; // to avoid duplications
828   for (; anIt != aLast; anIt++) {
829     if (!aSession->validators()->isConcealed(theFeature->getKind(), anIt->first))
830       continue; // use only concealed attributes
831     std::list<ObjectPtr> anObjects = (*anIt).second;
832     std::list<ObjectPtr>::const_iterator anOIt = anObjects.begin(), anOLast = anObjects.end();
833     for (; anOIt != anOLast; anOIt++) {
834       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(*anOIt);
835       if (aResult && aResult->isConcealed()) {
836         if (alreadyThere.find(aResult) == alreadyThere.end()) // issue 1712, avoid duplicates
837           alreadyThere.insert(aResult);
838         else continue;
839         theResults.push_back(aResult);
840       }
841     }
842   }
843 }
844
845 std::pair<std::wstring, bool> getDefaultName(const std::shared_ptr<ModelAPI_Result>& theResult,
846                                              const bool theInherited,
847                                              const bool theRecursive)
848 {
849   typedef std::list< std::pair < std::string, std::list<ObjectPtr> > > ListOfReferences;
850
851   SessionPtr aSession = ModelAPI_Session::get();
852
853   ResultBodyPtr anOwnerRes = bodyOwner(theResult);
854   if (anOwnerRes) {
855     // names of sub-solids in CompSolid should be default (for example,
856     // result of boolean operation 'Boolean_1_1' is a CompSolid which is renamed to 'MyBOOL',
857     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1_1', 'Boolean_1_1_2' etc.)
858     std::wostringstream aDefaultName;
859     aDefaultName << getDefaultName(anOwnerRes).first;
860     aDefaultName << "_" << (bodyIndex(theResult) + 1);
861     return std::pair<std::wstring, bool>(aDefaultName.str(), false);
862   }
863
864   FeaturePtr anOwner = ModelAPI_Feature::feature(theResult->data()->owner());
865   DataPtr aData = anOwner->data();
866
867   ListOfReferences aReferences;
868   // find first result with user-defined name
869   ListOfReferences::const_iterator aFoundRef = aReferences.end();
870   if (theInherited) {
871     aData->referencesToObjects(aReferences);
872
873     for (ListOfReferences::const_iterator aRefIt = aReferences.begin();
874          aRefIt != aReferences.end(); ++aRefIt) {
875       bool isConcealed = aSession->validators()->isConcealed(anOwner->getKind(), aRefIt->first);
876       bool isMainArg = isConcealed &&
877                        aSession->validators()->isMainArgument(anOwner->getKind(), aRefIt->first);
878       if (isConcealed) {
879         // check the referred object is a Body
880         // (for example, ExtrusionCut has a sketch as a first attribute which is concealing)
881         bool isBody = aRefIt->second.size() > 1 || (aRefIt->second.size() == 1 &&
882                       aRefIt->second.front().get() &&
883                       aRefIt->second.front()->groupName() == ModelAPI_ResultBody::group());
884         if (isBody && (isMainArg || aFoundRef == aReferences.end() ||
885             aData->isPrecedingAttribute(aRefIt->first, aFoundRef->first)))
886           aFoundRef = aRefIt;
887
888         if (isMainArg)
889           break;
890       }
891     }
892   }
893   // get the result number in the feature
894   int anIndexInOwner = 0;
895   const std::list<ResultPtr>& anOwnerResults = anOwner->results();
896   std::list<ResultPtr>::const_iterator aResIt = anOwnerResults.cbegin();
897   for(; aResIt != anOwnerResults.cend(); aResIt++) {
898     if(*aResIt == theResult)
899       break;
900     anIndexInOwner++;
901   }
902
903   // find an object which is concealed by theResult
904   if (aFoundRef != aReferences.end() && !aFoundRef->second.empty()) {
905     // store number of references for each object
906     std::map<ResultPtr, int> aNbRefToObject;
907     // search the object by result index
908     std::list<ObjectPtr>::const_iterator anObjIt = aFoundRef->second.begin();
909     int aResultIndex = anIndexInOwner;
910     while (--aResultIndex >= 0) {
911       ResultPtr aCurRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
912       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(aCurRes);
913       if (aParentBody)
914         aCurRes = aParentBody;
915       if (aNbRefToObject.find(aCurRes) == aNbRefToObject.end())
916         aNbRefToObject[aCurRes] = 1;
917       else
918         aNbRefToObject[aCurRes] += 1;
919
920       ++anObjIt;
921       if (anObjIt == aFoundRef->second.end()) {
922         anObjIt = aFoundRef->second.begin();
923         break;
924       }
925     }
926     // check the result is a Body
927     if (anObjIt->get() && (*anObjIt)->groupName() == ModelAPI_ResultBody::group()) {
928       // check the result is part of CompSolid
929       ResultPtr anObjRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
930       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(anObjRes);
931       if (aParentBody)
932         anObjRes = aParentBody;
933
934       // return name of reference result only if it has been renamed by the user,
935       // in other case compose a default name
936       if (anObjRes->data()->hasUserDefinedName() ||
937           (theRecursive && anObjRes->data()->name() != getDefaultName(anObjRes).first)) {
938         std::wstringstream aName;
939         aName << anObjRes->data()->name();
940         std::map<ResultPtr, int>::iterator aFound = aNbRefToObject.find(anObjRes);
941         if (aFound != aNbRefToObject.end()) {
942           // to generate unique name, add suffix if there are several results
943           // referring to the same shape
944           aName << "_" << aFound->second + 1;
945         }
946         return std::pair<std::wstring, bool>(aName.str(), true);
947       }
948     }
949   }
950
951   // compose default name by the name of the feature and the index of result
952   std::wstringstream aDefaultName;
953   aDefaultName << anOwner->name();
954   // if there are several results (issue #899: any number of result),
955   // add unique prefix starting from second
956   if (anIndexInOwner > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
957     aDefaultName << "_" << anIndexInOwner + 1;
958   return std::pair<std::wstring, bool>(aDefaultName.str(), false);
959 }
960
961 std::set<FeaturePtr> getParents(const FeaturePtr& theFeature)
962 {
963   std::set<FeaturePtr> aParents;
964   for (FeaturePtr aCurFeat = theFeature; aCurFeat; ) {
965     CompositeFeaturePtr aFoundComposite;
966     const std::set<AttributePtr>& aRefs = aCurFeat->data()->refsToMe();
967     for (std::set<AttributePtr>::const_iterator anIt = aRefs.begin();
968       anIt != aRefs.end(); ++anIt) {
969       FeaturePtr aF = ModelAPI_Feature::feature((*anIt)->owner());
970       aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aF);
971       if (aFoundComposite && aFoundComposite->isSub(aCurFeat))
972         break;
973       else
974         aFoundComposite = CompositeFeaturePtr();
975     }
976
977     if (aFoundComposite) {
978       aParents.insert(aFoundComposite);
979       aCurFeat = aFoundComposite;
980     }
981     else {
982       // add the part containing high-level feature
983       SessionPtr aSession = ModelAPI_Session::get();
984       DocumentPtr aPartSetDoc = aSession->moduleDocument();
985       std::list<FeaturePtr> aPartSetFeatures = aPartSetDoc->allFeatures();
986       for (std::list<FeaturePtr>::const_iterator anIt = aPartSetFeatures.begin();
987         anIt != aPartSetFeatures.end(); ++anIt) {
988         aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
989         if (aFoundComposite && aFoundComposite->isSub(aCurFeat)) {
990           aParents.insert(aFoundComposite);
991           break;
992         }
993       }
994
995       aCurFeat = FeaturePtr();
996     }
997   }
998   return aParents;
999 }
1000
1001 void fillShapeHierarchy(const GeomShapePtr& theShape,
1002                         const ResultPtr& theContext,
1003                         GeomAPI_ShapeHierarchy& theHierarchy)
1004 {
1005   ResultBodyPtr aResCompSolidPtr = ModelAPI_Tools::bodyOwner(theContext);
1006   if (aResCompSolidPtr.get()) {
1007     std::shared_ptr<GeomAPI_Shape> aContextShape = aResCompSolidPtr->shape();
1008     if (aContextShape->shapeType() <= GeomAPI_Shape::COMPSOLID) {
1009       theHierarchy.addParent(theShape, aContextShape);
1010       fillShapeHierarchy(aContextShape, aResCompSolidPtr, theHierarchy);
1011     }
1012   }
1013 }
1014
1015
1016 void removeResults(const std::list<ResultPtr>& theResults)
1017 {
1018   // collect all documents where the results must be removed
1019   std::map<DocumentPtr, std::list<ResultPtr> > aDocs;
1020
1021   std::list<ResultPtr>::const_iterator aResIter = theResults.cbegin();
1022   for(; aResIter != theResults.cend(); aResIter++) {
1023     DocumentPtr aDoc = (*aResIter)->document();
1024     if (!aDocs.count(aDoc))
1025       aDocs[aDoc] = std::list<ResultPtr>();
1026     aDocs[aDoc].push_back(*aResIter);
1027   }
1028   // create a "remove" feature in each doc
1029   std::map<DocumentPtr, std::list<ResultPtr> >::iterator aDoc = aDocs.begin();
1030   for(; aDoc != aDocs.end(); aDoc++) {
1031     FeaturePtr aRemove = aDoc->first->addFeature("RemoveResults");
1032     if (aRemove) {
1033       for(aResIter = aDoc->second.cbegin(); aResIter != aDoc->second.cend(); aResIter++)
1034         aRemove->selectionList("results")->append(*aResIter, GeomShapePtr());
1035     }
1036   }
1037 }
1038
1039 // used by GUI only
1040 // LCOV_EXCL_START
1041
1042 //**************************************************************
1043 void setDeflection(ResultPtr theResult, const double theDeflection)
1044 {
1045   if (!theResult.get())
1046     return;
1047
1048   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
1049   if (aDeflectionAttr.get() != NULL) {
1050     aDeflectionAttr->setValue(theDeflection);
1051   }
1052 }
1053
1054 double getDeflection(const std::shared_ptr<ModelAPI_Result>& theResult)
1055 {
1056   double aDeflection = -1;
1057   // get deflection from the attribute of the result
1058   if (theResult.get() != NULL &&
1059     theResult->data()->attribute(ModelAPI_Result::DEFLECTION_ID()).get() != NULL) {
1060     AttributeDoublePtr aDoubleAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
1061     if (aDoubleAttr.get() && aDoubleAttr->isInitialized()) {
1062       double aValue = aDoubleAttr->value();
1063       if (aValue > 0) /// zero value should not be used as a deflection(previous studies)
1064         aDeflection = aDoubleAttr->value();
1065     }
1066   }
1067   return aDeflection;
1068 }
1069
1070 //******************************************************
1071 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
1072 {
1073   if (!theResult.get())
1074     return;
1075
1076   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1077   if (aColorAttr.get() != NULL) {
1078     if (!aColorAttr->size()) {
1079       aColorAttr->setSize(3);
1080     }
1081     aColorAttr->setValue(0, theColor[0]);
1082     aColorAttr->setValue(1, theColor[1]);
1083     aColorAttr->setValue(2, theColor[2]);
1084   }
1085 }
1086
1087 void getColor(const std::shared_ptr<ModelAPI_Result>& theResult, std::vector<int>& theColor)
1088 {
1089   theColor.clear();
1090   // get color from the attribute of the result
1091   if (theResult.get() != NULL &&
1092     theResult->data()->attribute(ModelAPI_Result::COLOR_ID()).get() != NULL) {
1093     AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
1094     if (aColorAttr.get() && aColorAttr->size()) {
1095       theColor.push_back(aColorAttr->value(0));
1096       theColor.push_back(aColorAttr->value(1));
1097       theColor.push_back(aColorAttr->value(2));
1098     }
1099   }
1100 }
1101
1102 //******************************************************
1103 void getIsoLines(const std::shared_ptr<ModelAPI_Result>& theResult,
1104   bool& isVisible, std::vector<int>& theNbLines)
1105 {
1106   theNbLines.clear();
1107   isVisible = false;
1108   if (!theResult.get())
1109     return;
1110   if (theResult->groupName() == ModelAPI_ResultConstruction::group()) {
1111     theNbLines.push_back(0);
1112     theNbLines.push_back(0);
1113   }
1114   else {
1115     // get color from the attribute of the result
1116     AttributeIntArrayPtr aAttr = theResult->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
1117     if (aAttr.get()) {
1118       if (aAttr->size()) {
1119         theNbLines.push_back(aAttr->value(0));
1120         theNbLines.push_back(aAttr->value(1));
1121       }
1122     }
1123     AttributeBooleanPtr aBoolAttr =
1124       theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
1125     if (aBoolAttr.get()) {
1126       isVisible = aBoolAttr->value();
1127     }
1128   }
1129 }
1130
1131 //******************************************************
1132 void setIsoLines(ResultPtr theResult, const std::vector<int>& theIso)
1133 {
1134   if (!theResult.get())
1135     return;
1136
1137   AttributeIntArrayPtr aAttr = theResult->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
1138   if (aAttr.get() != NULL) {
1139     if (!aAttr->size()) {
1140       aAttr->setSize(2);
1141     }
1142     aAttr->setValue(0, theIso[0]);
1143     aAttr->setValue(1, theIso[1]);
1144   }
1145 }
1146
1147 //******************************************************
1148 void showIsoLines(std::shared_ptr<ModelAPI_Result> theResult, bool theShow)
1149 {
1150   if (!theResult.get())
1151     return;
1152
1153   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
1154   if (aAttr.get() != NULL) {
1155     aAttr->setValue(theShow);
1156   }
1157 }
1158
1159 //******************************************************
1160 bool isShownIsoLines(std::shared_ptr<ModelAPI_Result> theResult)
1161 {
1162   if (!theResult.get())
1163     return false;
1164
1165   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
1166   if (aAttr.get() != NULL) {
1167     return aAttr->value();
1168   }
1169   return false;
1170 }
1171
1172 //******************************************************
1173 void showEdgesDirection(std::shared_ptr<ModelAPI_Result> theResult, bool theShow)
1174 {
1175   if (!theResult.get())
1176     return;
1177
1178   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::SHOW_EDGES_DIRECTION_ID());
1179   if (aAttr.get() != NULL) {
1180     aAttr->setValue(theShow);
1181   }
1182 }
1183
1184 //******************************************************
1185 bool isShowEdgesDirection(std::shared_ptr<ModelAPI_Result> theResult)
1186 {
1187   if (!theResult.get())
1188     return false;
1189
1190   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::SHOW_EDGES_DIRECTION_ID());
1191   if (aAttr.get() != NULL) {
1192     return aAttr->value();
1193   }
1194   return false;
1195 }
1196
1197 //******************************************************
1198 void bringToFront(std::shared_ptr<ModelAPI_Result> theResult, bool theFlag)
1199 {
1200   if (!theResult.get())
1201     return;
1202
1203   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::BRING_TO_FRONT_ID());
1204   if (aAttr.get() != NULL) {
1205     aAttr->setValue(theFlag);
1206   }
1207 }
1208
1209 //******************************************************
1210 bool isBringToFront(std::shared_ptr<ModelAPI_Result> theResult)
1211 {
1212   if (!theResult.get())
1213     return false;
1214
1215   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::BRING_TO_FRONT_ID());
1216   if (aAttr.get() != NULL) {
1217     return aAttr->value();
1218   }
1219   return false;
1220 }
1221
1222 //**************************************************************
1223 void setTransparency(ResultPtr theResult, double theTransparency)
1224 {
1225   if (!theResult.get())
1226     return;
1227
1228   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1229   if (anAttribute.get() != NULL) {
1230     anAttribute->setValue(theTransparency);
1231   }
1232 }
1233
1234 double getTransparency(const std::shared_ptr<ModelAPI_Result>& theResult)
1235 {
1236   double aTransparency = -1;
1237   // get transparency from the attribute of the result
1238   if (theResult.get() != NULL &&
1239     theResult->data()->attribute(ModelAPI_Result::TRANSPARENCY_ID()).get() != NULL) {
1240     AttributeDoublePtr aDoubleAttr = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1241     if (aDoubleAttr.get() && aDoubleAttr->isInitialized()) {
1242       aTransparency = aDoubleAttr->value();
1243     }
1244   }
1245   return aTransparency;
1246 }
1247
1248 void copyVisualizationAttrs(
1249   std::shared_ptr<ModelAPI_Result> theSource, std::shared_ptr<ModelAPI_Result> theDest)
1250 {
1251   // color
1252   AttributeIntArrayPtr aSourceColor = theSource->data()->intArray(ModelAPI_Result::COLOR_ID());
1253   if (aSourceColor.get() && aSourceColor->isInitialized() && aSourceColor->size()) {
1254     AttributeIntArrayPtr aDestColor = theDest->data()->intArray(ModelAPI_Result::COLOR_ID());
1255     if (aDestColor.get()) {
1256       aDestColor->setSize(aSourceColor->size());
1257       for(int a = 0; a < aSourceColor->size(); a++)
1258         aDestColor->setValue(a, aSourceColor->value(a));
1259     }
1260   }
1261   // Iso-lines
1262   AttributeIntArrayPtr aSource = theSource->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
1263   if (aSource.get() && aSource->isInitialized() && aSource->size()) {
1264     AttributeIntArrayPtr aDest = theDest->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
1265     if (aDest.get()) {
1266       aDest->setSize(aSource->size());
1267       for(int a = 0; a < aSource->size(); a++)
1268         aDest->setValue(a, aSource->value(a));
1269     }
1270   }
1271   // deflection
1272   AttributeDoublePtr aSourceDefl = theSource->data()->real(ModelAPI_Result::DEFLECTION_ID());
1273   if (aSourceDefl.get() && aSourceDefl->isInitialized()) {
1274     AttributeDoublePtr aDestDefl = theDest->data()->real(ModelAPI_Result::DEFLECTION_ID());
1275     if (aDestDefl.get()) {
1276       aDestDefl->setValue(aSourceDefl->value());
1277     }
1278   }
1279   // transparency
1280   AttributeDoublePtr aSourceTransp = theSource->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1281   if (aSourceTransp.get() && aSourceTransp->isInitialized()) {
1282     AttributeDoublePtr aDestTransp = theDest->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
1283     if (aDestTransp.get()) {
1284       aDestTransp->setValue(aSourceTransp->value());
1285     }
1286   }
1287 }
1288
1289
1290 void copyImageAttribute (std::shared_ptr<ModelAPI_Result> theSource,
1291                          std::shared_ptr<ModelAPI_Result> theDest)
1292 {
1293   if (!theSource.get() || !theDest.get())
1294     return;
1295
1296   // images allowed only for ResultBody
1297   ResultBodyPtr aSourceBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theSource);
1298   ResultBodyPtr aDestBody   = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theDest);
1299   if (!aSourceBody.get() || !aDestBody.get())
1300     return;
1301
1302   AttributeImagePtr aSourceImage =
1303     theSource->data()->image(ModelAPI_ResultBody::IMAGE_ID());
1304   if (aSourceImage.get() && aSourceImage->hasTexture()) {
1305     AttributeImagePtr aDestImage =
1306       theDest->data()->image(ModelAPI_ResultBody::IMAGE_ID());
1307     if (aDestImage.get()) {
1308       aSourceImage->copyTo(aDestImage);
1309     }
1310   }
1311 }
1312
1313 std::list<FeaturePtr> referencedFeatures(
1314   std::shared_ptr<ModelAPI_Result> theTarget, const std::string& theFeatureKind,
1315   const bool theSortResults)
1316 {
1317   std::set<FeaturePtr> aResSet; // collect in the set initially to avoid duplicates
1318   std::list<ResultPtr> allSubRes;
1319   allSubRes.push_back(theTarget);
1320   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theTarget);
1321   if (aBody.get())
1322     allSubs(aBody, allSubRes);
1323   std::list<ResultPtr>::iterator aSub = allSubRes.begin();
1324   for(; aSub != allSubRes.end(); aSub++) {
1325     const std::set<AttributePtr>& aRefs = (*aSub)->data()->refsToMe();
1326     std::set<AttributePtr>::const_iterator aRef = aRefs.cbegin();
1327     for(; aRef != aRefs.cend(); aRef++) {
1328       FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1329       if (aFeat.get() && (theFeatureKind.empty() || aFeat->getKind() == theFeatureKind))
1330         aResSet.insert(aFeat);
1331     }
1332   }
1333   // add also feature of the target that may be referenced as a whole
1334   FeaturePtr aTargetFeature = theTarget->document()->feature(theTarget);
1335   const std::set<AttributePtr>& aRefs = aTargetFeature->data()->refsToMe();
1336   std::set<AttributePtr>::const_iterator aRef = aRefs.cbegin();
1337   for(; aRef != aRefs.cend(); aRef++) {
1338     FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1339     if (aFeat.get() && (theFeatureKind.empty() || aFeat->getKind() == theFeatureKind))
1340       aResSet.insert(aFeat);
1341   }
1342   // check also Group-operations that may refer to groups - add them for theFeatureKind "Group"
1343   if (theFeatureKind == "Group") {
1344     std::set<FeaturePtr> aGroupOperations;
1345     for(bool aNeedIterate = true; aNeedIterate; ) {
1346       std::set<FeaturePtr>::iterator aResIter = aResSet.begin();
1347       for(; aResIter != aResSet.end(); aResIter++) {
1348         std::list<ResultPtr>::const_iterator aGroupRes = (*aResIter)->results().cbegin();
1349         for(; aGroupRes != (*aResIter)->results().cend(); aGroupRes++) {
1350           const std::set<AttributePtr>& aGroupRefs = (*aGroupRes)->data()->refsToMe();
1351           std::set<AttributePtr>::const_iterator aRefIt = aGroupRefs.cbegin();
1352           for(; aRefIt != aGroupRefs.cend(); aRefIt++) {
1353             FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
1354             if (aFeat.get() && !aGroupOperations.count(aFeat) && !aFeat->results().empty() &&
1355                 aFeat->firstResult()->groupName() == ModelAPI_ResultGroup::group()) {
1356               // iterate results of this group operation because it may be without theTarget shape
1357               GeomShapePtr aTargetShape = theTarget->shape();
1358               bool anIsIn = false;
1359               std::list<ResultPtr>::const_iterator anOpRes = aFeat->results().cbegin();
1360               for(; anOpRes != aFeat->results().cend() && !anIsIn; anOpRes++) {
1361                 GeomShapePtr anOpShape = (*anOpRes)->shape();
1362                 if (!anOpShape.get() || anOpShape->isNull())
1363                   continue;
1364                 for(GeomAPI_ShapeIterator aSubIt(anOpShape); aSubIt.more(); aSubIt.next()) {
1365                   if (aTargetShape->isSubShape(aSubIt.current(), false)) {
1366                     anIsIn = true;
1367                     break;
1368                   }
1369                 }
1370               }
1371               if (anIsIn)
1372                 aGroupOperations.insert(aFeat);
1373             }
1374           }
1375         }
1376       }
1377       // insert all new group operations into result and if they are, check for next dependencies
1378       aNeedIterate = false;
1379       std::set<FeaturePtr>::iterator aGroupOpIter = aGroupOperations.begin();
1380       for(; aGroupOpIter != aGroupOperations.end(); aGroupOpIter++) {
1381         if (aResSet.find(*aGroupOpIter) == aResSet.end()) {
1382           aResSet.insert(*aGroupOpIter);
1383           aNeedIterate = true;
1384         }
1385       }
1386     }
1387   }
1388
1389   std::list<FeaturePtr> aResList;
1390   std::set<FeaturePtr>::iterator aResIter = aResSet.begin();
1391   for(; aResIter != aResSet.end(); aResIter++) {
1392     if (theSortResults) { // sort results by creation-order
1393       std::list<FeaturePtr>::iterator aListIter = aResList.begin();
1394       for(; aListIter != aResList.end(); aListIter++) {
1395         if ((*aResIter)->document()->isLater(*aListIter, *aResIter))
1396           break;
1397       }
1398       if (aListIter == aResList.end()) // goes to the end
1399         aResList.push_back(*aResIter);
1400       else
1401         aResList.insert(aListIter, *aResIter);
1402     } else //just push to the end unsorted
1403       aResList.push_back(*aResIter);
1404   }
1405   return aResList;
1406 }
1407
1408 void setValues(std::vector<int>& theRGB, const int theRed, const int theGreen, const int theBlue)
1409 {
1410   theRGB.push_back(theRed);
1411   theRGB.push_back(theGreen);
1412   theRGB.push_back(theBlue);
1413 }
1414
1415 std::vector<int> HSVtoRGB(int theH, int theS, int theV)
1416 {
1417   std::vector<int> aRGB;
1418   if (theH < 0 || theH > 360 ||
1419       theS < 0 || theS > 100 ||
1420       theV < 0 || theV > 100)
1421     return aRGB;
1422
1423   int aHi = (int)theH/60;
1424   double aV = theV;
1425   double aVmin = (100 - theS)*theV/100;
1426   double anA = (theV - aVmin)* (theH % 60) / 60;
1427   double aVinc = aVmin + anA;
1428   double aVdec = theV - anA;
1429   double aPercentToValue = 255./100;
1430   int aV_int    = (int)(aV*aPercentToValue);
1431   int aVinc_int = (int)(aVinc*aPercentToValue);
1432   int aVmin_int = (int)(aVmin*aPercentToValue);
1433   int aVdec_int = (int)(aVdec*aPercentToValue);
1434
1435   switch(aHi) {
1436     case 0: setValues(aRGB, aV_int,    aVinc_int, aVmin_int); break;
1437     case 1: setValues(aRGB, aVdec_int, aV_int,    aVmin_int); break;
1438     case 2: setValues(aRGB, aVmin_int, aV_int,    aVinc_int); break;
1439     case 3: setValues(aRGB, aVmin_int, aVdec_int, aV_int); break;
1440     case 4: setValues(aRGB, aVinc_int, aVmin_int, aV_int); break;
1441     case 5: setValues(aRGB, aV_int,    aVmin_int, aVdec_int); break;
1442     default: break;
1443   }
1444   return aRGB;
1445 }
1446
1447 std::array<std::vector<int>, 10> myColorTab = {
1448   std::vector<int> {255, 0, 0},
1449   std::vector<int> {0, 255, 0},
1450   std::vector<int> {0, 0, 255},
1451   std::vector<int> {255, 255, 0},
1452   std::vector<int> {0, 255, 255},
1453   std::vector<int> {255, 0, 255},
1454   std::vector<int> {255, 94, 0},
1455   std::vector<int> {132, 255, 0},
1456   std::vector<int> {132, 0, 255},
1457   std::vector<int> {0, 0, 0},
1458 };
1459
1460 void findRandomColor(std::vector<int>& theValues, bool theReset)
1461 {
1462   static size_t i = 0;
1463   static std::vector<std::vector<int>> usedGeneratedColor;
1464
1465   // True when disabling auto-color
1466   if ( theReset ) {
1467     i = 0;
1468     return;
1469   }
1470
1471   theValues.clear();
1472   if (i < myColorTab.size()) {
1473     theValues = myColorTab[i++];
1474   } else {
1475       int timeout = 0;
1476       std::vector<int> aHSVColor;
1477       std::vector<int> aRGBColor;
1478       do {
1479         aHSVColor = {rand() % 360 , rand() % (100 - 50 + 1) + 50, rand() % (100 - 50 + 1) + 50};
1480         aRGBColor = HSVtoRGB(aHSVColor[0], aHSVColor[1], aHSVColor[2]);
1481         timeout++;
1482       } while (
1483         timeout < 20 &&
1484         std::find(usedGeneratedColor.begin(), usedGeneratedColor.end(), aHSVColor)
1485         != usedGeneratedColor.end() &&
1486         std::find(myColorTab.begin(), myColorTab.end(), aRGBColor) != myColorTab.end());
1487       usedGeneratedColor.push_back(aHSVColor);
1488       theValues = aRGBColor;
1489   }
1490 }
1491
1492 // LCOV_EXCL_STOP
1493
1494 /// Returns name of the higher level feature (Part or feature of PartSet).
1495 static FeaturePtr topOwner(const FeaturePtr& theFeature)
1496 {
1497   FeaturePtr anOwner = theFeature;
1498   while (anOwner.get())
1499   {
1500     FeaturePtr aNextOwner = compositeOwner(anOwner);
1501     if (aNextOwner.get())
1502       anOwner = aNextOwner;
1503     else
1504       break;
1505   }
1506   if (anOwner->document() != ModelAPI_Session::get()->moduleDocument()) // the part-owner name
1507     anOwner = findPartFeature(ModelAPI_Session::get()->moduleDocument(), anOwner->document());
1508   return anOwner;
1509 }
1510
1511 std::wstring validateMovement(const FeaturePtr& theAfter, const std::list<FeaturePtr> theMoved)
1512 {
1513   std::wstring aResult;
1514   if (theMoved.empty())
1515     return aResult; // nothing to move, nothing to check, ok
1516   DocumentPtr aDoc = theAfter.get() ? theAfter->document() : (*(theMoved.cbegin()))->document();
1517   std::set<FeaturePtr> aMoved(theMoved.begin(), theMoved.end()); // fast access to moved
1518   std::set<FeaturePtr> aPassed, aPassedMoved; // all features and all moved before the current one
1519   std::set<FeaturePtr> aPassedAfter; // all passed features after theAfter
1520   bool anAfterIsPassed = theAfter.get() == 0; // flag that iterator already passed theAfter
1521   std::list<FeaturePtr> allFeat = aDoc->allFeatures();
1522   for (std::list<FeaturePtr>::iterator aFeat = allFeat.begin(); aFeat != allFeat.end(); aFeat++)
1523   {
1524     if (!anAfterIsPassed)
1525     {
1526       if (aMoved.count(*aFeat))
1527         aPassedMoved.insert(*aFeat);
1528       else // check aPassedMoved are not referenced by the current feature
1529         aPassed.insert(*aFeat);
1530
1531       anAfterIsPassed = *aFeat == theAfter;
1532       if (anAfterIsPassed && !aPassedMoved.empty())
1533       { // check dependencies of moved relatively to the passed
1534         std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1535         findAllReferences(aPassedMoved, aReferences);
1536         std::map<FeaturePtr, std::set<FeaturePtr> >::iterator aRefIter = aReferences.begin();
1537         for (; aRefIter != aReferences.end(); aRefIter++)
1538         {
1539           if (aPassed.count(aRefIter->first))
1540           {
1541             aResult += topOwner(aRefIter->first)->name() + L" -> ";
1542             // iterate all passed moved to check is it referenced by described feature or not
1543             std::set<FeaturePtr>::iterator aMovedIter = aPassedMoved.begin();
1544             for (; aMovedIter != aPassedMoved.end(); aMovedIter++)
1545             {
1546               std::map<FeaturePtr, std::set<FeaturePtr> > aPassedRefs;
1547               std::set<FeaturePtr> aMovedOne;
1548               aMovedOne.insert(*aMovedIter);
1549               findAllReferences(aMovedOne, aPassedRefs);
1550               if (aPassedRefs.count(aRefIter->first))
1551                 aResult += topOwner(*aMovedIter)->name() + L" ";
1552             }
1553             aResult += L"\n";
1554           }
1555         }
1556       }
1557     }
1558     else // iteration after theAfter
1559     {
1560       if (aMoved.count(*aFeat)) { // check dependencies of moved relatively to ones after theAfter
1561         std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1562         findAllReferences(aPassedAfter, aReferences);
1563         bool aFoundRef = aReferences.find(*aFeat) != aReferences.end();
1564         if (!aFoundRef && !(*aFeat)->results().empty()) // reference may be a feature in moved part
1565         {
1566           ResultPartPtr aFeatPart =
1567             std::dynamic_pointer_cast<ModelAPI_ResultPart>((*aFeat)->firstResult());
1568           if (aFeatPart.get() && aFeatPart->partDoc().get())
1569           {
1570             std::map<FeaturePtr, std::set<FeaturePtr> >::iterator aRef = aReferences.begin();
1571             for (; aRef != aReferences.end() && !aFoundRef; aRef++)
1572               aFoundRef = aRef->first->document() == aFeatPart->partDoc();
1573           }
1574         }
1575
1576         if (aFoundRef)
1577         {
1578           aResult += topOwner(*aFeat)->name() + L" -> ";
1579           std::set<FeaturePtr> aReferencedCount; // to avoid duplicates in the displayed references
1580           // iterate all passed after theAfter to check refers it described feature or not
1581           FeaturePtr aFeatTop = topOwner(*aFeat);
1582           std::set<FeaturePtr>::iterator aPassedIter = aPassedAfter.begin();
1583           for (; aPassedIter != aPassedAfter.end(); aPassedIter++)
1584           {
1585             FeaturePtr aPassedTop = topOwner(*aPassedIter);
1586             if (aReferencedCount.count(aPassedTop))
1587               continue;
1588             std::map<FeaturePtr, std::set<FeaturePtr> > aPassedRefs;
1589             std::set<FeaturePtr> aPassedOne;
1590             aPassedOne.insert(*aPassedIter);
1591             findAllReferences(aPassedOne, aPassedRefs);
1592             std::map<FeaturePtr, std::set<FeaturePtr> >::iterator aPRIter = aPassedRefs.begin();
1593             for (; aPRIter != aPassedRefs.end(); aPRIter++)
1594             {
1595               FeaturePtr aPRTop = topOwner(aPRIter->first);
1596               if (aPRIter->first == *aFeat || aPRIter->first == aFeatTop ||
1597                   aPRTop == *aFeat || aPRTop == aFeatTop)
1598               {
1599                 aResult += aPassedTop->name() + L" ";
1600                 aReferencedCount.insert(aPassedTop);
1601                 break;
1602               }
1603             }
1604           }
1605           aResult += L"\n";
1606         }
1607       }
1608       else {
1609         aPassedAfter.insert(*aFeat);
1610       }
1611     }
1612
1613   }
1614   return aResult;
1615 }
1616
1617 } // namespace ModelAPI_Tools