Salome HOME
Task #2924 implementation : Ability to remove a result
[modules/shaper.git] / src / ModelAPI / ModelAPI_Tools.cpp
old mode 100755 (executable)
new mode 100644 (file)
index 9dd0d9d..c6b8a6f
@@ -1,4 +1,4 @@
-// Copyright (C) 2014-2017  CEA/DEN, EDF R&D
+// Copyright (C) 2014-2019  CEA/DEN, EDF R&D
 //
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
 //
 // You should have received a copy of the GNU Lesser General Public
 // License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 //
-// See http://www.salome-platform.org/ or
-// email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 //
 
 #include "ModelAPI_Tools.h"
@@ -24,7 +23,8 @@
 #include <ModelAPI_Document.h>
 #include <ModelAPI_Object.h>
 #include <ModelAPI_AttributeDouble.h>
-#include <ModelAPI_ResultCompSolid.h>
+#include <ModelAPI_AttributeSelectionList.h>
+#include <ModelAPI_ResultBody.h>
 #include <ModelAPI_ResultParameter.h>
 #include <ModelAPI_ResultPart.h>
 #include <ModelAPI_AttributeDocRef.h>
@@ -32,6 +32,7 @@
 #include <list>
 #include <map>
 #include <iostream>
+#include <sstream>
 
 #include <Events_Loop.h>
 #include <ModelAPI_Events.h>
@@ -106,18 +107,17 @@ std::shared_ptr<GeomAPI_Shape> shape(const ResultPtr& theResult)
   return theResult->shape();
 }
 
+// LCOV_EXCL_START
 const char* toString(ModelAPI_ExecState theExecState)
 {
-#define TO_STRING(__NAME__) case __NAME__: return #__NAME__;
   switch (theExecState) {
-  TO_STRING(ModelAPI_StateDone)
-  TO_STRING(ModelAPI_StateMustBeUpdated)
-  TO_STRING(ModelAPI_StateExecFailed)
-  TO_STRING(ModelAPI_StateInvalidArgument)
-  TO_STRING(ModelAPI_StateNothing)
+  case ModelAPI_StateDone: return "Done";
+  case ModelAPI_StateMustBeUpdated: return "Must be updated";
+  case ModelAPI_StateExecFailed: return "Execution failed";
+  case ModelAPI_StateInvalidArgument: return "Invalid argument";
+  case ModelAPI_StateNothing: return "Empty state";
   default: return "Unknown ExecState.";
   }
-#undef TO_STRING
 }
 
 std::string getFeatureError(const FeaturePtr& theFeature)
@@ -160,6 +160,7 @@ std::string getFeatureError(const FeaturePtr& theFeature)
 
   return anError;
 }
+// LCOV_EXCL_STOP
 
 ObjectPtr objectByName(const DocumentPtr& theDocument, const std::string& theGroup,
                        const std::string& theName)
@@ -253,7 +254,7 @@ FeaturePtr findPartFeature(const DocumentPtr& theMain, const DocumentPtr& theSub
 
 CompositeFeaturePtr compositeOwner(const FeaturePtr& theFeature)
 {
-  if (theFeature.get() && theFeature->data()->isValid()) {
+  if (theFeature.get() && theFeature->data() && theFeature->data()->isValid()) {
     const std::set<std::shared_ptr<ModelAPI_Attribute> >& aRefs = theFeature->data()->refsToMe();
     std::set<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aRefIter = aRefs.begin();
     for(; aRefIter != aRefs.end(); aRefIter++) {
@@ -266,46 +267,66 @@ CompositeFeaturePtr compositeOwner(const FeaturePtr& theFeature)
   return CompositeFeaturePtr(); // not found
 }
 
-ResultCompSolidPtr compSolidOwner(const ResultPtr& theSub)
+ResultBodyPtr bodyOwner(const ResultPtr& theSub, const bool theRoot)
 {
-  ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theSub);
-  if (aBody.get()) {
-    FeaturePtr aFeatureOwner = aBody->document()->feature(aBody);
-    if (aFeatureOwner.get()) {
-      std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
-        aFeatureOwner->results().cbegin();
-      for(; aResIter != aFeatureOwner->results().cend(); aResIter++) {
-        ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aResIter);
-        if (aComp && aComp->isSub(aBody))
-          return aComp;
+  if (theSub.get()) {
+    ObjectPtr aParent = theSub->document()->parent(theSub);
+    if (aParent.get()) {
+      if (theRoot) { // try to find parent of parent
+        ResultPtr aResultParent = std::dynamic_pointer_cast<ModelAPI_Result>(aParent);
+        ResultBodyPtr aGrandParent = bodyOwner(aResultParent, true);
+        if (aGrandParent.get())
+          aParent = aGrandParent;
       }
+      return std::dynamic_pointer_cast<ModelAPI_ResultBody>(aParent);
     }
   }
-  return ResultCompSolidPtr(); // not found
+  return ResultBodyPtr(); // not found
+}
+
+int bodyIndex(const ResultPtr& theSub)
+{
+  int anIndex = -1;
+  ResultBodyPtr aParent = bodyOwner(theSub);
+  if (aParent.get()) {
+    ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theSub);
+    if (aBody.get() && aParent->isSub(aBody, anIndex))
+      return anIndex;
+  }
+  return anIndex; // not found
 }
 
 bool hasSubResults(const ResultPtr& theResult)
 {
-  ResultCompSolidPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theResult);
+  ResultBodyPtr aCompSolid = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
   return aCompSolid.get() && aCompSolid->numberOfSubs() > 0;
 }
 
+void allSubs(const ResultBodyPtr& theResult, std::list<ResultPtr>& theResults,
+             const bool theLowerOnly) {
+  // iterate sub-bodies of compsolid
+  ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
+  if (aComp.get()) {
+    int aNumSub = aComp->numberOfSubs();
+    for (int a = 0; a < aNumSub; a++) {
+      ResultBodyPtr aSub = aComp->subResult(a);
+      if (!theLowerOnly || aSub->numberOfSubs() == 0)
+        theResults.push_back(aSub);
+      allSubs(aSub, theResults);
+    }
+  }
+}
+
 void allResults(const FeaturePtr& theFeature, std::list<ResultPtr>& theResults)
 {
   if (!theFeature.get()) // safety: for empty feature no results
     return;
   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
-  std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
+  std::list<ResultPtr>::const_iterator aRIter = aResults.begin();
   for (; aRIter != aResults.cend(); aRIter++) {
     theResults.push_back(*aRIter);
-    // iterate sub-bodies of compsolid
-    ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
-    if (aComp.get()) {
-      int aNumSub = aComp->numberOfSubs();
-      for(int a = 0; a < aNumSub; a++) {
-        theResults.push_back(aComp->subResult(a));
-      }
-    }
+    ResultBodyPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRIter);
+    allSubs(aResult, theResults);
   }
 }
 
@@ -361,6 +382,7 @@ bool removeFeaturesAndReferences(const std::set<FeaturePtr>& theFeatures,
   return ModelAPI_Tools::removeFeatures(aFeatures, false);
 }
 
+//***********************************************************************
 bool removeFeatures(const std::set<FeaturePtr>& theFeatures,
                     const bool theFlushRedisplay)
 {
@@ -385,6 +407,7 @@ bool removeFeatures(const std::set<FeaturePtr>& theFeatures,
   return true;
 }
 
+//***********************************************************************
 // Fills the references list by all references of the feature from the references map.
 // This is a recusive method to find references by next found feature in the map of references.
 // \param theFeature a feature to find references
@@ -392,7 +415,6 @@ bool removeFeatures(const std::set<FeaturePtr>& theFeatures,
 // \param theReferences an out container of references
 void addRefsToFeature(const FeaturePtr& theFeature,
                       const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferencesMap,
-                      std::map<FeaturePtr, std::set<FeaturePtr> >& theProcessedReferences,
                       int theRecLevel,
                       std::set<FeaturePtr>& theReferences)
 {
@@ -400,34 +422,18 @@ void addRefsToFeature(const FeaturePtr& theFeature,
     return;
   theRecLevel++;
 
-  // if the feature is already processed, get the ready references from the map
-  if (theProcessedReferences.find(theFeature) != theProcessedReferences.end()) {
-    std::set<FeaturePtr> aReferences = theProcessedReferences.at(theFeature);
-    theReferences.insert(aReferences.begin(), aReferences.end());
-    return;
-  }
-
   if (theReferencesMap.find(theFeature) == theReferencesMap.end())
     return; // this feature is not in the selection list, so exists without references to it
   std::set<FeaturePtr> aMainReferences = theReferencesMap.at(theFeature);
 
   std::set<FeaturePtr>::const_iterator anIt = aMainReferences.begin(),
                                        aLast = aMainReferences.end();
-#ifdef DEBUG_REMOVE_FEATURES_RECURSE
-  std::string aSpacing;
-  for (int i = 0; i < theRecLevel; i++)
-    aSpacing.append(" ");
-#endif
-
   for (; anIt != aLast; anIt++) {
     FeaturePtr aRefFeature = *anIt;
-#ifdef DEBUG_REMOVE_FEATURES_RECURSE
-  std::cout << aSpacing << " Ref: " << getFeatureInfo(aRefFeature) << std::endl;
-#endif
-    if (theReferences.find(aRefFeature) == theReferences.end())
+    if (theReferences.find(aRefFeature) == theReferences.end()) {
+      addRefsToFeature(aRefFeature, theReferencesMap, theRecLevel, theReferences);
       theReferences.insert(aRefFeature);
-    addRefsToFeature(aRefFeature, theReferencesMap, theProcessedReferences,
-                     theRecLevel, theReferences);
+    }
   }
 }
 
@@ -535,7 +541,7 @@ void findAllReferences(const std::set<FeaturePtr>& theFeatures,
       std::cout << " Ref: " << getFeatureInfo(aFeature) << std::endl;
 #endif
       aRecLevel++;
-      addRefsToFeature(aFeature, aMainList, theReferences,
+      addRefsToFeature(aFeature, aMainList,
                        aRecLevel, aResultRefList/*aMainRefList*/);
     }
     theReferences[aMainListFeature] = aResultRefList;
@@ -602,4 +608,180 @@ void getConcealedResults(const FeaturePtr& theFeature,
   }
 }
 
+std::pair<std::string, bool> getDefaultName(const std::shared_ptr<ModelAPI_Result>& theResult,
+                                            const bool theInherited)
+{
+  typedef std::list< std::pair < std::string, std::list<ObjectPtr> > > ListOfReferences;
+
+  SessionPtr aSession = ModelAPI_Session::get();
+
+  ResultBodyPtr anOwnerRes = bodyOwner(theResult);
+  if (anOwnerRes) {
+    // names of sub-solids in CompSolid should be default (for example,
+    // result of boolean operation 'Boolean_1_1' is a CompSolid which is renamed to 'MyBOOL',
+    // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1_1', 'Boolean_1_1_2' etc.)
+    std::ostringstream aDefaultName;
+    aDefaultName << getDefaultName(anOwnerRes).first;
+    aDefaultName << "_" << (bodyIndex(theResult) + 1);
+    return std::pair<std::string, bool>(aDefaultName.str(), false);
+  }
+
+  FeaturePtr anOwner = ModelAPI_Feature::feature(theResult->data()->owner());
+  DataPtr aData = anOwner->data();
+
+  ListOfReferences aReferences;
+  // find first result with user-defined name
+  ListOfReferences::const_iterator aFoundRef = aReferences.end();
+  if (theInherited) {
+    aData->referencesToObjects(aReferences);
+
+    for (ListOfReferences::const_iterator aRefIt = aReferences.begin();
+         aRefIt != aReferences.end(); ++aRefIt) {
+      bool isConcealed = aSession->validators()->isConcealed(anOwner->getKind(), aRefIt->first);
+      bool isMainArg = isConcealed &&
+                       aSession->validators()->isMainArgument(anOwner->getKind(), aRefIt->first);
+      if (isConcealed) {
+        // check the referred object is a Body
+        // (for example, ExtrusionCut has a sketch as a first attribute which is concealing)
+        bool isBody = aRefIt->second.size() > 1 || (aRefIt->second.size() == 1 &&
+                      aRefIt->second.front()->groupName() == ModelAPI_ResultBody::group());
+        if (isBody && (isMainArg || aFoundRef == aReferences.end() ||
+            aData->isPrecedingAttribute(aRefIt->first, aFoundRef->first)))
+          aFoundRef = aRefIt;
+
+        if (isMainArg)
+          break;
+      }
+    }
+  }
+  // get the result number in the feature
+  int anIndexInOwner = 0;
+  const std::list<ResultPtr>& anOwnerResults = anOwner->results();
+  std::list<ResultPtr>::const_iterator aResIt = anOwnerResults.cbegin();
+  for(; aResIt != anOwnerResults.cend(); aResIt++) {
+    if(*aResIt == theResult)
+      break;
+    anIndexInOwner++;
+  }
+
+  // find an object which is concealed by theResult
+  if (aFoundRef != aReferences.end() && !aFoundRef->second.empty()) {
+    // store number of references for each object
+    std::map<ResultPtr, int> aNbRefToObject;
+    // search the object by result index
+    std::list<ObjectPtr>::const_iterator anObjIt = aFoundRef->second.begin();
+    int aResultIndex = anIndexInOwner;
+    while (--aResultIndex >= 0) {
+      ResultPtr aCurRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
+      ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(aCurRes);
+      if (aParentBody)
+        aCurRes = aParentBody;
+      if (aNbRefToObject.find(aCurRes) == aNbRefToObject.end())
+        aNbRefToObject[aCurRes] = 1;
+      else
+        aNbRefToObject[aCurRes] += 1;
+
+      ++anObjIt;
+      if (anObjIt == aFoundRef->second.end()) {
+        anObjIt = aFoundRef->second.begin();
+        break;
+      }
+    }
+    // check the result is a Body
+    if ((*anObjIt)->groupName() == ModelAPI_ResultBody::group()) {
+      // check the result is part of CompSolid
+      ResultPtr anObjRes = std::dynamic_pointer_cast<ModelAPI_Result>(*anObjIt);
+      ResultBodyPtr aParentBody = ModelAPI_Tools::bodyOwner(anObjRes);
+      if (aParentBody)
+        anObjRes = aParentBody;
+
+      // return name of reference result only if it has been renamed by the user,
+      // in other case compose a default name
+      if (anObjRes->data()->hasUserDefinedName()) {
+        std::stringstream aName;
+        aName << anObjRes->data()->name();
+        std::map<ResultPtr, int>::iterator aFound = aNbRefToObject.find(anObjRes);
+        if (aFound != aNbRefToObject.end()) {
+          // to generate unique name, add suffix if there are several results
+          // referring to the same shape
+          aName << "_" << aFound->second + 1;
+        }
+        return std::pair<std::string, bool>(aName.str(), true);
+      }
+    }
+  }
+
+  // compose default name by the name of the feature and the index of result
+  std::stringstream aDefaultName;
+  aDefaultName << anOwner->name();
+  // if there are several results (issue #899: any number of result),
+  // add unique prefix starting from second
+  if (anIndexInOwner > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
+    aDefaultName << "_" << anIndexInOwner + 1;
+  return std::pair<std::string, bool>(aDefaultName.str(), false);
+}
+
+std::set<FeaturePtr> getParents(const FeaturePtr& theFeature)
+{
+  std::set<FeaturePtr> aParents;
+  for (FeaturePtr aCurFeat = theFeature; aCurFeat; ) {
+    CompositeFeaturePtr aFoundComposite;
+    const std::set<AttributePtr>& aRefs = aCurFeat->data()->refsToMe();
+    for (std::set<AttributePtr>::const_iterator anIt = aRefs.begin();
+      anIt != aRefs.end(); ++anIt) {
+      FeaturePtr aF = ModelAPI_Feature::feature((*anIt)->owner());
+      aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aF);
+      if (aFoundComposite && aFoundComposite->isSub(aCurFeat))
+        break;
+      else
+        aFoundComposite = CompositeFeaturePtr();
+    }
+
+    if (aFoundComposite) {
+      aParents.insert(aFoundComposite);
+      aCurFeat = aFoundComposite;
+    }
+    else {
+      // add the part containing high-level feature
+      SessionPtr aSession = ModelAPI_Session::get();
+      DocumentPtr aPartSetDoc = aSession->moduleDocument();
+      std::list<FeaturePtr> aPartSetFeatures = aPartSetDoc->allFeatures();
+      for (std::list<FeaturePtr>::const_iterator anIt = aPartSetFeatures.begin();
+        anIt != aPartSetFeatures.end(); ++anIt) {
+        aFoundComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIt);
+        if (aFoundComposite && aFoundComposite->isSub(aCurFeat)) {
+          aParents.insert(aFoundComposite);
+          break;
+        }
+      }
+
+      aCurFeat = FeaturePtr();
+    }
+  }
+  return aParents;
+}
+
+void removeResults(const std::list<ResultPtr>& theResults)
+{
+  // collect all documents where the results must be removed
+  std::map<DocumentPtr, std::list<ResultPtr> > aDocs;
+
+  std::list<ResultPtr>::const_iterator aResIter = theResults.cbegin();
+  for(; aResIter != theResults.cend(); aResIter++) {
+    DocumentPtr aDoc = (*aResIter)->document();
+    if (!aDocs.count(aDoc))
+      aDocs[aDoc] = std::list<ResultPtr>();
+    aDocs[aDoc].push_back(*aResIter);
+  }
+  // create a "remove" feature in each doc
+  std::map<DocumentPtr, std::list<ResultPtr> >::iterator aDoc = aDocs.begin();
+  for(; aDoc != aDocs.end(); aDoc++) {
+    FeaturePtr aRemove = aDoc->first->addFeature("RemoveResults");
+    if (aRemove) {
+      for(aResIter = aDoc->second.cbegin(); aResIter != aDoc->second.cend(); aResIter++)
+        aRemove->selectionList("results")->append(*aResIter, GeomShapePtr());
+    }
+  }
+}
+
 } // namespace ModelAPI_Tools