Salome HOME
Fix for the issue #2892 : Group in error when loading dump from Test2241.py
[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 // LCOV_EXCL_START
110 const char* toString(ModelAPI_ExecState theExecState)
111 {
112   switch (theExecState) {
113   case ModelAPI_StateDone: return "Done";
114   case ModelAPI_StateMustBeUpdated: return "Must be updated";
115   case ModelAPI_StateExecFailed: return "Execution failed";
116   case ModelAPI_StateInvalidArgument: return "Invalid argument";
117   case ModelAPI_StateNothing: return "Empty state";
118   default: return "Unknown ExecState.";
119   }
120 }
121
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              const bool theLowerOnly) {
306   // iterate sub-bodies of compsolid
307   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
308   if (aComp.get()) {
309     int aNumSub = aComp->numberOfSubs();
310     for (int a = 0; a < aNumSub; a++) {
311       ResultBodyPtr aSub = aComp->subResult(a);
312       if (!theLowerOnly || aSub->numberOfSubs() == 0)
313         theResults.push_back(aSub);
314       allSubs(aSub, theResults);
315     }
316   }
317 }
318
319 void allResults(const FeaturePtr& theFeature, std::list<ResultPtr>& theResults)
320 {
321   if (!theFeature.get()) // safety: for empty feature no results
322     return;
323   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
324   std::list<ResultPtr>::const_iterator aRIter = aResults.begin();
325   for (; aRIter != aResults.cend(); aRIter++) {
326     theResults.push_back(*aRIter);
327     ResultBodyPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRIter);
328     allSubs(aResult, theResults);
329   }
330 }
331
332 //******************************************************************
333 bool allDocumentsActivated(std::string& theNotActivatedNames)
334 {
335   theNotActivatedNames = "";
336   bool anAllPartActivated = true;
337
338   DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
339   int aSize = aRootDoc->size(ModelAPI_ResultPart::group());
340   for (int i = 0; i < aSize; i++) {
341     ObjectPtr aObject = aRootDoc->object(ModelAPI_ResultPart::group(), i);
342     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aObject);
343     if (!aPart->isActivated()) {
344       anAllPartActivated = false;
345       if (!theNotActivatedNames.empty())
346         theNotActivatedNames += ", ";
347       theNotActivatedNames += aObject->data()->name().c_str();
348     }
349   }
350   return anAllPartActivated;
351 }
352
353 bool removeFeaturesAndReferences(const std::set<FeaturePtr>& theFeatures,
354                                  const bool theFlushRedisplay,
355                                  const bool theUseComposite,
356                                  const bool theUseRecursion)
357 {
358 #ifdef DEBUG_REMOVE_FEATURES
359   printListInfo(theFeatures, "selection: ");
360 #endif
361
362   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
363   ModelAPI_Tools::findAllReferences(theFeatures, aReferences, theUseComposite, theUseRecursion);
364 #ifdef DEBUG_REMOVE_FEATURES
365   printMapInfo(aReferences, "allDependencies: ");
366 #endif
367
368   std::set<FeaturePtr> aFeaturesRefsTo;
369   ModelAPI_Tools::findRefsToFeatures(theFeatures, aReferences, aFeaturesRefsTo);
370 #ifdef DEBUG_REMOVE_FEATURES
371   printListInfo(aFeaturesRefsTo, "references: ");
372 #endif
373
374   std::set<FeaturePtr> aFeatures = theFeatures;
375   if (!aFeaturesRefsTo.empty())
376     aFeatures.insert(aFeaturesRefsTo.begin(), aFeaturesRefsTo.end());
377 #ifdef DEBUG_REMOVE_FEATURES
378   printListInfo(aFeatures, "removeFeatures: ");
379 #endif
380
381   return ModelAPI_Tools::removeFeatures(aFeatures, false);
382 }
383
384 //***********************************************************************
385 bool removeFeatures(const std::set<FeaturePtr>& theFeatures,
386                     const bool theFlushRedisplay)
387 {
388   bool isDone = false;
389   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
390                                        aLast = theFeatures.end();
391   for (; anIt != aLast; anIt++) {
392     FeaturePtr aFeature = *anIt;
393     if (aFeature.get()) {
394       DocumentPtr aDoc = aFeature->document();
395       // flush REDISPLAY signal after remove feature
396       aDoc->removeFeature(aFeature);
397       isDone = true;
398     }
399   }
400   if (isDone && theFlushRedisplay) {
401     // the redisplay signal should be flushed in order to erase
402     // the feature presentation in the viewer
403     // if should be done after removeFeature() of document
404     Events_Loop::loop()->flush(Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY));
405   }
406   return true;
407 }
408
409 //***********************************************************************
410 // Fills the references list by all references of the feature from the references map.
411 // This is a recusive method to find references by next found feature in the map of references.
412 // \param theFeature a feature to find references
413 // \param theReferencesMap a map of references
414 // \param theReferences an out container of references
415 void addRefsToFeature(const FeaturePtr& theFeature,
416                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferencesMap,
417                       int theRecLevel,
418                       std::set<FeaturePtr>& theReferences)
419 {
420   if (theRecLevel > RECURSE_TOP_LEVEL)
421     return;
422   theRecLevel++;
423
424   if (theReferencesMap.find(theFeature) == theReferencesMap.end())
425     return; // this feature is not in the selection list, so exists without references to it
426   std::set<FeaturePtr> aMainReferences = theReferencesMap.at(theFeature);
427
428   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
429                                        aLast = aMainReferences.end();
430   for (; anIt != aLast; anIt++) {
431     FeaturePtr aRefFeature = *anIt;
432     if (theReferences.find(aRefFeature) == theReferences.end()) {
433       addRefsToFeature(aRefFeature, theReferencesMap, theRecLevel, theReferences);
434       theReferences.insert(aRefFeature);
435     }
436   }
437 }
438
439 // For each feature from the feature list it searches references to the feature and append them
440 // to the references map. This is a recusive method.
441 // \param theFeature a feature to find references
442 // \param theReferencesMap a map of references
443 // \param theReferences an out container of references
444 void findReferences(const std::set<FeaturePtr>& theFeatures,
445                     std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
446                     const bool theUseComposite, const bool theUseRecursion, int theRecLevel)
447 {
448   if (theRecLevel > RECURSE_TOP_LEVEL)
449     return;
450   theRecLevel++;
451   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
452                                         aLast = theFeatures.end();
453   for (; anIt != aLast; anIt++) {
454     FeaturePtr aFeature = *anIt;
455     if (aFeature.get() && theReferences.find(aFeature) == theReferences.end()) {
456       DocumentPtr aSelFeatureDoc = aFeature->document();
457       std::set<FeaturePtr> aSelRefFeatures;
458       aSelFeatureDoc->refsToFeature(aFeature, aSelRefFeatures, false/*do not emit signals*/);
459       if (theUseComposite) { // do not filter selection
460         theReferences[aFeature] = aSelRefFeatures;
461       }
462       else { // filter references to skip composition features of the current feature
463         std::set<FeaturePtr> aFilteredFeatures;
464         std::set<FeaturePtr>::const_iterator anIt = aSelRefFeatures.begin(),
465                                              aLast = aSelRefFeatures.end();
466         for (; anIt != aLast; anIt++) {
467           FeaturePtr aCFeature = *anIt;
468           CompositeFeaturePtr aComposite =
469             std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCFeature);
470           if (aComposite.get() && aComposite->isSub(aFeature))
471             continue; /// composite of the current feature should be skipped
472           aFilteredFeatures.insert(aCFeature);
473         }
474         theReferences[aFeature] = aFilteredFeatures;
475       }
476       if (theUseRecursion) {
477 #ifdef DEBUG_CYCLING_1550
478         findReferences(aSelRefFeatures, theReferences, theUseComposite,
479                        theUseRecursion, theRecLevel);
480 #else
481         findReferences(theReferences[aFeature], theReferences, theUseComposite, theUseRecursion,
482                        theRecLevel);
483 #endif
484       }
485     }
486   }
487 }
488
489 void findAllReferences(const std::set<FeaturePtr>& theFeatures,
490                        std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
491                        const bool theUseComposite,
492                        const bool theUseRecursion)
493 {
494   // For dependencies, find main_list:
495   // sk_1(ext_1, vertex_1)
496   // ext_1(bool_1, sk_3)
497   // vertex_1()
498   // sk_2(ext_2)
499   // ext_2(bool_2)
500   // sk_3()
501   // Information: bool_1 is not selected, ext_2(bool_2) exists
502   // find all referenced features
503   std::map<FeaturePtr, std::set<FeaturePtr> > aMainList;
504   int aRecLevel = 0;
505   findReferences(theFeatures, aMainList, theUseComposite, theUseRecursion, aRecLevel);
506
507 #ifdef DEBUG_REMOVE_FEATURES
508   printMapInfo(aMainList, "firstDependencies");
509 #endif
510   // find all dependencies for each object:
511   // sk_1(ext_1, vertex_1) + (sk_3, bool_1)
512   // ext_1(bool_1, sk_3)
513   // vertex_1()
514   // sk_2(ext_2) + (bool_1)
515   // ext_2(bool_1)
516   // sk_3()
517   std::map<FeaturePtr, std::set<FeaturePtr> >::const_iterator aMainIt = aMainList.begin(),
518                                                               aMainLast = aMainList.end();
519   for (; aMainIt != aMainLast; aMainIt++) {
520     FeaturePtr aMainListFeature = aMainIt->first;
521
522     //std::string aName = aMainListFeature->name();
523     std::set<FeaturePtr> aMainRefList = aMainIt->second;
524
525 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
526     char aBuf[50];
527     int n = sprintf(aBuf, "%d", aMainRefList.size());
528     std::string aSize(aBuf);
529     std::cout << "_findAllReferences for the Feature: " << getFeatureInfo(aMainListFeature)
530               << ", references size = " << aSize << std::endl;
531 #endif
532     std::set<FeaturePtr>::const_iterator anIt = aMainRefList.begin(),
533                                          aLast = aMainRefList.end();
534     std::set<FeaturePtr> aResultRefList;
535     aResultRefList.insert(aMainRefList.begin(), aMainRefList.end());
536     for (; anIt != aLast; anIt++) {
537       FeaturePtr aFeature = *anIt;
538       int aRecLevel = 0;
539 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
540       std::cout << " Ref: " << getFeatureInfo(aFeature) << std::endl;
541 #endif
542       aRecLevel++;
543       addRefsToFeature(aFeature, aMainList,
544                        aRecLevel, aResultRefList/*aMainRefList*/);
545     }
546     theReferences[aMainListFeature] = aResultRefList;
547   }
548 #ifdef DEBUG_REMOVE_FEATURES_RECURSE
549     std::cout << std::endl;
550 #endif
551
552 #ifdef DEBUG_REMOVE_FEATURES
553   printMapInfo(theReferences, "allDependencies");
554 #endif
555 }
556
557 void findRefsToFeatures(const std::set<FeaturePtr>& theFeatures,
558                         const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
559                         std::set<FeaturePtr>& theFeaturesRefsTo)
560 {
561   std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
562                                        aLast = theFeatures.end();
563   for (; anIt != aLast; anIt++) {
564     FeaturePtr aFeature = *anIt;
565     if (theReferences.find(aFeature) == theReferences.end())
566       continue;
567     std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
568     std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
569     for (; aRefIt != aRefLast; aRefIt++) {
570       FeaturePtr aRefFeature = *aRefIt;
571       CompositeFeaturePtr aComposite =
572         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeature);
573       if (aComposite.get() && aComposite->isSub(aFeature))
574         continue; /// composite of the current feature should not be removed
575
576       if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
577           theFeaturesRefsTo.find(aRefFeature) == theFeaturesRefsTo.end()) // it is not added
578         theFeaturesRefsTo.insert(aRefFeature);
579     }
580   }
581 }
582
583 void getConcealedResults(const FeaturePtr& theFeature,
584                          std::list<std::shared_ptr<ModelAPI_Result> >& theResults)
585 {
586   SessionPtr aSession = ModelAPI_Session::get();
587
588   std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
589   theFeature->data()->referencesToObjects(aRefs);
590   std::list<std::pair<std::string, std::list<ObjectPtr> > >::const_iterator
591                                                   anIt = aRefs.begin(), aLast = aRefs.end();
592   std::set<ResultPtr> alreadyThere; // to avoid duplications
593   for (; anIt != aLast; anIt++) {
594     if (!aSession->validators()->isConcealed(theFeature->getKind(), anIt->first))
595       continue; // use only concealed attributes
596     std::list<ObjectPtr> anObjects = (*anIt).second;
597     std::list<ObjectPtr>::const_iterator anOIt = anObjects.begin(), anOLast = anObjects.end();
598     for (; anOIt != anOLast; anOIt++) {
599       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(*anOIt);
600       if (aResult && aResult->isConcealed()) {
601         if (alreadyThere.find(aResult) == alreadyThere.end()) // issue 1712, avoid duplicates
602           alreadyThere.insert(aResult);
603         else continue;
604         theResults.push_back(aResult);
605       }
606     }
607   }
608 }
609
610 std::pair<std::string, bool> getDefaultName(const std::shared_ptr<ModelAPI_Result>& theResult,
611                                             const bool theInherited)
612 {
613   typedef std::list< std::pair < std::string, std::list<ObjectPtr> > > ListOfReferences;
614
615   SessionPtr aSession = ModelAPI_Session::get();
616
617   ResultBodyPtr anOwnerRes = bodyOwner(theResult);
618   if (anOwnerRes) {
619     // names of sub-solids in CompSolid should be default (for example,
620     // result of boolean operation 'Boolean_1_1' is a CompSolid which is renamed to 'MyBOOL',
621     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1_1', 'Boolean_1_1_2' etc.)
622     std::ostringstream aDefaultName;
623     aDefaultName << getDefaultName(anOwnerRes).first;
624     aDefaultName << "_" << (bodyIndex(theResult) + 1);
625     return std::pair<std::string, bool>(aDefaultName.str(), false);
626   }
627
628   FeaturePtr anOwner = ModelAPI_Feature::feature(theResult->data()->owner());
629   DataPtr aData = anOwner->data();
630
631   ListOfReferences aReferences;
632   // find first result with user-defined name
633   ListOfReferences::const_iterator aFoundRef = aReferences.end();
634   if (theInherited) {
635     aData->referencesToObjects(aReferences);
636
637     for (ListOfReferences::const_iterator aRefIt = aReferences.begin();
638          aRefIt != aReferences.end(); ++aRefIt) {
639       bool isConcealed = aSession->validators()->isConcealed(anOwner->getKind(), aRefIt->first);
640       bool isMainArg = isConcealed &&
641                        aSession->validators()->isMainArgument(anOwner->getKind(), aRefIt->first);
642       if (isConcealed) {
643         // check the referred object is a Body
644         // (for example, ExtrusionCut has a sketch as a first attribute which is concealing)
645         bool isBody = aRefIt->second.size() > 1 || (aRefIt->second.size() == 1 &&
646                       aRefIt->second.front()->groupName() == ModelAPI_ResultBody::group());
647         if (isBody && (isMainArg || aFoundRef == aReferences.end() ||
648             aData->isPrecedingAttribute(aRefIt->first, aFoundRef->first)))
649           aFoundRef = aRefIt;
650
651         if (isMainArg)
652           break;
653       }
654     }
655   }
656   // get the result number in the feature
657   int anIndexInOwner = 0;
658   const std::list<ResultPtr>& anOwnerResults = anOwner->results();
659   std::list<ResultPtr>::const_iterator aResIt = anOwnerResults.cbegin();
660   for(; aResIt != anOwnerResults.cend(); aResIt++) {
661     if(*aResIt == theResult)
662       break;
663     anIndexInOwner++;
664   }
665
666   // find an object which is concealed by theResult
667   if (aFoundRef != aReferences.end() && !aFoundRef->second.empty()) {
668     // store number of references for each object
669     std::map<ResultPtr, int> aNbRefToObject;
670     // search the object by result index
671     std::list<ObjectPtr>::const_iterator anObjIt = aFoundRef->second.begin();
672     int aResultIndex = anIndexInOwner;
673     while (--aResultIndex >= 0) {
674       ResultPtr aCurRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
675       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(aCurRes);
676       if (aParentBody)
677         aCurRes = aParentBody;
678       if (aNbRefToObject.find(aCurRes) == aNbRefToObject.end())
679         aNbRefToObject[aCurRes] = 1;
680       else
681         aNbRefToObject[aCurRes] += 1;
682
683       ++anObjIt;
684       if (anObjIt == aFoundRef->second.end()) {
685         anObjIt = aFoundRef->second.begin();
686         break;
687       }
688     }
689     // check the result is a Body
690     if ((*anObjIt)->groupName() == ModelAPI_ResultBody::group()) {
691       // check the result is part of CompSolid
692       ResultPtr anObjRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
693       ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(anObjRes);
694       if (aParentBody)
695         anObjRes = aParentBody;
696
697       // return name of reference result only if it has been renamed by the user,
698       // in other case compose a default name
699       if (anObjRes->data()->hasUserDefinedName()) {
700         std::stringstream aName;
701         aName << anObjRes->data()->name();
702         std::map<ResultPtr, int>::iterator aFound = aNbRefToObject.find(anObjRes);
703         if (aFound != aNbRefToObject.end()) {
704           // to generate unique name, add suffix if there are several results
705           // referring to the same shape
706           aName << "_" << aFound->second + 1;
707         }
708         return std::pair<std::string, bool>(aName.str(), true);
709       }
710     }
711   }
712
713   // compose default name by the name of the feature and the index of result
714   std::stringstream aDefaultName;
715   aDefaultName << anOwner->name();
716   // if there are several results (issue #899: any number of result),
717   // add unique prefix starting from second
718   if (anIndexInOwner > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
719     aDefaultName << "_" << anIndexInOwner + 1;
720   return std::pair<std::string, bool>(aDefaultName.str(), false);
721 }
722
723 std::set<FeaturePtr> getParents(const FeaturePtr& theFeature)
724 {
725   std::set<FeaturePtr> aParents;
726   for (FeaturePtr aCurFeat = theFeature; aCurFeat; ) {
727     CompositeFeaturePtr aFoundComposite;
728     const std::set<AttributePtr>& aRefs = aCurFeat->data()->refsToMe();
729     for (std::set<AttributePtr>::const_iterator anIt = aRefs.begin();
730       anIt != aRefs.end(); ++anIt) {
731       FeaturePtr aF = ModelAPI_Feature::feature((*anIt)->owner());
732       aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aF);
733       if (aFoundComposite && aFoundComposite->isSub(aCurFeat))
734         break;
735       else
736         aFoundComposite = CompositeFeaturePtr();
737     }
738
739     if (aFoundComposite) {
740       aParents.insert(aFoundComposite);
741       aCurFeat = aFoundComposite;
742     }
743     else {
744       // add the part containing high-level feature
745       SessionPtr aSession = ModelAPI_Session::get();
746       DocumentPtr aPartSetDoc = aSession->moduleDocument();
747       std::list<FeaturePtr> aPartSetFeatures = aPartSetDoc->allFeatures();
748       for (std::list<FeaturePtr>::const_iterator anIt = aPartSetFeatures.begin();
749         anIt != aPartSetFeatures.end(); ++anIt) {
750         aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
751         if (aFoundComposite && aFoundComposite->isSub(aCurFeat)) {
752           aParents.insert(aFoundComposite);
753           break;
754         }
755       }
756
757       aCurFeat = FeaturePtr();
758     }
759   }
760   return aParents;
761 }
762
763 } // namespace ModelAPI_Tools