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