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