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