Salome HOME
Make highlight of points as a circle instead of +
[modules/shaper.git] / src / ModuleBase / ModuleBase_Tools.cpp
index 3211a935a2c596e6a2998519435143525bef774f..986d22d18a5f707545ee2f583f80e4f58037504c 100755 (executable)
@@ -21,6 +21,7 @@
 #include <ModelAPI_AttributeRefList.h>
 #include <ModelAPI_AttributeRefAttrList.h>
 #include <ModelAPI_ResultPart.h>
+#include <ModelAPI_ResultConstruction.h>
 #include <Events_Loop.h>
 
 #include <ModelAPI_Data.h>
 #include <TopoDS_Iterator.hxx>
 
 #include <GeomDataAPI_Point2D.h>
-#include <Events_Error.h>
+#include <Events_InfoMessage.h>
+#include <GeomAPI_ShapeExplorer.h>
 
 #include <Config_PropManager.h>
+#include <Config_Translator.h>
+
+#include <Prs3d_PointAspect.hxx>
+#include <Graphic3d_AspectMarker3d.hxx>
 
 #include <QWidget>
 #include <QLayout>
 #include <QColor>
 #include <QApplication>
 #include <QMessageBox>
+#include <QAction>
+#include <QTextCodec>
 
 #include <sstream>
 #include <string>
 
 const double tolerance = 1e-7;
+const double DEFAULT_DEVIATION_COEFFICIENT = 1.e-4;
 
 //#define DEBUG_ACTIVATE_WINDOW
 //#define DEBUG_SET_FOCUS
+//#define DEBUG_SELECTION_INFO
+
+#ifdef DEBUG_SELECTION_INFO
+#include <ModuleBase_ISelection.h>
+#include <ModuleBase_ViewerPrs.h>
+
+#include <AIS_InteractiveContext.hxx>
+#include <AIS_ListOfInteractive.hxx>
+#include <AIS_ListIteratorOfListOfInteractive.hxx>
+#include <AIS_Shape.hxx>
+#include <TopoDS_Shape.hxx>
+#include <AIS_LocalContext.hxx>
+#include <NCollection_List.hxx>
+#include <StdSelect_BRepOwner.hxx>
+#include <TColStd_ListOfInteger.hxx>
+#include <TColStd_ListIteratorOfListOfInteger.hxx>
+#endif
 
 namespace ModuleBase_Tools {
 
@@ -122,7 +148,7 @@ void setShadowEffect(QWidget* theWidget, const bool isSetEffect)
   else {
     QGraphicsEffect* anEffect = theWidget->graphicsEffect();
     if(anEffect)
-    anEffect->deleteLater();
+      anEffect->deleteLater();
     theWidget->setGraphicsEffect(NULL);
   }
 }
@@ -227,6 +253,21 @@ void setSpinValue(ModuleBase_ParamIntSpinBox* theSpin, int theValue)
   theSpin->blockSignals(isBlocked);
 }
 
+QAction* createAction(const QIcon& theIcon, const QString& theText,
+                      QObject* theParent, const QObject* theReceiver,
+                      const char* theMember, const QString& theToolTip,
+                      const QString& theStatusTip)
+{
+  QAction* anAction = new QAction(theIcon, theText, theParent);
+  anAction->setToolTip(theToolTip.isEmpty() ? theText : theToolTip);
+  anAction->setStatusTip(!theStatusTip.isEmpty() ? theStatusTip :
+                                                   (!theToolTip.isEmpty() ? theToolTip : theText));
+  if (theReceiver)
+    QObject::connect(anAction, SIGNAL(triggered(bool)), theReceiver, theMember);
+
+  return anAction;
+}
+
 QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
 {
   QString aFeatureStr = "feature";
@@ -255,7 +296,7 @@ QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
   if (aFeature.get()) {
     aFeatureStr.append(QString(": %1").arg(aFeature->getKind().c_str()).toStdString().c_str());
     if (aFeature->data()->isValid()) {
-      aFeatureStr.append(QString(", name=%1").arg(aFeature->data()->name().c_str()).toStdString()
+      aFeatureStr.append(QString(", name=%1").arg(theObj->data()->name().c_str()).toStdString()
                                                                                        .c_str());
     }
     if (isUseAttributesInfo) {
@@ -285,28 +326,219 @@ QString objectInfo(const ObjectPtr& theObj, const bool isUseAttributesInfo)
   return aFeatureStr;
 }
 
+#ifdef DEBUG_SELECTION_INFO
+QString getShapeTypeInfo(const int theType)
+{
+  QString anInfo = "Undefined";
+  switch(theType) {
+    case TopAbs_COMPOUND:  anInfo = "compound"; break;
+    case TopAbs_COMPSOLID: anInfo = "compsolid"; break;
+    case TopAbs_SOLID:     anInfo = "solid"; break;
+    case TopAbs_SHELL:     anInfo = "shell"; break;
+    case TopAbs_FACE:      anInfo = "face"; break;
+    case TopAbs_WIRE:      anInfo = "wire"; break;
+    case TopAbs_EDGE:      anInfo = "edge"; break;
+    case TopAbs_VERTEX:    anInfo = "vertex"; break;
+    case TopAbs_SHAPE:     anInfo = "shape"; break;
+    default: break;
+  }
+  return anInfo;
+}
+
+QString getModeInfo(const int theMode)
+{
+  QString anInfo = "Undefined";
+  switch(theMode) {
+    case 0: anInfo = "SHAPE(0)"; break;
+    case 1: anInfo = "VERTEX(1)"; break;
+    case 2: anInfo = "EDGE(2)"; break;
+    case 3: anInfo = "WIRE(3)"; break;
+    case 4: anInfo = "FACE(4)"; break;
+    case 5: anInfo = "SHELL(5)"; break;
+    case 6: anInfo = "SOLID(6)"; break;
+    case 7: anInfo = "COMPSOLID(7)"; break;
+    case 8: anInfo = "COMPOUND(8)"; break;
+    case 100: anInfo = "Sel_Mode_First(100)"; break; //SketcherPrs_Tools
+    case 101: anInfo = "Sel_Constraint(101)"; break;
+    case 102: anInfo = "Sel_Dimension_All(102)"; break;
+    case 103: anInfo = "Sel_Dimension_Line(103)"; break;
+    case 104: anInfo = "Sel_Dimension_Text(104)"; break;
+    default: break;
+  }
+  return anInfo;
+}
+
+QString displayedInteractiveObjects(Handle(AIS_InteractiveContext)& theContext,
+                                    const bool theShapeInfoOnly = true)
+{
+  if (theContext.IsNull())
+    return "";
+  AIS_ListOfInteractive aListOfIO;
+  theContext->DisplayedObjects(aListOfIO, false);
+  QStringList anObjects;
+  AIS_ListIteratorOfListOfInteractive aIt;
+  for (aIt.Initialize(aListOfIO); aIt.More(); aIt.Next()) {
+    Handle(AIS_InteractiveObject) anAISIO = aIt.Value();
+    Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISIO);
+    if (theShapeInfoOnly && aShapePrs.IsNull())
+      continue;
+
+    QString anInfo = "IO";
+    std::ostringstream aPtrStr;
+    aPtrStr << "[" << anAISIO.Access() << "]";
+    anInfo += aPtrStr.str().c_str();
+
+    if (!aShapePrs.IsNull()) {
+      const TopoDS_Shape& aShape = aShapePrs->Shape();
+      if (aShape.IsNull())
+        Events_Error::throwException("An empty AIS presentation");
+      else
+        anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
+    }
+    TColStd_ListOfInteger aTColModes;
+    theContext->ActivatedModes(anAISIO, aTColModes);
+    TColStd_ListIteratorOfListOfInteger itr( aTColModes );
+    QIntList aModesActivatedForIO;
+    bool isDeactivated = false;
+    QStringList aModes;
+    for (; itr.More(); itr.Next() ) {
+      Standard_Integer aMode = itr.Value();
+      aModes.append(getModeInfo(aMode));
+      //int aShapeMode = (aMode > 8)? aMode : AIS_Shape::SelectionType(aMode);
+    }
+    if (aModes.size() > 0)
+      anInfo += QString(", activated modes: %1").arg(aModes.join(", "));
+
+    anObjects += anInfo;
+  }
+  QString aValue = QString("displayedIO[%1]").arg(anObjects.size());
+  if (anObjects.size() > 0)
+    aValue += QString(":\n  %1").arg(anObjects.join("\n  "));
+  return aValue;
+}
+
+QString activeOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
+{
+  if (theContext.IsNull())
+    return "";
+  Handle(AIS_LocalContext) aLContext = theContext->LocalContext();
+  TCollection_AsciiString aSelectionName = aLContext->SelectionName();
+  aLContext->UnhilightPicked(Standard_False);
+
+  NCollection_List<Handle(SelectBasics_EntityOwner)> anActiveOwners;
+  aLContext->MainSelector()->ActiveOwners(anActiveOwners);
+  NCollection_List<Handle(SelectBasics_EntityOwner)>::Iterator anOwnersIt (anActiveOwners);
+  Handle(SelectMgr_EntityOwner) anOwner;
+  QStringList anObjects;
+  for (; anOwnersIt.More(); anOwnersIt.Next()) {
+    anOwner = Handle(SelectMgr_EntityOwner)::DownCast (anOwnersIt.Value());
+    Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
+    if (theShapeInfoOnly && BROwnr.IsNull())
+      continue;
+
+    QString anInfo = "Owner";
+    std::ostringstream aPtrStr;
+    aPtrStr << "[" << anOwner.Access() << "]";
+    anInfo += aPtrStr.str().c_str();
+
+    Handle(AIS_InteractiveObject) aAISObj = 
+          Handle(AIS_InteractiveObject)::DownCast(anOwner->Selectable());
+    if (!aAISObj.IsNull()) {
+      std::ostringstream aPtrStr;
+      aPtrStr << "[" << aAISObj.Access() << "]";
+      anInfo += QString(", selectable(IO): %1").arg(aPtrStr.str().c_str());
+    }
+
+    if (!BROwnr.IsNull() && BROwnr->HasShape()) {
+      const TopoDS_Shape& aShape = BROwnr->Shape();
+      if (aShape.IsNull())
+        Events_Error::throwException("An empty AIS presentation");
+      else
+        anInfo += QString(", shape type: %1").arg(getShapeTypeInfo(aShape.ShapeType()));
+    }
+    anObjects += anInfo;
+  }
+  QString aValue = QString("activeOwners[%1]").arg(anObjects.size());
+  if (anObjects.size() > 0)
+    aValue += QString(":\n  %1").arg(anObjects.join("\n  "));
+  return aValue;
+}
+
+QString selectedOwners(Handle(AIS_InteractiveContext)& theContext, const bool theShapeInfoOnly = true)
+{
+  QStringList anObjects;
+  if (theContext.IsNull())
+    return "";
+
+  QList<long> aSelectedIds; // Remember of selected address in order to avoid duplicates
+  for (theContext->InitSelected(); theContext->MoreSelected(); theContext->NextSelected()) {
+    Handle(SelectMgr_EntityOwner) anOwner = theContext->SelectedOwner();
+    Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
+    if (theShapeInfoOnly && BROwnr.IsNull())
+      continue;
+
+    if (aSelectedIds.contains((long)anOwner.Access()))
+      continue;
+    aSelectedIds.append((long)anOwner.Access());
+
+    QString anInfo = "Owner";
+    std::ostringstream aPtrStr;
+    aPtrStr << "[" << anOwner.Access() << "]";
+    anInfo += aPtrStr.str().c_str();
+
+    if (!BROwnr.IsNull() && BROwnr->HasShape()) {
+      const TopoDS_Shape& aShape = BROwnr->Shape();
+      anInfo += QString(", shape type = %1").arg(getShapeTypeInfo(aShape.ShapeType()));
+    }
+    anObjects += anInfo;
+  }
+  QString aValue = QString("selectedOwners[%1]").arg(anObjects.size());
+  if (anObjects.size() > 0)
+    aValue += QString(":\n  %1").arg(anObjects.join("\n  "));
+  return aValue;
+}
+#endif
+
+void selectionInfo(Handle(AIS_InteractiveContext)& theContext, const std::string& thePrefix)
+{
+#ifdef DEBUG_SELECTION_INFO
+  QString aValue = QString("\n\n\nDEBUG_SELECTION_INFO for '%1'\n%2\n%3\n%4")
+                                              .arg(thePrefix.c_str())
+                                              .arg(displayedInteractiveObjects(theContext))
+                                              .arg(activeOwners(theContext))
+                                              .arg(selectedOwners(theContext));
+  qDebug(aValue.toStdString().c_str());
+#endif
+}
+
 typedef QMap<QString, TopAbs_ShapeEnum> ShapeTypes;
-static ShapeTypes MyShapeTypes;
+static ShapeTypes myShapeTypes;
 
 TopAbs_ShapeEnum shapeType(const QString& theType)
 {
-  if (MyShapeTypes.count() == 0) {
-    MyShapeTypes["face"] = TopAbs_FACE;
-    MyShapeTypes["faces"] = TopAbs_FACE;
-    MyShapeTypes["vertex"] = TopAbs_VERTEX;
-    MyShapeTypes["vertices"] = TopAbs_VERTEX;
-    MyShapeTypes["wire"] = TopAbs_WIRE;
-    MyShapeTypes["edge"] = TopAbs_EDGE;
-    MyShapeTypes["edges"] = TopAbs_EDGE;
-    MyShapeTypes["shell"] = TopAbs_SHELL;
-    MyShapeTypes["solid"] = TopAbs_SOLID;
-    MyShapeTypes["solids"] = TopAbs_SOLID;
-    MyShapeTypes["objects"] = TopAbs_SHAPE;
+  if (myShapeTypes.count() == 0) {
+    myShapeTypes["compound"]   = TopAbs_COMPOUND;
+    myShapeTypes["compounds"]  = TopAbs_COMPOUND;
+    myShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
+    myShapeTypes["compsolids"] = TopAbs_COMPSOLID;
+    myShapeTypes["solid"]      = TopAbs_SOLID;
+    myShapeTypes["solids"]     = TopAbs_SOLID;
+    myShapeTypes["shell"]      = TopAbs_SHELL;
+    myShapeTypes["shells"]     = TopAbs_SHELL;
+    myShapeTypes["face"]       = TopAbs_FACE;
+    myShapeTypes["faces"]      = TopAbs_FACE;
+    myShapeTypes["wire"]       = TopAbs_WIRE;
+    myShapeTypes["wires"]      = TopAbs_WIRE;
+    myShapeTypes["edge"]       = TopAbs_EDGE;
+    myShapeTypes["edges"]      = TopAbs_EDGE;
+    myShapeTypes["vertex"]     = TopAbs_VERTEX;
+    myShapeTypes["vertices"]   = TopAbs_VERTEX;
+    myShapeTypes["objects"]    = TopAbs_SHAPE;
   }
   QString aType = theType.toLower();
-  if (MyShapeTypes.contains(aType))
-    return MyShapeTypes[aType];
-  Events_Error::send("Shape type defined in XML is not implemented!");
+  if(myShapeTypes.contains(aType))
+    return myShapeTypes[aType];
+  Events_InfoMessage("ModuleBase_Tools", "Shape type defined in XML is not implemented!").send();
   return TopAbs_SHAPE;
 }
 
@@ -332,14 +564,46 @@ void checkObjects(const QObjectPtrList& theObjects, bool& hasResult, bool& hasFe
   }
 }
 
+bool setDefaultDeviationCoefficient(std::shared_ptr<GeomAPI_Shape> theGeomShape)
+{
+  if (!theGeomShape.get())
+    return false;
+  // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
+  // correction of deviation for them should not influence to the application performance
+  GeomAPI_ShapeExplorer anExp(theGeomShape, GeomAPI_Shape::FACE);
+  bool anEmpty = anExp.empty();
+  return !anExp.more();
+}
+
+void setDefaultDeviationCoefficient(const std::shared_ptr<ModelAPI_Result>& theResult,
+                                    const Handle(Prs3d_Drawer)& theDrawer)
+{
+  if (!theResult.get())
+    return;
+  bool aUseDeviation = false;
+
+  std::string aResultGroup = theResult->groupName();
+  if (aResultGroup == ModelAPI_ResultConstruction::group())
+    aUseDeviation = true;
+  else if (aResultGroup == ModelAPI_ResultBody::group()) {
+    GeomShapePtr aGeomShape = theResult->shape();
+    if (aGeomShape.get())
+      aUseDeviation = setDefaultDeviationCoefficient(aGeomShape);
+  }
+  if (aUseDeviation)
+    theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
+}
+
 void setDefaultDeviationCoefficient(const TopoDS_Shape& theShape,
                                     const Handle(Prs3d_Drawer)& theDrawer)
 {
   if (theShape.IsNull())
     return;
-  TopAbs_ShapeEnum aType = theShape.ShapeType();
-  if ((aType == TopAbs_EDGE) || (aType == TopAbs_WIRE)) 
-    theDrawer->SetDeviationCoefficient(1.e-4);
+
+  std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape());
+  aGeomShape->setImpl(new TopoDS_Shape(theShape));
+  if (setDefaultDeviationCoefficient(aGeomShape))
+    theDrawer->SetDeviationCoefficient(DEFAULT_DEVIATION_COEFFICIENT);
 }
 
 Quantity_Color color(const std::string& theSection,
@@ -657,144 +921,6 @@ QString wrapTextByWords(const QString& theValue, QWidget* theWidget,
   return aResult;
 }
 
-void findReferences(const QObjectPtrList& theList,
-                    std::set<FeaturePtr>& aDirectRefFeatures,
-                    std::set<FeaturePtr>& aIndirectRefFeatures)
-{
-  foreach (ObjectPtr aDeletedObj, theList) {
-    std::set<FeaturePtr> alreadyProcessed;
-    refsToFeatureInAllDocuments(aDeletedObj, aDeletedObj, theList, aDirectRefFeatures,
-                                            aIndirectRefFeatures, alreadyProcessed);
-    std::set<FeaturePtr> aDifference;
-    std::set_difference(aIndirectRefFeatures.begin(), aIndirectRefFeatures.end(), 
-                        aDirectRefFeatures.begin(), aDirectRefFeatures.end(), 
-                        std::inserter(aDifference, aDifference.begin()));
-    aIndirectRefFeatures = aDifference;
-  }
-}
-
-//**************************************************************
-void refsToFeatureInAllDocuments(const ObjectPtr& theSourceObject, const ObjectPtr& theObject,
-                                 const QObjectPtrList& theIgnoreList,
-                                 std::set<FeaturePtr>& theDirectRefFeatures, 
-                                 std::set<FeaturePtr>& theIndirectRefFeatures,
-                                 std::set<FeaturePtr>& theAlreadyProcessed)
-{
-  refsDirectToFeatureInAllDocuments(theSourceObject, theObject, theIgnoreList, theDirectRefFeatures, 
-                                    theAlreadyProcessed);
-
-  // Run recursion. It is possible recursive dependency, like the following: plane, extrusion uses plane,
-  // axis is built on extrusion. Delete of a plane should check the dependency from the axis also.
-  std::set<FeaturePtr>::const_iterator aFeatureIt = theDirectRefFeatures.begin();
-  for (; aFeatureIt != theDirectRefFeatures.end(); ++aFeatureIt) {
-    std::set<FeaturePtr> aRecursiveRefFeatures;
-    refsToFeatureInAllDocuments(theSourceObject, *aFeatureIt, theIgnoreList,
-      aRecursiveRefFeatures, aRecursiveRefFeatures, theAlreadyProcessed);
-    theIndirectRefFeatures.insert(aRecursiveRefFeatures.begin(), aRecursiveRefFeatures.end());
-  }
-
-}
-
-
-
-//**************************************************************
-void refsDirectToFeatureInAllDocuments(const ObjectPtr& theSourceObject, const ObjectPtr& theObject,
-                                       const QObjectPtrList& theIgnoreList,
-                                       std::set<FeaturePtr>& theDirectRefFeatures, 
-                                       std::set<FeaturePtr>& theAlreadyProcessed)
-{
-  FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
-  if (!aFeature.get())
-    return;
-  if (theAlreadyProcessed.find(aFeature) != theAlreadyProcessed.end())
-    return;
-  theAlreadyProcessed.insert(aFeature);
-
-  //convert ignore object list to containt sub-features if the composite feature is in the list
-  QObjectPtrList aFullIgnoreList;
-  QObjectPtrList::const_iterator anIIt = theIgnoreList.begin(), anILast = theIgnoreList.end();
-  for (; anIIt != anILast; anIIt++) {
-    aFullIgnoreList.append(*anIIt);
-    CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*anIIt);
-    // if the current feature is aborted, the composite is removed and has invalid data
-    if (aComposite.get() && aComposite->data()->isValid()) {
-      int aNbSubs = aComposite->numberOfSubs();
-      for (int aSub = 0; aSub < aNbSubs; aSub++) {
-        aFullIgnoreList.append(aComposite->subFeature(aSub));
-      }
-    }
-  }
-
-  // 1. find references in the current document
-  std::set<FeaturePtr> aRefFeatures;
-  refsToFeatureInFeatureDocument(theObject, aRefFeatures);
-  std::set<FeaturePtr>::const_iterator anIt = aRefFeatures.begin(),
-                                       aLast = aRefFeatures.end();
-  for (; anIt != aLast; anIt++) {
-    // composite feature should not be deleted when the sub feature is to be deleted
-    if (!isSubOfComposite(theSourceObject, *anIt) && !aFullIgnoreList.contains(*anIt))
-      theDirectRefFeatures.insert(*anIt);
-  }
-
-  // 2. find references in all documents if the document of the feature is
-  // "PartSet". Features of this document can be used in all other documents
-  DocumentPtr aFeatureDoc = aFeature->document();
-
-  SessionPtr aMgr = ModelAPI_Session::get();
-  DocumentPtr aModuleDoc = aMgr->moduleDocument();
-  if (aFeatureDoc == aModuleDoc) {
-    // the feature and results of the feature should be found in references
-    std::list<ObjectPtr> aObjects;
-    aObjects.push_back(aFeature);
-    typedef std::list<std::shared_ptr<ModelAPI_Result> > ResultsList;
-    const ResultsList& aResults = aFeature->results();
-    ResultsList::const_iterator aRIter = aResults.begin();
-    for (; aRIter != aResults.cend(); aRIter++) {
-      ResultPtr aRes = *aRIter;
-      if (aRes.get())
-        aObjects.push_back(aRes);
-    }
-    // get all opened documents; found features in the documents;
-    // get a list of objects where a feature refers;
-    // search in these objects the deleted objects.
-    SessionPtr aMgr = ModelAPI_Session::get();
-    std::list<DocumentPtr> anOpenedDocs = aMgr->allOpenedDocuments();
-    std::list<DocumentPtr>::const_iterator anIt = anOpenedDocs.begin(),
-                                            aLast = anOpenedDocs.end();
-    std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
-    for (; anIt != aLast; anIt++) {
-      DocumentPtr aDocument = *anIt;
-      if (aDocument == aFeatureDoc)
-        continue; // this document has been already processed in 1.1
-
-      int aFeaturesCount = aDocument->size(ModelAPI_Feature::group());
-      for (int aId = 0; aId < aFeaturesCount; aId++) {
-        ObjectPtr anObject = aDocument->object(ModelAPI_Feature::group(), aId);
-        FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
-        if (!aFeature.get())
-          continue;
-
-        aRefs.clear();
-        aFeature->data()->referencesToObjects(aRefs);
-        std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRef = aRefs.begin();
-        bool aHasReferenceToObject = false;
-        for(; aRef != aRefs.end() && !aHasReferenceToObject; aRef++) {
-          std::list<ObjectPtr>::iterator aRefObj = aRef->second.begin();
-          for(; aRefObj != aRef->second.end() && !aHasReferenceToObject; aRefObj++) {
-            std::list<ObjectPtr>::const_iterator aObjIt = aObjects.begin();
-            for(; aObjIt != aObjects.end() && !aHasReferenceToObject; aObjIt++) {
-              aHasReferenceToObject = *aObjIt == *aRefObj;
-            }
-          }
-        }
-        if (aHasReferenceToObject && !isSubOfComposite(theSourceObject, aFeature) &&
-            !theIgnoreList.contains(aFeature))
-          theDirectRefFeatures.insert(aFeature);
-      }
-    }
-  }
-}
-
 //**************************************************************
 void refsToFeatureInFeatureDocument(const ObjectPtr& theObject, std::set<FeaturePtr>& theRefFeatures)
 {
@@ -840,49 +966,126 @@ bool isSubOfComposite(const ObjectPtr& theObject, const FeaturePtr& theFeature)
   return isSub;
 }
 
+//**************************************************************
+ResultPtr firstResult(const ObjectPtr& theObject)
+{
+  ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
+  if (!aResult.get()) {
+    FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
+    if (aFeature.get())
+      aResult = aFeature->firstResult();
+  }
+  return aResult;
+}
 
 //**************************************************************
-bool isDeleteFeatureWithReferences(const QObjectPtrList& theList,
-                                   const std::set<FeaturePtr>& aDirectRefFeatures,
-                                   const std::set<FeaturePtr>& aIndirectRefFeatures,
-                                   QWidget* theParent,
-                                   bool& doDeleteReferences)
+bool isFeatureOfResult(const FeaturePtr& theFeature, const std::string& theGroupOfResult)
 {
-  doDeleteReferences = true;
+  bool isResult = false;
 
-  QString aDirectNames, aIndirectNames;
-  if (!aDirectRefFeatures.empty()) {
-    QStringList aDirectRefNames;
-    foreach (const FeaturePtr& aFeature, aDirectRefFeatures)
-      aDirectRefNames.append(aFeature->name().c_str());
-    aDirectNames = aDirectRefNames.join(", ");
+  if (!theFeature->data()->isValid())
+    return isResult;
 
-    QStringList aIndirectRefNames;
-    foreach (const FeaturePtr& aFeature, aIndirectRefFeatures)
-      aIndirectRefNames.append(aFeature->name().c_str());
-    aIndirectNames = aIndirectRefNames.join(", ");
+  ResultPtr aFirstResult = theFeature->firstResult();
+  if (!aFirstResult.get())
+    return isResult;
+
+  return aFirstResult->groupName() == theGroupOfResult;
+}
+
+//**************************************************************
+bool hasModuleDocumentFeature(const std::set<FeaturePtr>& theFeatures)
+{
+  bool aFoundModuleDocumentObject = false;
+  DocumentPtr aModuleDoc = ModelAPI_Session::get()->moduleDocument();
+
+  std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(), aLast = theFeatures.end();
+  for (; anIt != aLast && !aFoundModuleDocumentObject; anIt++) {
+    FeaturePtr aFeature = *anIt;
+    ResultPtr aResult = ModuleBase_Tools::firstResult(aFeature);
+    if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group())
+      continue;
+    aFoundModuleDocumentObject = aFeature->document() == aModuleDoc;
   }
 
-  bool aCanReplaceParameters = !aDirectRefFeatures.empty();
+  return aFoundModuleDocumentObject;
+}
+
+//**************************************************************
+bool askToDelete(const std::set<FeaturePtr> theFeatures,
+                 const std::map<FeaturePtr, std::set<FeaturePtr> >& theReferences,
+                 QWidget* theParent,
+                 std::set<FeaturePtr>& theReferencesToDelete)
+{
+  QString aNotActivatedDocWrn;
+  std::string aNotActivatedNames;
+  if (!ModelAPI_Tools::allDocumentsActivated(aNotActivatedNames)) {
+    if (ModuleBase_Tools::hasModuleDocumentFeature(theFeatures))
+      aNotActivatedDocWrn = QObject::tr("Selected objects can be used in Part documents which are not loaded:%1.\n")
+                            .arg(aNotActivatedNames.c_str());
+  }
+  
+  std::set<FeaturePtr> aFeaturesRefsTo;
+  std::set<FeaturePtr> aFeaturesRefsToParameter;
+  std::set<FeaturePtr> aParameterFeatures;
   QStringList aPartFeatureNames;
-  foreach (ObjectPtr aObj, theList) {
-    FeaturePtr aFeature = ModelAPI_Feature::feature(aObj);
-    // invalid feature data means that the feature is already removed in model,
-    // we needn't process it. E.g. delete of feature from create operation. The operation abort
-    // will delete the operation
-    if (!aFeature->data()->isValid())
-      continue;
-    ResultPtr aFirstResult = aFeature->firstResult();
-    if (!aFirstResult.get())
+  std::set<FeaturePtr>::const_iterator anIt = theFeatures.begin(),
+                                       aLast = theFeatures.end();
+  // separate features to references to parameter features and references to others
+  for (; anIt != aLast; anIt++) {
+    FeaturePtr aFeature = *anIt;
+    if (theReferences.find(aFeature) == theReferences.end())
       continue;
-    std::string aResultGroupName = aFirstResult->groupName();
-    if (aResultGroupName == ModelAPI_ResultPart::group())
+
+    if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
       aPartFeatureNames.append(aFeature->name().c_str());
 
-    if (aCanReplaceParameters && aResultGroupName != ModelAPI_ResultParameter::group())
-      aCanReplaceParameters = false;
+    std::set<FeaturePtr> aRefFeatures;
+    std::set<FeaturePtr> aRefList = theReferences.at(aFeature);
+    std::set<FeaturePtr>::const_iterator aRefIt = aRefList.begin(), aRefLast = aRefList.end();
+    for (; aRefIt != aRefLast; aRefIt++) {
+      FeaturePtr aRefFeature = *aRefIt;
+      if (theFeatures.find(aRefFeature) == theFeatures.end() && // it is not selected
+          aRefFeatures.find(aRefFeature) == aRefFeatures.end()) // it is not added
+        aRefFeatures.insert(aRefFeature);
+    }
+
+    if (isFeatureOfResult(aFeature, ModelAPI_ResultParameter::group())) {
+      aFeaturesRefsToParameter.insert(aRefFeatures.begin(), aRefFeatures.end());
+      aParameterFeatures.insert(aFeature);
+    }
+    else {
+      theReferencesToDelete.insert(aRefFeatures.begin(), aRefFeatures.end());
+    }
+  }
+
+  std::set<FeaturePtr> aFeaturesRefsToParameterOnly;
+  anIt = aFeaturesRefsToParameter.begin();
+  aLast = aFeaturesRefsToParameter.end();
+  // separate features to references to parameter features and references to others
+  QStringList aParamFeatureNames;
+  for (; anIt != aLast; anIt++) {
+    FeaturePtr aFeature = *anIt;
+    if (theReferencesToDelete.find(aFeature) == theReferencesToDelete.end()) {
+      aFeaturesRefsToParameterOnly.insert(aFeature);
+      aParamFeatureNames.append(aFeature->name().c_str());
+    }
   }
-  QString aPartNames = aPartFeatureNames.join(", ");
+  aParamFeatureNames.sort();
+  QStringList anOtherFeatureNames;
+  anIt = theReferencesToDelete.begin();
+  aLast = theReferencesToDelete.end();
+  for (; anIt != aLast; anIt++) {
+    FeaturePtr aFeature = *anIt;
+    if (isFeatureOfResult(aFeature, ModelAPI_ResultPart::group()))
+      aPartFeatureNames.append(aFeature->name().c_str());
+    else
+      anOtherFeatureNames.append(aFeature->name().c_str());
+  }
+  aPartFeatureNames.sort();
+  anOtherFeatureNames.sort();
+
+  bool aCanReplaceParameters = !aFeaturesRefsToParameterOnly.empty();
 
   QMessageBox aMessageBox(theParent);
   aMessageBox.setWindowTitle(QObject::tr("Delete features"));
@@ -891,21 +1094,19 @@ bool isDeleteFeatureWithReferences(const QObjectPtrList& theList,
   aMessageBox.setDefaultButton(QMessageBox::No);
 
   QString aText;
-  if (!aDirectNames.isEmpty() || !aIndirectNames.isEmpty()) {
-    if (aCanReplaceParameters) {
-      aText = QString(QObject::tr("Selected parameters are used in the following features: %1.\nThese features will be deleted.\nOr parameters could be replaced by their values.\n")
-                      .arg(aDirectNames));
-      if (!aIndirectNames.isEmpty())
-        aText += QString(QObject::tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
-      QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
-    } else {
-      aText = QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n")).arg(aDirectNames);
-      if (!aIndirectNames.isEmpty())
-        aText += QString(QObject::tr("(Also these features will be deleted: %1)\n")).arg(aIndirectNames);
-    }
+  QString aSep = ", ";
+  if (!aPartFeatureNames.empty())
+    aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartFeatureNames.join(aSep));
+  if (!aNotActivatedDocWrn.isEmpty())
+    aText += aNotActivatedDocWrn;
+  if (!anOtherFeatureNames.empty())
+    aText += QString(QObject::tr("Selected features are used in the following features: %1.\nThese features will be deleted.\n"))
+                     .arg(anOtherFeatureNames.join(aSep));
+  if (!aParamFeatureNames.empty()) {
+    aText += QString(QObject::tr("Selected parameters are used in the following features: %1.\nThese features will be deleted.\nOr parameters could be replaced by their values.\n"))
+                     .arg(aParamFeatureNames.join(aSep));
+    QPushButton *aReplaceButton = aMessageBox.addButton(QObject::tr("Replace"), QMessageBox::ActionRole);
   }
-  if (!aPartNames.isEmpty())
-    aText += QString(QObject::tr("The following parts will be deleted: %1.\n")).arg(aPartNames);
 
   if (!aText.isEmpty()) {
     aText += "Would you like to continue?";
@@ -917,14 +1118,52 @@ bool isDeleteFeatureWithReferences(const QObjectPtrList& theList,
       return false;
 
     if (aButtonRole == QMessageBox::ActionRole) {
-      foreach (ObjectPtr aObj, theList)
+      foreach (FeaturePtr aObj, aParameterFeatures)
         ModelAPI_ReplaceParameterMessage::send(aObj, 0);
-      doDeleteReferences = false;
     }
+    else
+      theReferencesToDelete.insert(aFeaturesRefsToParameterOnly.begin(), aFeaturesRefsToParameterOnly.end());
   }
   return true;
 }
 
+//**************************************************************
+void convertToFeatures(const QObjectPtrList& theObjects, std::set<FeaturePtr>& theFeatures)
+{
+  QObjectPtrList::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
+  for(; anIt != aLast; anIt++) {
+    ObjectPtr anObject = *anIt;
+    FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
+    // for parameter result, use the corresponded reature to be removed
+    if (!aFeature.get() && anObject->groupName() == ModelAPI_ResultParameter::group()) {
+      aFeature = ModelAPI_Feature::feature(anObject);
+    }
+    theFeatures.insert(aFeature);
+  }
+}
+
+void translate(const std::string& theContext, std::string& theMessage)
+{
+  if (!theMessage.empty()) {
+    std::string aStr = Config_Translator::translate(theContext, theMessage);
+    if (!aStr.empty()) {
+      std::string aCodec = Config_Translator::codec(theContext);
+      theMessage = QTextCodec::codecForName(aCodec.c_str())->toUnicode(aStr.c_str()).toStdString();
+    }
+  }
+}
+
+void setPointBallHighlighting(AIS_Shape* theAIS)
+{
+  Handle(Prs3d_Drawer) aDrawer = theAIS->HilightAttributes();
+  if (aDrawer->HasOwnPointAspect()) {
+    Handle(Prs3d_PointAspect) aPntAspect = aDrawer->PointAspect();
+    aPntAspect->Aspect()->SetType(Aspect_TOM_BALL);
+    aDrawer->SetPointAspect(aPntAspect);
+    theAIS->SetHilightAttributes(aDrawer);
+  }
+}
+
 } // namespace ModuleBase_Tools