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