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