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