]> SALOME platform Git repositories - modules/shaper.git/blob - src/ModelAPI/ModelAPI_Tools.cpp
Salome HOME
Merge remote-tracking branch 'origin/EDF_IMPROVEMENTS_2020'
[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 #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().get() &&
651                       aRefIt->second.front()->groupName() == ModelAPI_ResultBody::group());
652         if (isBody && (isMainArg || aFoundRef == aReferences.end() ||
653             aData->isPrecedingAttribute(aRefIt->first, aFoundRef->first)))
654           aFoundRef = aRefIt;
655
656         if (isMainArg)
657           break;
658       }
659     }
660   }
661   // get the result number in the feature
662   int anIndexInOwner = 0;
663   const std::list<ResultPtr>& anOwnerResults = anOwner->results();
664   std::list<ResultPtr>::const_iterator aResIt = anOwnerResults.cbegin();
665   for(; aResIt != anOwnerResults.cend(); aResIt++) {
666     if(*aResIt == theResult)
667       break;
668     anIndexInOwner++;
669   }
670
671   // find an object which is concealed by theResult
672   if (aFoundRef != aReferences.end() && !aFoundRef->second.empty()) {
673     // store number of references for each object
674     std::map<ResultPtr, int> aNbRefToObject;
675     // search the object by result index
676     std::list<ObjectPtr>::const_iterator anObjIt = aFoundRef->second.begin();
677     int aResultIndex = anIndexInOwner;
678     while (--aResultIndex >= 0) {
679       ResultPtr aCurRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
680       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(aCurRes);
681       if (aParentBody)
682         aCurRes = aParentBody;
683       if (aNbRefToObject.find(aCurRes) == aNbRefToObject.end())
684         aNbRefToObject[aCurRes] = 1;
685       else
686         aNbRefToObject[aCurRes] += 1;
687
688       ++anObjIt;
689       if (anObjIt == aFoundRef->second.end()) {
690         anObjIt = aFoundRef->second.begin();
691         break;
692       }
693     }
694     // check the result is a Body
695     if ((*anObjIt)->groupName() == ModelAPI_ResultBody::group()) {
696       // check the result is part of CompSolid
697       ResultPtr anObjRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
698       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(anObjRes);
699       if (aParentBody)
700         anObjRes = aParentBody;
701
702       // return name of reference result only if it has been renamed by the user,
703       // in other case compose a default name
704       if (anObjRes->data()->hasUserDefinedName()) {
705         std::stringstream aName;
706         aName << anObjRes->data()->name();
707         std::map<ResultPtr, int>::iterator aFound = aNbRefToObject.find(anObjRes);
708         if (aFound != aNbRefToObject.end()) {
709           // to generate unique name, add suffix if there are several results
710           // referring to the same shape
711           aName << "_" << aFound->second + 1;
712         }
713         return std::pair<std::string, bool>(aName.str(), true);
714       }
715     }
716   }
717
718   // compose default name by the name of the feature and the index of result
719   std::stringstream aDefaultName;
720   aDefaultName << anOwner->name();
721   // if there are several results (issue #899: any number of result),
722   // add unique prefix starting from second
723   if (anIndexInOwner > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
724     aDefaultName << "_" << anIndexInOwner + 1;
725   return std::pair<std::string, bool>(aDefaultName.str(), false);
726 }
727
728 std::set<FeaturePtr> getParents(const FeaturePtr& theFeature)
729 {
730   std::set<FeaturePtr> aParents;
731   for (FeaturePtr aCurFeat = theFeature; aCurFeat; ) {
732     CompositeFeaturePtr aFoundComposite;
733     const std::set<AttributePtr>& aRefs = aCurFeat->data()->refsToMe();
734     for (std::set<AttributePtr>::const_iterator anIt = aRefs.begin();
735       anIt != aRefs.end(); ++anIt) {
736       FeaturePtr aF = ModelAPI_Feature::feature((*anIt)->owner());
737       aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aF);
738       if (aFoundComposite && aFoundComposite->isSub(aCurFeat))
739         break;
740       else
741         aFoundComposite = CompositeFeaturePtr();
742     }
743
744     if (aFoundComposite) {
745       aParents.insert(aFoundComposite);
746       aCurFeat = aFoundComposite;
747     }
748     else {
749       // add the part containing high-level feature
750       SessionPtr aSession = ModelAPI_Session::get();
751       DocumentPtr aPartSetDoc = aSession->moduleDocument();
752       std::list<FeaturePtr> aPartSetFeatures = aPartSetDoc->allFeatures();
753       for (std::list<FeaturePtr>::const_iterator anIt = aPartSetFeatures.begin();
754         anIt != aPartSetFeatures.end(); ++anIt) {
755         aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
756         if (aFoundComposite && aFoundComposite->isSub(aCurFeat)) {
757           aParents.insert(aFoundComposite);
758           break;
759         }
760       }
761
762       aCurFeat = FeaturePtr();
763     }
764   }
765   return aParents;
766 }
767
768 void removeResults(const std::list<ResultPtr>& theResults)
769 {
770   // collect all documents where the results must be removed
771   std::map<DocumentPtr, std::list<ResultPtr> > aDocs;
772
773   std::list<ResultPtr>::const_iterator aResIter = theResults.cbegin();
774   for(; aResIter != theResults.cend(); aResIter++) {
775     DocumentPtr aDoc = (*aResIter)->document();
776     if (!aDocs.count(aDoc))
777       aDocs[aDoc] = std::list<ResultPtr>();
778     aDocs[aDoc].push_back(*aResIter);
779   }
780   // create a "remove" feature in each doc
781   std::map<DocumentPtr, std::list<ResultPtr> >::iterator aDoc = aDocs.begin();
782   for(; aDoc != aDocs.end(); aDoc++) {
783     FeaturePtr aRemove = aDoc->first->addFeature("RemoveResults");
784     if (aRemove) {
785       for(aResIter = aDoc->second.cbegin(); aResIter != aDoc->second.cend(); aResIter++)
786         aRemove->selectionList("results")->append(*aResIter, GeomShapePtr());
787     }
788   }
789 }
790
791
792 //**************************************************************
793 void setDeflection(ResultPtr theResult, const double theDeflection)
794 {
795   if (!theResult.get())
796     return;
797
798   AttributeDoublePtr aDeflectionAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
799   if (aDeflectionAttr.get() != NULL) {
800     aDeflectionAttr->setValue(theDeflection);
801   }
802 }
803
804 // used by GUI only
805 // LCOV_EXCL_START
806 double getDeflection(const std::shared_ptr<ModelAPI_Result>& theResult)
807 {
808   double aDeflection = -1;
809   // get deflection from the attribute of the result
810   if (theResult.get() != NULL &&
811     theResult->data()->attribute(ModelAPI_Result::DEFLECTION_ID()).get() != NULL) {
812     AttributeDoublePtr aDoubleAttr = theResult->data()->real(ModelAPI_Result::DEFLECTION_ID());
813     if (aDoubleAttr.get() && aDoubleAttr->isInitialized()) {
814       double aValue = aDoubleAttr->value();
815       if (aValue > 0) /// zero value should not be used as a deflection(previous studies)
816         aDeflection = aDoubleAttr->value();
817     }
818   }
819   return aDeflection;
820 }
821
822 //******************************************************
823 void setColor(ResultPtr theResult, const std::vector<int>& theColor)
824 {
825   if (!theResult.get())
826     return;
827
828   AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
829   if (aColorAttr.get() != NULL) {
830     if (!aColorAttr->size()) {
831       aColorAttr->setSize(3);
832     }
833     aColorAttr->setValue(0, theColor[0]);
834     aColorAttr->setValue(1, theColor[1]);
835     aColorAttr->setValue(2, theColor[2]);
836   }
837 }
838
839 void getColor(const std::shared_ptr<ModelAPI_Result>& theResult, std::vector<int>& theColor)
840 {
841   theColor.clear();
842   // get color from the attribute of the result
843   if (theResult.get() != NULL &&
844     theResult->data()->attribute(ModelAPI_Result::COLOR_ID()).get() != NULL) {
845     AttributeIntArrayPtr aColorAttr = theResult->data()->intArray(ModelAPI_Result::COLOR_ID());
846     if (aColorAttr.get() && aColorAttr->size()) {
847       theColor.push_back(aColorAttr->value(0));
848       theColor.push_back(aColorAttr->value(1));
849       theColor.push_back(aColorAttr->value(2));
850     }
851   }
852 }
853
854 //******************************************************
855 void getIsoLines(const std::shared_ptr<ModelAPI_Result>& theResult,
856   bool& isVisible, std::vector<int>& theNbLines)
857 {
858   theNbLines.clear();
859   isVisible = false;
860   if (!theResult.get())
861     return;
862   if (theResult->groupName() == ModelAPI_ResultConstruction::group()) {
863     theNbLines.push_back(0);
864     theNbLines.push_back(0);
865   }
866   else {
867     // get color from the attribute of the result
868     AttributeIntArrayPtr aAttr = theResult->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
869     if (aAttr.get()) {
870       if (aAttr->size()) {
871         theNbLines.push_back(aAttr->value(0));
872         theNbLines.push_back(aAttr->value(1));
873       }
874     }
875     AttributeBooleanPtr aBoolAttr =
876       theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
877     if (aBoolAttr.get()) {
878       isVisible = aBoolAttr->value();
879     }
880   }
881 }
882
883 //******************************************************
884 void setIsoLines(ResultPtr theResult, const std::vector<int>& theIso)
885 {
886   if (!theResult.get())
887     return;
888
889   AttributeIntArrayPtr aAttr = theResult->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
890   if (aAttr.get() != NULL) {
891     if (!aAttr->size()) {
892       aAttr->setSize(2);
893     }
894     aAttr->setValue(0, theIso[0]);
895     aAttr->setValue(1, theIso[1]);
896   }
897 }
898
899 //******************************************************
900 void showIsoLines(std::shared_ptr<ModelAPI_Result> theResult, bool theShow)
901 {
902   if (!theResult.get())
903     return;
904
905   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
906   if (aAttr.get() != NULL) {
907     aAttr->setValue(theShow);
908   }
909 }
910
911 //******************************************************
912 bool isShownIsoLines(std::shared_ptr<ModelAPI_Result> theResult)
913 {
914   if (!theResult.get())
915     return false;
916
917   AttributeBooleanPtr aAttr = theResult->data()->boolean(ModelAPI_Result::SHOW_ISO_LINES_ID());
918   if (aAttr.get() != NULL) {
919     return aAttr->value();
920   }
921   return false;
922 }
923
924 //**************************************************************
925 void setTransparency(ResultPtr theResult, double theTransparency)
926 {
927   if (!theResult.get())
928     return;
929
930   AttributeDoublePtr anAttribute = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
931   if (anAttribute.get() != NULL) {
932     anAttribute->setValue(theTransparency);
933   }
934 }
935
936 double getTransparency(const std::shared_ptr<ModelAPI_Result>& theResult)
937 {
938   double aTransparency = -1;
939   // get transparency from the attribute of the result
940   if (theResult.get() != NULL &&
941     theResult->data()->attribute(ModelAPI_Result::TRANSPARENCY_ID()).get() != NULL) {
942     AttributeDoublePtr aDoubleAttr = theResult->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
943     if (aDoubleAttr.get() && aDoubleAttr->isInitialized()) {
944       aTransparency = aDoubleAttr->value();
945     }
946   }
947   return aTransparency;
948 }
949 // LCOV_EXCL_STOP
950
951 void copyVisualizationAttrs(
952   std::shared_ptr<ModelAPI_Result> theSource, std::shared_ptr<ModelAPI_Result> theDest)
953 {
954   // color
955   AttributeIntArrayPtr aSourceColor = theSource->data()->intArray(ModelAPI_Result::COLOR_ID());
956   if (aSourceColor.get() && aSourceColor->isInitialized() && aSourceColor->size()) {
957     AttributeIntArrayPtr aDestColor = theDest->data()->intArray(ModelAPI_Result::COLOR_ID());
958     if (aDestColor.get()) {
959       aDestColor->setSize(aSourceColor->size());
960       for(int a = 0; a < aSourceColor->size(); a++)
961         aDestColor->setValue(a, aSourceColor->value(a));
962     }
963   }
964   // Iso-lines
965   AttributeIntArrayPtr aSource = theSource->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
966   if (aSource.get() && aSource->isInitialized() && aSource->size()) {
967     AttributeIntArrayPtr aDest = theDest->data()->intArray(ModelAPI_Result::ISO_LINES_ID());
968     if (aDest.get()) {
969       aDest->setSize(aSource->size());
970       for(int a = 0; a < aSource->size(); a++)
971         aDest->setValue(a, aSource->value(a));
972     }
973   }
974   // deflection
975   AttributeDoublePtr aSourceDefl = theSource->data()->real(ModelAPI_Result::DEFLECTION_ID());
976   if (aSourceDefl.get() && aSourceDefl->isInitialized()) {
977     AttributeDoublePtr aDestDefl = theDest->data()->real(ModelAPI_Result::DEFLECTION_ID());
978     if (aDestDefl.get()) {
979       aDestDefl->setValue(aSourceDefl->value());
980     }
981   }
982   // transparency
983   AttributeDoublePtr aSourceTransp = theSource->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
984   if (aSourceTransp.get() && aSourceTransp->isInitialized()) {
985     AttributeDoublePtr aDestTransp = theDest->data()->real(ModelAPI_Result::TRANSPARENCY_ID());
986     if (aDestTransp.get()) {
987       aDestTransp->setValue(aSourceTransp->value());
988     }
989   }
990 }
991
992 std::list<FeaturePtr> referencedFeatures(
993   std::shared_ptr<ModelAPI_Result> theTarget, const std::string& theFeatureKind,
994   const bool theSortResults)
995 {
996   std::set<FeaturePtr> aResSet; // collect in the set initially to avoid duplicates
997   std::list<ResultPtr> allSubRes;
998   allSubRes.push_back(theTarget);
999   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theTarget);
1000   if (aBody.get())
1001     allSubs(aBody, allSubRes);
1002   std::list<ResultPtr>::iterator aSub = allSubRes.begin();
1003   for(; aSub != allSubRes.end(); aSub++) {
1004     const std::set<AttributePtr>& aRefs = (*aSub)->data()->refsToMe();
1005     std::set<AttributePtr>::const_iterator aRef = aRefs.cbegin();
1006     for(; aRef != aRefs.cend(); aRef++) {
1007       FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1008       if (aFeat.get() && (theFeatureKind.empty() || aFeat->getKind() == theFeatureKind))
1009         aResSet.insert(aFeat);
1010     }
1011   }
1012   // add also feature of the target that may be referenced as a whole
1013   FeaturePtr aTargetFeature = theTarget->document()->feature(theTarget);
1014   const std::set<AttributePtr>& aRefs = aTargetFeature->data()->refsToMe();
1015   std::set<AttributePtr>::const_iterator aRef = aRefs.cbegin();
1016   for(; aRef != aRefs.cend(); aRef++) {
1017     FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1018     if (aFeat.get() && (theFeatureKind.empty() || aFeat->getKind() == theFeatureKind))
1019       aResSet.insert(aFeat);
1020   }
1021
1022   std::list<FeaturePtr> aResList;
1023   std::set<FeaturePtr>::iterator aResIter = aResSet.begin();
1024   for(; aResIter != aResSet.end(); aResIter++) {
1025     if (theSortResults) { // sort results by creation-order
1026       std::list<FeaturePtr>::iterator aListIter = aResList.begin();
1027       for(; aListIter != aResList.end(); aListIter++) {
1028         if ((*aResIter)->document()->isLater(*aListIter, *aResIter))
1029           break;
1030       }
1031       if (aListIter == aResList.end()) // goes to the end
1032         aResList.push_back(*aResIter);
1033       else
1034         aResList.insert(aListIter, *aResIter);
1035     } else //just push to the end unsorted
1036       aResList.push_back(*aResIter);
1037   }
1038   return aResList;
1039 }
1040
1041 } // namespace ModelAPI_Tools