Salome HOME
Correction for additional debug information
[modules/shaper.git] / src / XGUI / XGUI_Displayer.cpp
index 68d6ae9dcbb8f72c6962d8f1c50a58356a0b6364..0d718aae1ea5af1aca283ca5aebc5effbe0cf64e 100644 (file)
 #include "XGUI_Selection.h"
 #include "XGUI_CustomPrs.h"
 
+#ifndef HAVE_SALOME
 #include <AppElements_Viewer.h>
+#endif
 
 #include <ModelAPI_Document.h>
 #include <ModelAPI_Data.h>
 #include <ModelAPI_Object.h>
 #include <ModelAPI_Tools.h>
 #include <ModelAPI_AttributeIntArray.h>
+#include <ModelAPI_ResultCompSolid.h>
 
 #include <ModuleBase_ResultPrs.h>
 #include <ModuleBase_Tools.h>
 #include <ModuleBase_IModule.h>
+#include <ModuleBase_ViewerPrs.h>
+#include <ModuleBase_Preferences.h>
 
 #include <GeomAPI_Shape.h>
 #include <GeomAPI_IPresentable.h>
 #include <GeomAPI_ICustomPrs.h>
 
+#include <SUIT_ResourceMgr.h>
+
 #include <AIS_InteractiveContext.hxx>
 #include <AIS_LocalContext.hxx>
 #include <AIS_ListOfInteractive.hxx>
 #include <AIS_DimensionSelectionMode.hxx>
 #include <AIS_Shape.hxx>
 #include <AIS_Dimension.hxx>
+#include <AIS_Trihedron.hxx>
+#include <AIS_Axis.hxx>
+#include <AIS_Plane.hxx>
+#include <AIS_Point.hxx>
+#include <AIS_Selection.hxx>
 #include <TColStd_ListIteratorOfListOfInteger.hxx>
 #include <SelectMgr_ListOfFilter.hxx>
 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
+#include <Prs3d_Drawer.hxx>
+#include <Prs3d_IsoAspect.hxx>
+#include <SelectMgr_SelectionManager.hxx>
 
 #include <StdSelect_ViewerSelector3d.hxx>
 
 #include <TColStd_MapOfTransient.hxx>
 #include <TColStd_MapIteratorOfMapOfTransient.hxx>
 
+#ifdef VINSPECTOR
+#include <VInspectorAPI_CallBack.h>
+#endif
+
+#include <Events_Loop.h>
+#include <ModelAPI_Events.h>
+
 #include <set>
 
-const int MOUSE_SENSITIVITY_IN_PIXEL = 10;  ///< defines the local context mouse selection sensitivity
+/// defines the local context mouse selection sensitivity
+const int MOUSE_SENSITIVITY_IN_PIXEL = 10;
 
 //#define DEBUG_ACTIVATE_OBJECTS
 //#define DEBUG_DEACTIVATE
@@ -56,7 +79,13 @@ const int MOUSE_SENSITIVITY_IN_PIXEL = 10;  ///< defines the local context mouse
 //#define DEBUG_FEATURE_REDISPLAY
 //#define DEBUG_SELECTION_FILTERS
 
+//#define DEBUG_COMPOSILID_DISPLAY
 // Workaround for bug #25637
+
+//#define DEBUG_OCCT_SHAPE_SELECTION
+
+//#define WORKAROUND_UNTIL_27523_IS_FIXED
+
 void displayedObjects(const Handle(AIS_InteractiveContext)& theAIS, AIS_ListOfInteractive& theList)
 {
   // Get from null point
@@ -89,10 +118,13 @@ QString qIntListInfo(const QIntList& theValues, const QString& theSeparator = QS
 }
 
 XGUI_Displayer::XGUI_Displayer(XGUI_Workshop* theWorkshop)
-  : myWorkshop(theWorkshop)
+  : myWorkshop(theWorkshop), myNeedUpdate(false),
+  myIsTrihedronActive(true), myViewerBlockedRecursiveCount(0)
 {
-  enableUpdateViewer(true);
-  myCustomPrs = std::shared_ptr<GeomAPI_ICustomPrs>(new XGUI_CustomPrs());
+  #ifdef VINSPECTOR
+  myContextCallBack = 0;
+  #endif
+  myCustomPrs = std::shared_ptr<GeomAPI_ICustomPrs>(new XGUI_CustomPrs(theWorkshop));
 }
 
 XGUI_Displayer::~XGUI_Displayer()
@@ -104,59 +136,113 @@ bool XGUI_Displayer::isVisible(ObjectPtr theObject) const
   return myResult2AISObjectMap.contains(theObject);
 }
 
-void XGUI_Displayer::display(ObjectPtr theObject, bool theUpdateViewer)
+bool XGUI_Displayer::display(ObjectPtr theObject, bool theUpdateViewer)
 {
+  bool aDisplayed = false;
   if (isVisible(theObject)) {
-    redisplay(theObject, theUpdateViewer);
+#ifdef DEBUG_COMPOSILID_DISPLAY
+    ResultCompSolidPtr aCompsolidResult =
+      std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
+    if (aCompsolidResult.get()) {
+      for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
+        ResultPtr aSubResult = aCompsolidResult->subResult(i);
+        if (aSubResult.get())
+          redisplay(aSubResult, false);
+      }
+      if (theUpdateViewer)
+        updateViewer();
+    }
+    else
+#endif
+    aDisplayed = redisplay(theObject, theUpdateViewer);
   } else {
     AISObjectPtr anAIS;
-
     GeomPresentablePtr aPrs = std::dynamic_pointer_cast<GeomAPI_IPresentable>(theObject);
     bool isShading = false;
     if (aPrs.get() != NULL) {
       anAIS = aPrs->getAISObject(anAIS);
+      if (anAIS.get()) {
+        // correct deviation coefficient for
+        /*Handle(AIS_InteractiveObject) anAISPrs = anAIS->impl<Handle(AIS_InteractiveObject)>();
+        if (!anAISPrs.IsNull()) {
+          Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISPrs);
+          if (!aShapePrs.IsNull()) {
+            TopoDS_Shape aShape = aShapePrs->Shape();
+            if (!aShape.IsNull())
+              //ModuleBase_Tools::setDefaultDeviationCoefficient(aShape, anAISPrs->Attributes());
+          }
+        }*/
+      }
     } else {
       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
       if (aResult.get() != NULL) {
+#ifdef DEBUG_COMPOSILID_DISPLAY
+        ResultCompSolidPtr aCompsolidResult =
+          std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
+        if (aCompsolidResult.get()) {
+          for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
+            ResultPtr aSubResult = aCompsolidResult->subResult(i);
+            if (aSubResult.get())
+              display(aSubResult, false);
+          }
+          if (theUpdateViewer)
+            updateViewer();
+        }
+        else {
+#endif
         std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
         if (aShapePtr.get() != NULL) {
           anAIS = AISObjectPtr(new GeomAPI_AISObject());
-          anAIS->setImpl(new Handle(AIS_InteractiveObject)(new ModuleBase_ResultPrs(aResult)));
+          Handle(AIS_InteractiveObject) anAISPrs =
+            myWorkshop->module()->createPresentation(aResult);
+          if (anAISPrs.IsNull())
+            anAISPrs = new ModuleBase_ResultPrs(aResult);
+          else {
+            Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISPrs);
+            if (!aShapePrs.IsNull())
+              ModuleBase_Tools::setPointBallHighlighting((AIS_Shape*) aShapePrs.Access());
+          }
+          anAIS->setImpl(new Handle(AIS_InteractiveObject)(anAISPrs));
           //anAIS->createShape(aShapePtr);
           isShading = true;
         }
+#ifdef DEBUG_COMPOSILID_DISPLAY
+        } // close else
+#endif
       }
     }
     if (anAIS)
-      display(theObject, anAIS, isShading, theUpdateViewer);
+      aDisplayed = display(theObject, anAIS, isShading, theUpdateViewer);
   }
+  return aDisplayed;
 }
 
-bool canBeShaded(Handle(AIS_InteractiveObject) theAIS)
+bool canBeShaded(Handle(AIS_InteractiveObject) theAIS, ModuleBase_IModule* theModule)
 {
   Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(theAIS);
   if (!aShapePrs.IsNull()) {
     TopoDS_Shape aShape = aShapePrs->Shape();
+    if (aShape.IsNull())
+      return false;
     TopAbs_ShapeEnum aType = aShape.ShapeType();
     if ((aType == TopAbs_VERTEX) || (aType == TopAbs_EDGE) || (aType == TopAbs_WIRE))
       return false;
     else {
       // Check that the presentation is not a sketch
-      Handle(ModuleBase_ResultPrs) aPrs = Handle(ModuleBase_ResultPrs)::DownCast(theAIS);
-      if (!aPrs.IsNull()) 
-        return !aPrs->isSketchMode();
-      return true;
+      return theModule->canBeShaded(theAIS);
     }
   }
   return false;
 }
 
-void XGUI_Displayer::display(ObjectPtr theObject, AISObjectPtr theAIS, 
+bool XGUI_Displayer::display(ObjectPtr theObject, AISObjectPtr theAIS,
                              bool isShading, bool theUpdateViewer)
 {
+  bool aDisplayed = false;
+
   Handle(AIS_InteractiveContext) aContext = AISContext();
   if (aContext.IsNull())
-    return;
+    return aDisplayed;
 
   Handle(AIS_InteractiveObject) anAISIO = theAIS->impl<Handle(AIS_InteractiveObject)>();
   if (!anAISIO.IsNull()) {
@@ -168,38 +254,64 @@ void XGUI_Displayer::display(ObjectPtr theObject, AISObjectPtr theAIS,
     if (isShading)
       anAISIO->Attributes()->SetFaceBoundaryDraw( Standard_True );
     anAISIO->SetDisplayMode(aDispMode);
-    aContext->Display(anAISIO, aDispMode, 0, false, true, AIS_DS_Displayed); 
+    aContext->Display(anAISIO, aDispMode, 0, false, true, AIS_DS_Displayed);
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->Display(anAISIO);
+    #endif
+    aDisplayed = true;
 
     emit objectDisplayed(theObject, theAIS);
     activate(anAISIO, myActiveSelectionModes, theUpdateViewer);
- } 
+  }
   if (theUpdateViewer)
     updateViewer();
+
+  return aDisplayed;
 }
 
-void XGUI_Displayer::erase(ObjectPtr theObject, const bool theUpdateViewer)
+bool XGUI_Displayer::erase(ObjectPtr theObject, const bool theUpdateViewer)
 {
+  bool aErased = false;
   if (!isVisible(theObject))
-    return;
+    return aErased;
 
   Handle(AIS_InteractiveContext) aContext = AISContext();
   if (aContext.IsNull())
-    return;
+    return aErased;
+
   AISObjectPtr anObject = myResult2AISObjectMap[theObject];
   if (anObject) {
     Handle(AIS_InteractiveObject) anAIS = anObject->impl<Handle(AIS_InteractiveObject)>();
     if (!anAIS.IsNull()) {
       emit beforeObjectErase(theObject, anObject);
-      aContext->Remove(anAIS, theUpdateViewer);
+      aContext->Remove(anAIS, false/*update viewer*/);
+      #ifdef VINSPECTOR
+      if (myContextCallBack) myContextCallBack->Remove(anAIS);
+      #endif
+      ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::erase -- Remove");
+      aErased = true;
     }
   }
   myResult2AISObjectMap.remove(theObject);
+
+#ifdef DEBUG_DISPLAY
+  std::ostringstream aPtrStr;
+  aPtrStr << theObject.get();
+  qDebug(QString("erase object: %1").arg(aPtrStr.str().c_str()).toStdString().c_str());
+  qDebug(getResult2AISObjectMapInfo().c_str());
+#endif
+
+  if (theUpdateViewer)
+    updateViewer();
+
+  return aErased;
 }
 
-void XGUI_Displayer::redisplay(ObjectPtr theObject, bool theUpdateViewer)
+bool XGUI_Displayer::redisplay(ObjectPtr theObject, bool theUpdateViewer)
 {
+  bool aRedisplayed = false;
   if (!isVisible(theObject))
-    return;
+    return aRedisplayed;
 
   AISObjectPtr aAISObj = getAISObject(theObject);
   Handle(AIS_InteractiveObject) aAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
@@ -208,8 +320,8 @@ void XGUI_Displayer::redisplay(ObjectPtr theObject, bool theUpdateViewer)
   if (aPrs) {
     AISObjectPtr aAIS_Obj = aPrs->getAISObject(aAISObj);
     if (!aAIS_Obj) {
-      erase(theObject, theUpdateViewer);
-      return;
+      aRedisplayed = erase(theObject, theUpdateViewer);
+      return aRedisplayed;
     }
     if (aAIS_Obj != aAISObj) {
       appendResultObject(theObject, aAIS_Obj);
@@ -217,14 +329,11 @@ void XGUI_Displayer::redisplay(ObjectPtr theObject, bool theUpdateViewer)
     aAISIO = aAIS_Obj->impl<Handle(AIS_InteractiveObject)>();
   }
 
-  if (!aAISIO.IsNull()) {
-    Handle(AIS_InteractiveContext) aContext = AISContext();
-    if (aContext.IsNull())
-      return;
+  Handle(AIS_InteractiveContext) aContext = AISContext();
+  if (!aContext.IsNull() && !aAISIO.IsNull()) {
     // Check that the visualized shape is the same and the redisplay is not necessary
-    // Redisplay of AIS object leads to this object selection compute and the selection 
+    // Redisplay of AIS object leads to this object selection compute and the selection
     // in the browser is lost
-
     // this check is not necessary anymore because the selection store/restore is realized
     // before and after the values modification.
     // Moreother, this check avoids customize and redisplay presentation if the presentable
@@ -237,7 +346,8 @@ void XGUI_Displayer::redisplay(ObjectPtr theObject, bool theUpdateViewer)
         std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
         if (aShapePtr.get()) {
           const TopoDS_Shape& aOldShape = aShapePrs->Shape();
-          isEqualShapes = aOldShape.IsEqual(aShapePtr->impl<TopoDS_Shape>());
+          if (!aOldShape.IsNull())
+            isEqualShapes = aOldShape.IsEqual(aShapePtr->impl<TopoDS_Shape>());
         }
       }
     }
@@ -245,10 +355,36 @@ void XGUI_Displayer::redisplay(ObjectPtr theObject, bool theUpdateViewer)
     bool isCustomized = customizeObject(theObject);
     #ifdef DEBUG_FEATURE_REDISPLAY
       qDebug(QString("Redisplay: %1, isEqualShapes=%2, isCustomized=%3").
-        arg(!isEqualShapes || isCustomized).arg(isEqualShapes).arg(isCustomized).toStdString().c_str());
+        arg(!isEqualShapes || isCustomized).arg(isEqualShapes)
+        .arg(isCustomized).toStdString().c_str());
     #endif
     if (!isEqualShapes || isCustomized) {
+      /// if shapes are equal and presentation are customized, selection should be restored
+      bool aNeedToRestoreSelection = isEqualShapes && isCustomized;
+      if (aNeedToRestoreSelection)
+        myWorkshop->module()->storeSelection();
+
+#ifdef WORKAROUND_UNTIL_27523_IS_FIXED
+      if (!myActiveSelectionModes.contains(0))
+        aContext->Activate(aAISIO, 0);
+#endif
+
       aContext->Redisplay(aAISIO, false);
+
+#ifdef WORKAROUND_UNTIL_27523_IS_FIXED
+      if (!myActiveSelectionModes.contains(0))
+        aContext->Deactivate(aAISIO, 0);
+#endif
+
+      #ifdef VINSPECTOR
+      if (myContextCallBack) myContextCallBack->Redisplay(aAISIO);
+      #endif
+      ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::redisplay -- Redisplay");
+
+      if (aNeedToRestoreSelection)
+        myWorkshop->module()->restoreSelection();
+
+      aRedisplayed = true;
       #ifdef DEBUG_FEATURE_REDISPLAY
         qDebug("  Redisplay happens");
       #endif
@@ -256,6 +392,20 @@ void XGUI_Displayer::redisplay(ObjectPtr theObject, bool theUpdateViewer)
         updateViewer();
     }
   }
+  return aRedisplayed;
+}
+
+void XGUI_Displayer::redisplayObjects()
+{
+  // redisplay objects visualized in the viewer
+  static Events_ID EVENT_DISP = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
+  static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
+  QObjectPtrList aDisplayed = myWorkshop->displayer()->displayedObjects();
+  QObjectPtrList::const_iterator anIt = aDisplayed.begin(), aLast = aDisplayed.end();
+  for (; anIt != aLast; anIt++) {
+    aECreator->sendUpdated(*anIt, EVENT_DISP);
+  }
+  Events_Loop::loop()->flush(EVENT_DISP);
 }
 
 void XGUI_Displayer::deactivate(ObjectPtr theObject, const bool theUpdateViewer)
@@ -267,29 +417,44 @@ void XGUI_Displayer::deactivate(ObjectPtr theObject, const bool theUpdateViewer)
     arg(anInfoStr).
     toStdString().c_str());
 #endif
-  if (isVisible(theObject)) {
-    Handle(AIS_InteractiveContext) aContext = AISContext();
-    if (aContext.IsNull())
-      return;
-
+  Handle(AIS_InteractiveContext) aContext = AISContext();
+  if (!aContext.IsNull() && isVisible(theObject)) {
     AISObjectPtr anObj = myResult2AISObjectMap[theObject];
     Handle(AIS_InteractiveObject) anAIS = anObj->impl<Handle(AIS_InteractiveObject)>();
 
     deactivateAIS(anAIS);
     // the selection from the previous activation modes should be cleared manually (#26172)
     aContext->LocalContext()->ClearOutdatedSelection(anAIS, true);
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->ClearOutdatedSelection(anAIS);
+    #endif
+    ModuleBase_Tools::selectionInfo(aContext,
+      "XGUI_Displayer::deactivate -- ClearOutdatedSelection");
     if (theUpdateViewer)
       updateViewer();
   }
 }
 
-void XGUI_Displayer::getModesOfActivation(ObjectPtr theObject, QIntList& theModes)
+void XGUI_Displayer::deactivateObjects(const QObjectPtrList& theObjList,
+                                       const bool theUpdateViewer)
 {
-  if (!isVisible(theObject))
-    return;
+  //Handle(AIS_InteractiveObject) aTrihedron = getTrihedron();
+  //if (!aTrihedron.IsNull())
+  //  deactivateAIS(aTrihedron);
 
+  QObjectPtrList::const_iterator anIt = theObjList.begin(), aLast = theObjList.end();
+  for (; anIt != aLast; anIt++) {
+    deactivate(*anIt, false);
+  }
+  //VSV It seems that there is no necessity to update viewer on deactivation
+  //if (theUpdateViewer)
+  //  updateViewer();
+}
+
+void XGUI_Displayer::getModesOfActivation(ObjectPtr theObject, QIntList& theModes)
+{
   Handle(AIS_InteractiveContext) aContext = AISContext();
-  if (aContext.IsNull())
+  if (aContext.IsNull() || !isVisible(theObject))
     return;
 
   AISObjectPtr aAISObj = getAISObject(theObject);
@@ -305,16 +470,90 @@ void XGUI_Displayer::getModesOfActivation(ObjectPtr theObject, QIntList& theMode
   }
 }
 
+int XGUI_Displayer::getSelectionMode(int theShapeType)
+{
+  return (theShapeType > TopAbs_SHAPE) ? theShapeType :
+                                         AIS_Shape::SelectionMode((TopAbs_ShapeEnum)theShapeType);
+}
+
+bool XGUI_Displayer::isVisible(XGUI_Displayer* theDisplayer, const ObjectPtr& theObject)
+{
+  bool aVisible = false;
+  GeomPresentablePtr aPrs = std::dynamic_pointer_cast<GeomAPI_IPresentable>(theObject);
+  ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
+  if (aPrs.get() || aResult.get()) {
+    aVisible = theDisplayer->isVisible(theObject);
+    // compsolid is not visualized in the viewer,
+    // but should have presentation when all sub solids are
+    // visible. It is useful for highlight presentation where compsolid shape is selectable
+    if (!aVisible && aResult.get() && aResult->groupName() == ModelAPI_ResultCompSolid::group()) {
+      ResultCompSolidPtr aCompsolidResult =
+        std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
+      if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
+        bool anAllSubsVisible = aCompsolidResult->numberOfSubs() > 0;
+        for(int i = 0; i < aCompsolidResult->numberOfSubs() && anAllSubsVisible; i++) {
+          anAllSubsVisible = theDisplayer->isVisible(aCompsolidResult->subResult(i));
+        }
+        aVisible = anAllSubsVisible;
+      }
+    }
+  }
+  // it is possible that feature is presentable and has results, so we should check visibility
+  // of results if presentation is not shown (e.g. Sketch Circle/Arc features)
+  if (!aVisible) {
+    // check if all results of the feature are visible
+    FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
+    std::list<ResultPtr> aResults;
+    ModelAPI_Tools::allResults(aFeature, aResults);
+    std::list<ResultPtr>::const_iterator aIt;
+    aVisible = !aResults.empty();
+    for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
+      aVisible = aVisible && theDisplayer->isVisible(*aIt);
+    }
+  }
+  return aVisible;
+}
+
+#ifdef DEBUG_ACTIVATE_OBJECTS
+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 getModesInfo(const QIntList& theModes)
+{
+  QStringList aModesInfo;
+  for (int i = 0, aSize = theModes.size(); i < aSize; i++)
+    aModesInfo.append(getModeInfo(theModes[i]));
+  return QString("[%1] = %2").arg(aModesInfo.size()).arg(aModesInfo.join(", "));
+}
+#endif
+
 void XGUI_Displayer::activateObjects(const QIntList& theModes, const QObjectPtrList& theObjList,
                                      const bool theUpdateViewer)
 {
   // Convert shape types to selection types
   QIntList aModes;
   foreach(int aType, theModes) {
-    if (aType > TopAbs_SHAPE) 
-      aModes.append(aType);
-    else
-      aModes.append(AIS_Shape::SelectionMode((TopAbs_ShapeEnum)aType));
+    aModes.append(getSelectionMode(aType));
   }
 
 #ifdef DEBUG_ACTIVATE_OBJECTS
@@ -325,9 +564,10 @@ void XGUI_Displayer::activateObjects(const QIntList& theModes, const QObjectPtrL
   }
   QString anInfoStr = anInfo.join(", ");
 
-  qDebug(QString("activateObjects: aModes[%1] = %2, myActiveSelectionModes[%3] = %4, objects = %5").
-    arg(aModes.size()).arg(qIntListInfo(aModes)).
-    arg(myActiveSelectionModes.size()).arg(qIntListInfo(myActiveSelectionModes)).
+  qDebug(QString("activateObjects: new modes%1, active modes%2, objects[%3] = %4").
+    arg(getModesInfo(aModes)).
+    arg(getModesInfo(myActiveSelectionModes)).
+    arg(theObjList.size()).
     arg(anInfoStr).
     toStdString().c_str());
 #endif
@@ -339,10 +579,8 @@ void XGUI_Displayer::activateObjects(const QIntList& theModes, const QObjectPtrL
   }
   myActiveSelectionModes = aNewModes;
   Handle(AIS_InteractiveContext) aContext = AISContext();
-  if (aContext.IsNull())
-    return;
   // Open local context if there is no one
-  if (!aContext->HasOpenedContext()) 
+  if (aContext.IsNull() || !aContext->HasOpenedContext())
     return;
 
   //aContext->UseDisplayedObjects();
@@ -350,53 +588,91 @@ void XGUI_Displayer::activateObjects(const QIntList& theModes, const QObjectPtrL
 
   Handle(AIS_InteractiveObject) anAISIO;
   AIS_ListOfInteractive aPrsList;
-  if (theObjList.isEmpty())
-    return;
-  else {
-    foreach(ObjectPtr aObj, theObjList) {
-      if (myResult2AISObjectMap.contains(aObj))
-        aPrsList.Append(myResult2AISObjectMap[aObj]->impl<Handle(AIS_InteractiveObject)>());
-    }
+  //if (aObjList.isEmpty())
+  //  return;
+  //else {
+  foreach(ObjectPtr aObj, theObjList) {
+    if (myResult2AISObjectMap.contains(aObj))
+      aPrsList.Append(myResult2AISObjectMap[aObj]->impl<Handle(AIS_InteractiveObject)>());
   }
+  //}
+
+  // Add trihedron because it has to partisipate in selection
+  Handle(AIS_InteractiveObject) aTrihedron;
+  if (isTrihedronActive()) {
+    aTrihedron = getTrihedron();
+    if (!aTrihedron.IsNull() && aContext->IsDisplayed(aTrihedron))
+      aPrsList.Append(aTrihedron);
+  }
+  if (aPrsList.Extent() == 0)
+    return;
 
   AIS_ListIteratorOfListOfInteractive aLIt(aPrsList);
+  bool isActivationChanged = false;
   for(aLIt.Initialize(aPrsList); aLIt.More(); aLIt.Next()){
     anAISIO = aLIt.Value();
-    activate(anAISIO, myActiveSelectionModes, false);
+    if (activate(anAISIO, myActiveSelectionModes, false))
+      isActivationChanged = true;
   }
-  if (theUpdateViewer)
-    updateViewer();
 }
 
 bool XGUI_Displayer::isActive(ObjectPtr theObject) const
 {
   Handle(AIS_InteractiveContext) aContext = AISContext();
-  if (aContext.IsNull())
-    return false;
-  if (!isVisible(theObject))
+  if (aContext.IsNull() || !isVisible(theObject))
     return false;
-    
+
   AISObjectPtr anObj = myResult2AISObjectMap[theObject];
   Handle(AIS_InteractiveObject) anAIS = anObj->impl<Handle(AIS_InteractiveObject)>();
 
   TColStd_ListOfInteger aModes;
   aContext->ActivatedModes(anAIS, aModes);
+  #ifdef VINSPECTOR
+  if (myContextCallBack) myContextCallBack->ActivatedModes(anAIS, aModes);
+  #endif
+
   return aModes.Extent() > 0;
 }
-void XGUI_Displayer::setSelected(const  QList<ModuleBase_ViewerPrs>& theValues, bool theUpdateViewer)
+
+
+void XGUI_Displayer::setSelected(const  QList<ModuleBase_ViewerPrsPtr>& theValues,
+                                 bool theUpdateViewer)
 {
   Handle(AIS_InteractiveContext) aContext = AISContext();
   if (aContext.IsNull())
     return;
   if (aContext->HasOpenedContext()) {
-    aContext->UnhilightSelected();
-    aContext->ClearSelected();
-    foreach (ModuleBase_ViewerPrs aPrs, theValues) {
-      const TopoDS_Shape& aShape = aPrs.shape();
-      if (!aShape.IsNull()) {
+    aContext->UnhilightSelected(false);
+    aContext->ClearSelected(false);
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->ClearSelected();
+    #endif
+    NCollection_DataMap<TopoDS_Shape, NCollection_Map<Handle(AIS_InteractiveObject)>>
+      aShapesToBeSelected;
+
+    foreach (ModuleBase_ViewerPrsPtr aPrs, theValues) {
+      const GeomShapePtr& aGeomShape = aPrs->shape();
+      if (aGeomShape.get() && !aGeomShape->isNull()) {
+        const TopoDS_Shape& aShape = aGeomShape->impl<TopoDS_Shape>();
+#ifdef DEBUG_OCCT_SHAPE_SELECTION
+        // problem 1: performance
+        // problem 2: IO is not specified, so the first found owner is selected, as a result
+        // it might belong to another result
         aContext->AddOrRemoveSelected(aShape, false);
+        #ifdef VINSPECTOR
+        if (myContextCallBack) myContextCallBack->AddOrRemoveSelected(aShape);
+        #endif
+#else
+        NCollection_Map<Handle(AIS_InteractiveObject)> aPresentations;
+        if (aShapesToBeSelected.IsBound(aShape))
+          aPresentations = aShapesToBeSelected.Find(aShape);
+        ObjectPtr anObject = aPrs->object();
+        getPresentations(anObject, aPresentations);
+
+        aShapesToBeSelected.Bind(aShape, aPresentations);
+#endif
       } else {
-        ObjectPtr anObject = aPrs.object();
+        ObjectPtr anObject = aPrs->object();
         ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
         if (aResult.get() && isVisible(aResult)) {
           AISObjectPtr anObj = myResult2AISObjectMap[aResult];
@@ -408,15 +684,20 @@ void XGUI_Displayer::setSelected(const  QList<ModuleBase_ViewerPrs>& theValues,
             //aContext->SetSelected(anAIS, false);
             // The selection in the context was cleared, so the method sets the objects are selected
             aContext->AddOrRemoveSelected(anAIS, false);
+            #ifdef VINSPECTOR
+            if (myContextCallBack) myContextCallBack->AddOrRemoveSelected(anAIS);
+            #endif
           }
         }
       }
     }
-  } else {
-    aContext->UnhilightCurrents();
-    aContext->ClearCurrents();
-    foreach (ModuleBase_ViewerPrs aPrs, theValues) {
-      ObjectPtr anObject = aPrs.object();
+    if (!aShapesToBeSelected.IsEmpty())
+      XGUI_Displayer::AddOrRemoveSelectedShapes(aContext, aShapesToBeSelected);
+  } else { // it seems the next code is obsolete as the context is always opened in SHAPER
+    aContext->UnhilightCurrents(false);
+    aContext->ClearCurrents(false);
+    foreach (ModuleBase_ViewerPrsPtr aPrs, theValues) {
+      ObjectPtr anObject = aPrs->object();
       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
       if (aResult.get() && isVisible(aResult)) {
         AISObjectPtr anObj = myResult2AISObjectMap[aResult];
@@ -426,21 +707,27 @@ void XGUI_Displayer::setSelected(const  QList<ModuleBase_ViewerPrs>& theValues,
       }
     }
   }
+  ModuleBase_Tools::selectionInfo(aContext,
+    "XGUI_Displayer::setSelected -- AddOrRemoveSelected/UnhilightCurrents(no local context)");
   if (theUpdateViewer)
     updateViewer();
 }
 
-void XGUI_Displayer::clearSelected()
+void XGUI_Displayer::clearSelected(const bool theUpdateViewer)
 {
   Handle(AIS_InteractiveContext) aContext = AISContext();
-  if (aContext) {
+  if (!aContext.IsNull()) {
     aContext->UnhilightCurrents(false);
-    aContext->ClearSelected();
+    aContext->ClearSelected(theUpdateViewer);
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->ClearSelected();
+    #endif
   }
 }
 
-void XGUI_Displayer::eraseAll(const bool theUpdateViewer)
+bool XGUI_Displayer::eraseAll(const bool theUpdateViewer)
 {
+  bool aErased = false;
   Handle(AIS_InteractiveContext) aContext = AISContext();
   if (!aContext.IsNull()) {
     foreach (ObjectPtr aObj, myResult2AISObjectMap.keys()) {
@@ -449,37 +736,80 @@ void XGUI_Displayer::eraseAll(const bool theUpdateViewer)
       Handle(AIS_InteractiveObject) anIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
       if (!anIO.IsNull()) {
         emit beforeObjectErase(aObj, aAISObj);
-        aContext->Remove(anIO, false);
+        aContext->Remove(anIO, false/*update viewer*/);
+        #ifdef VINSPECTOR
+        if (myContextCallBack) myContextCallBack->Remove(anIO);
+        #endif
+        aErased = true;
       }
     }
     if (theUpdateViewer)
       updateViewer();
   }
+  ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::eraseAll -- Remove");
   myResult2AISObjectMap.clear();
+#ifdef DEBUG_DISPLAY
+  qDebug("eraseAll");
+  qDebug(getResult2AISObjectMapInfo().c_str());
+#endif
+  return aErased;
 }
 
-void XGUI_Displayer::deactivateTrihedron() const
+void deactivateObject(Handle(AIS_InteractiveContext) theContext,
+                      Handle(AIS_InteractiveObject) theObject,
+#ifdef VINSPECTOR
+                      VInspectorAPI_CallBack* theCallBack,
+#endif
+                      const bool theClear = true)
 {
-  Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
+  if (!theObject.IsNull()) {
+    theContext->Deactivate(theObject);
+    #ifdef VINSPECTOR
+    if (theCallBack) theCallBack->Deactivate(theObject);
+    #endif
+    ModuleBase_Tools::selectionInfo(theContext, "XGUI_Displayer::deactivateObject -- Deactivate");
+    //if (theClear) {
+      //theObject->ClearSelected();
+      //  theContext->LocalContext()->ClearOutdatedSelection(theObject, true);
+    //}
+  }
+}
 
-  AIS_ListOfInteractive aList;
-  aContext->DisplayedObjects(aList, true);
-  AIS_ListIteratorOfListOfInteractive aIt;
-  for (aIt.Initialize(aList); aIt.More(); aIt.Next()) {
-    Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast(aIt.Value());
-    if (!aTrihedron.IsNull()) {
-      aContext->Deactivate(aTrihedron);
-    }
+void XGUI_Displayer::deactivateTrihedron(const bool theUpdateViewer) const
+{
+  Handle(AIS_InteractiveObject) aTrihedron = getTrihedron();
+  Handle(AIS_InteractiveContext) aContext = AISContext();
+  if (!aTrihedron.IsNull() && aContext->IsDisplayed(aTrihedron)) {
+    Handle(AIS_Trihedron) aTrie = Handle(AIS_Trihedron)::DownCast(aTrihedron);
+    deactivateObject(aContext, aTrie, myContextCallBack);
+
+    /// #1136 hidden axis are selected in sketch
+    /// workaround for Cascade: there is a crash in AIS_LocalContext::ClearOutdatedSelection
+    /// for Position AIS object in SelectionModes.
+    deactivateObject(aContext, aTrie->XAxis(), myContextCallBack);
+    deactivateObject(aContext, aTrie->YAxis(), myContextCallBack);
+    deactivateObject(aContext, aTrie->Axis(), myContextCallBack);
+    deactivateObject(aContext, aTrie->Position(), myContextCallBack);
+
+    deactivateObject(aContext, aTrie->XYPlane(), myContextCallBack);
+    deactivateObject(aContext, aTrie->XZPlane(), myContextCallBack);
+    deactivateObject(aContext, aTrie->YZPlane(), myContextCallBack);
+
+    if (theUpdateViewer)
+      updateViewer();
   }
 }
 
+Handle(AIS_InteractiveObject) XGUI_Displayer::getTrihedron() const
+{
+  return myWorkshop->viewer()->trihedron();
+}
+
 void XGUI_Displayer::openLocalContext()
 {
-  Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
-  if (aContext.IsNull())
-    return;
+  Handle(AIS_InteractiveContext) aContext = AISContext();
   // Open local context if there is no one
-  if (!aContext->HasOpenedContext()) {
+  if (!aContext.IsNull() && !aContext->HasOpenedContext()) {
     // Preserve selected objects
     //AIS_ListOfInteractive aAisList;
     //for (aContext->InitCurrent(); aContext->MoreCurrent(); aContext->NextCurrent())
@@ -495,7 +825,7 @@ void XGUI_Displayer::openLocalContext()
 
     //aContext->ClearCurrents();
     aContext->OpenLocalContext();
-    deactivateTrihedron();
+    //deactivateTrihedron();
     //aContext->NotUseDisplayedObjects();
 
     //myUseExternalObjects = false;
@@ -515,7 +845,7 @@ void XGUI_Displayer::openLocalContext()
 void XGUI_Displayer::closeLocalContexts(const bool theUpdateViewer)
 {
   Handle(AIS_InteractiveContext) aContext = AISContext();
-  if ( (!aContext.IsNull()) && (aContext->HasOpenedContext()) ) {
+  if (!aContext.IsNull() && aContext->HasOpenedContext()) {
     // Preserve selected objects
     //AIS_ListOfInteractive aAisList;
     //for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
@@ -529,15 +859,18 @@ void XGUI_Displayer::closeLocalContexts(const bool theUpdateViewer)
     //aContext->ClearSelected();
     aContext->CloseAllContexts(false);
 
+    // From the moment when the AIS_DS_Displayed flag is used in the Display of AIS object,
+    // this code is obsolete. It is temporaty commented and should be removed after
+    // the test campaign.
     // Redisplay all object if they were displayed in localContext
-    Handle(AIS_InteractiveObject) aAISIO;
+    /*Handle(AIS_InteractiveObject) aAISIO;
     foreach (AISObjectPtr aAIS, myResult2AISObjectMap) {
       aAISIO = aAIS->impl<Handle(AIS_InteractiveObject)>();
       if (aContext->DisplayStatus(aAISIO) != AIS_DS_Displayed) {
         aContext->Display(aAISIO, false);
         aContext->SetDisplayMode(aAISIO, Shading, false);
       }
-    }
+    }*/
 
     // Append the filters from the local selection in the global selection context
     SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
@@ -596,19 +929,32 @@ ObjectPtr XGUI_Displayer::getObject(const Handle(AIS_InteractiveObject)& theIO)
 
 bool XGUI_Displayer::enableUpdateViewer(const bool isEnabled)
 {
-  bool aWasEnabled = myEnableUpdateViewer;
-
-  myEnableUpdateViewer = isEnabled;
+  bool aWasEnabled = isUpdateEnabled();
+  if (isEnabled)
+    myViewerBlockedRecursiveCount--;
+  else
+    myViewerBlockedRecursiveCount++;
 
+  if (myNeedUpdate && isUpdateEnabled()) {
+    updateViewer();
+    myNeedUpdate = false;
+  }
   return aWasEnabled;
 }
 
+bool XGUI_Displayer::isUpdateEnabled() const
+{
+  return myViewerBlockedRecursiveCount == 0;
+}
+
 void XGUI_Displayer::updateViewer() const
 {
   Handle(AIS_InteractiveContext) aContext = AISContext();
-  if (!aContext.IsNull() && myEnableUpdateViewer) {
+  if (!aContext.IsNull() && isUpdateEnabled()) {
     myWorkshop->viewer()->Zfitall();
     aContext->UpdateCurrentViewer();
+  } else {
+    myNeedUpdate = true;
   }
 }
 
@@ -616,36 +962,85 @@ void XGUI_Displayer::activateAIS(const Handle(AIS_InteractiveObject)& theIO,
                                  const int theMode, const bool theUpdateViewer) const
 {
   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
-  aContext->Activate(theIO, theMode, theUpdateViewer);
+  if (!theIO.IsNull() && theIO == getTrihedron()) {
+    if (theMode != AIS_Shape::SelectionType(TopAbs_EDGE) &&
+        theMode != AIS_Shape::SelectionType(TopAbs_VERTEX))
+      return;
+  }
+  if (!aContext.IsNull()) {
+    if (myWorkshop->module()) {
+      int aMode = (theMode > 8)? theMode : AIS_Shape::SelectionType(theMode);
+      aContext->Activate(theIO, theMode, false);
+    } else
+      aContext->Activate(theIO, theMode, false);
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->Activate(theIO, theMode);
+    #endif
+
+    // the fix from VPA for more suitable selection of sketcher lines
+    if (theIO->Width() > 1) {
+      double aPrecision = theIO->Width() + 2;
+      if (theMode == getSelectionMode(TopAbs_VERTEX))
+        aPrecision = ModuleBase_Preferences::resourceMgr()->doubleValue("Viewer",
+                                                                    "point-selection-sensitivity",
+                                                                        12);
+      else if ((theMode == getSelectionMode(TopAbs_EDGE)) ||
+               (theMode == getSelectionMode(TopAbs_WIRE)))
+        aPrecision = theIO->Width() +
+           ModuleBase_Preferences::resourceMgr()->doubleValue("Viewer",
+                                                              "edge-selection-sensitivity", 2);
+      aContext->SetSelectionSensitivity(theIO, theMode, aPrecision);
+    }
+    ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::activateAIS -- Activate");
 
 #ifdef DEBUG_ACTIVATE_AIS
-  ObjectPtr anObject = getObject(theIO);
-  anInfo.append(ModuleBase_Tools::objectInfo((*anIt)));
-  qDebug(QString("activateAIS: theMode = %1, object = %2").arg(theMode).arg(anInfo).toStdString().c_str());
+    ObjectPtr anObject = getObject(theIO);
+    anInfo.append(ModuleBase_Tools::objectInfo((*anIt)));
+    qDebug(QString("activateAIS: theMode = %1, object = %2").arg(theMode)
+      .arg(anInfo).toStdString().c_str());
 #endif
+    if (theUpdateViewer)
+      updateViewer();
+  }
 }
 
-void XGUI_Displayer::deactivateAIS(const Handle(AIS_InteractiveObject)& theIO, const int theMode) const
+void XGUI_Displayer::deactivateAIS(const Handle(AIS_InteractiveObject)& theIO,
+                                   const int theMode) const
 {
-  Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
-  if (theMode == -1)
-    aContext->Deactivate(theIO);
-  else
-    aContext->Deactivate(theIO, theMode);
+  Handle(AIS_InteractiveContext) aContext = AISContext();
+  if (!aContext.IsNull()) {
+    if (theMode == -1) {
+      aContext->Deactivate(theIO);
+      #ifdef VINSPECTOR
+      if (myContextCallBack) myContextCallBack->Deactivate(theIO);
+      #endif
+    }
+    else {
+      aContext->Deactivate(theIO, theMode);
+      #ifdef VINSPECTOR
+      if (myContextCallBack) myContextCallBack->Deactivate(theIO, theMode);
+      #endif
+    }
+    ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::deactivateAIS -- Deactivate");
 
 #ifdef DEBUG_DEACTIVATE_AIS
-  ObjectPtr anObject = getObject(theIO);
-  anInfo.append(ModuleBase_Tools::objectInfo((*anIt)));
-  qDebug(QString("deactivateAIS: theMode = %1, object = %2").arg(theMode).arg(anInfo).toStdString().c_str());
+    ObjectPtr anObject = getObject(theIO);
+    anInfo.append(ModuleBase_Tools::objectInfo((*anIt)));
+    qDebug(QString("deactivateAIS: theMode = %1, object = %2").arg(theMode)
+      .arg(anInfo).toStdString().c_str());
 #endif
+  }
 }
 
 Handle(AIS_InteractiveContext) XGUI_Displayer::AISContext() const
 {
   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
-  if ((!aContext.IsNull()) && (!aContext->HasOpenedContext())) {
+  if (!aContext.IsNull() && !aContext->HasOpenedContext()) {
     aContext->OpenLocalContext();
-    deactivateTrihedron();
+    if (!isTrihedronActive())
+      deactivateTrihedron(true);
+    aContext->DefaultDrawer()->VIsoAspect()->SetNumber(0);
+    aContext->DefaultDrawer()->UIsoAspect()->SetNumber(0);
   }
   return aContext;
 }
@@ -653,42 +1048,68 @@ Handle(AIS_InteractiveContext) XGUI_Displayer::AISContext() const
 Handle(SelectMgr_AndFilter) XGUI_Displayer::GetFilter()
 {
   Handle(AIS_InteractiveContext) aContext = AISContext();
-  if (myAndFilter.IsNull() && !aContext.IsNull()) {
+  if (!aContext.IsNull() && myAndFilter.IsNull()) {
     myAndFilter = new SelectMgr_AndFilter();
     aContext->AddFilter(myAndFilter);
   }
   return myAndFilter;
 }
 
-void XGUI_Displayer::displayAIS(AISObjectPtr theAIS, bool theUpdateViewer)
+bool XGUI_Displayer::displayAIS(AISObjectPtr theAIS, const bool toActivateInSelectionModes,
+                                bool theUpdateViewer)
 {
+  bool aDisplayed = false;
   Handle(AIS_InteractiveContext) aContext = AISContext();
-  if (aContext.IsNull())
-    return;
   Handle(AIS_InteractiveObject) anAISIO = theAIS->impl<Handle(AIS_InteractiveObject)>();
-  if (!anAISIO.IsNull()) {
-    aContext->Display(anAISIO, theUpdateViewer);
-    if (aContext->HasOpenedContext()) {
-      if (myActiveSelectionModes.size() == 0)
-        activateAIS(anAISIO, 0, theUpdateViewer);
-      else {
-        foreach(int aMode, myActiveSelectionModes) {
-          activateAIS(anAISIO, aMode, theUpdateViewer);
+  if (!aContext.IsNull() && !anAISIO.IsNull()) {
+    aContext->Display(anAISIO, 0/*wireframe*/, 0, false/*update viewer*/, true, AIS_DS_Displayed);
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->Display(anAISIO);
+    #endif
+    aDisplayed = true;
+    aContext->Deactivate(anAISIO);
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->Deactivate(anAISIO);
+    #endif
+    aContext->Load(anAISIO);
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->Load(anAISIO);
+    #endif
+    if (toActivateInSelectionModes) {
+      if (aContext->HasOpenedContext()) {
+        if (myActiveSelectionModes.size() == 0)
+          activateAIS(anAISIO, 0, theUpdateViewer);
+        else {
+          foreach(int aMode, myActiveSelectionModes) {
+            activateAIS(anAISIO, aMode, theUpdateViewer);
+          }
         }
       }
     }
+    if (theUpdateViewer)
+      updateViewer();
   }
+  return aDisplayed;
 }
 
-void XGUI_Displayer::eraseAIS(AISObjectPtr theAIS, const bool theUpdateViewer)
+bool XGUI_Displayer::eraseAIS(AISObjectPtr theAIS, const bool theUpdateViewer)
 {
+  bool aErased = false;
   Handle(AIS_InteractiveContext) aContext = AISContext();
-  if (aContext.IsNull())
-    return;
-  Handle(AIS_InteractiveObject) anAISIO = theAIS->impl<Handle(AIS_InteractiveObject)>();
-  if (!anAISIO.IsNull()) {
-    aContext->Remove(anAISIO, theUpdateViewer);
+  if (!aContext.IsNull()) {
+    Handle(AIS_InteractiveObject) anAISIO = theAIS->impl<Handle(AIS_InteractiveObject)>();
+    if (!anAISIO.IsNull() && aContext->IsDisplayed(anAISIO)) {
+      aContext->Remove(anAISIO, false/*update viewer*/);
+      #ifdef VINSPECTOR
+      if (myContextCallBack) myContextCallBack->Remove(anAISIO);
+      #endif
+      ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::eraseAIS -- Remove");
+      aErased = true;
+    }
   }
+  if (aErased && theUpdateViewer)
+    updateViewer();
+  return aErased;
 }
 
 
@@ -726,28 +1147,39 @@ XGUI_Displayer::DisplayMode XGUI_Displayer::displayMode(ObjectPtr theObject) con
   return (XGUI_Displayer::DisplayMode) aAISIO->DisplayMode();
 }
 
+void XGUI_Displayer::deactivateSelectionFilters()
+{
+  Handle(AIS_InteractiveContext) aContext = AISContext();
+  if (!myAndFilter.IsNull()) {
+    bool aFound = false;
+    if (!aContext.IsNull()) {
+      const SelectMgr_ListOfFilter& aFilters = aContext->Filters();
+      SelectMgr_ListIteratorOfListOfFilter anIt(aFilters);
+      for (; anIt.More() && !aFound; anIt.Next()) {
+        Handle(SelectMgr_Filter) aFilter = anIt.Value();
+        aFound = aFilter == myAndFilter;
+      }
+      if (aFound)
+        aContext->RemoveFilter(myAndFilter);
+    }
+    myAndFilter.Nullify();
+  }
+}
+
 void XGUI_Displayer::addSelectionFilter(const Handle(SelectMgr_Filter)& theFilter)
 {
   Handle(AIS_InteractiveContext) aContext = AISContext();
-  if (aContext.IsNull())
+  if (aContext.IsNull() || hasSelectionFilter(theFilter))
     return;
-  const SelectMgr_ListOfFilter& aFilters = aContext->Filters();
-  SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
-  for (; aIt.More(); aIt.Next()) {
-    if (theFilter.Access() == aIt.Value().Access())
-      return;
-  }
-  Handle(SelectMgr_CompositionFilter) aCompFilter = GetFilter();
-  const SelectMgr_ListOfFilter& aStoredFilters = aCompFilter->StoredFilters();
-  for (aIt.Initialize(aStoredFilters); aIt.More(); aIt.Next()) {
-    if (theFilter.Access() == aIt.Value().Access())
-      return;
-  }
-  aCompFilter->Add(theFilter);
+
+  Handle(SelectMgr_CompositionFilter) aCompositeFilter = GetFilter();
+  if (!aCompositeFilter.IsNull()) {
+    aCompositeFilter->Add(theFilter);
 #ifdef DEBUG_SELECTION_FILTERS
-  int aCount = GetFilter()->StoredFilters().Extent();
-  qDebug(QString("addSelectionFilter: filters.count() = %1").arg(aCount).toStdString().c_str());
+    int aCount = aCompositeFilter->StoredFilters().Extent();
+    qDebug(QString("addSelectionFilter: filters.count() = %1").arg(aCount).toStdString().c_str());
 #endif
+  }
 }
 
 void XGUI_Displayer::removeSelectionFilter(const Handle(SelectMgr_Filter)& theFilter)
@@ -755,13 +1187,40 @@ void XGUI_Displayer::removeSelectionFilter(const Handle(SelectMgr_Filter)& theFi
   Handle(AIS_InteractiveContext) aContext = AISContext();
   if (aContext.IsNull())
     return;
+
   Handle(SelectMgr_AndFilter) aCompositeFilter = GetFilter();
-  if (aCompositeFilter->IsIn(theFilter))
+  if (!aCompositeFilter.IsNull() && aCompositeFilter->IsIn(theFilter)) {
     aCompositeFilter->Remove(theFilter);
 #ifdef DEBUG_SELECTION_FILTERS
-  int aCount = GetFilter()->StoredFilters().Extent();
-  qDebug(QString("removeSelectionFilter: filters.count() = %1").arg(aCount).toStdString().c_str());
+    int aCount = aCompositeFilter->StoredFilters().Extent();
+    qDebug(QString("removeSelectionFilter: filters.count() = %1")
+      .arg(aCount).toStdString().c_str());
 #endif
+  }
+}
+
+bool XGUI_Displayer::hasSelectionFilter(const Handle(SelectMgr_Filter)& theFilter)
+{
+  bool aFilterFound = false;
+
+  Handle(AIS_InteractiveContext) aContext = AISContext();
+  if (aContext.IsNull())
+    return aFilterFound;
+  const SelectMgr_ListOfFilter& aFilters = aContext->Filters();
+  SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
+  for (; aIt.More() && !aFilterFound; aIt.Next()) {
+    if (theFilter.Access() == aIt.Value().Access())
+      aFilterFound = true;
+  }
+  Handle(SelectMgr_CompositionFilter) aCompositeFilter = GetFilter();
+  if (!aCompositeFilter.IsNull()) {
+    const SelectMgr_ListOfFilter& aStoredFilters = aCompositeFilter->StoredFilters();
+    for (aIt.Initialize(aStoredFilters); aIt.More() && !aFilterFound; aIt.Next()) {
+      if (theFilter.Access() == aIt.Value().Access())
+        aFilterFound = true;
+    }
+  }
+  return aFilterFound;
 }
 
 void XGUI_Displayer::removeFilters()
@@ -769,7 +1228,10 @@ void XGUI_Displayer::removeFilters()
   Handle(AIS_InteractiveContext) aContext = AISContext();
   if (aContext.IsNull())
     return;
-  GetFilter()->Clear();
+
+  Handle(SelectMgr_CompositionFilter) aCompositeFilter = GetFilter();
+  if (!aCompositeFilter.IsNull())
+    aCompositeFilter->Clear();
 }
 
 void XGUI_Displayer::showOnly(const QObjectPtrList& theList)
@@ -787,7 +1249,7 @@ void XGUI_Displayer::showOnly(const QObjectPtrList& theList)
 }
 
 bool XGUI_Displayer::canBeShaded(ObjectPtr theObject) const
-{ 
+{
   if (!isVisible(theObject))
     return false;
 
@@ -796,17 +1258,18 @@ bool XGUI_Displayer::canBeShaded(ObjectPtr theObject) const
     return false;
 
   Handle(AIS_InteractiveObject) anAIS = aAISObj->impl<Handle(AIS_InteractiveObject)>();
-  return ::canBeShaded(anAIS);
+  return ::canBeShaded(anAIS, myWorkshop->module());
 }
 
-void XGUI_Displayer::activate(const Handle(AIS_InteractiveObject)& theIO,
+bool XGUI_Displayer::activate(const Handle(AIS_InteractiveObject)& theIO,
                               const QIntList& theModes,
                               const bool theUpdateViewer) const
 {
   Handle(AIS_InteractiveContext) aContext = AISContext();
   if (aContext.IsNull() || theIO.IsNull())
-    return;
+    return false;
 
+  bool isActivationChanged = false;
   // deactivate object in all modes, which are not in the list of activation
   // It seems that after the IO deactivation the selected state of the IO's owners
   // is modified in OCC(version: 6.8.0) and the selection of the object later is lost.
@@ -815,14 +1278,19 @@ void XGUI_Displayer::activate(const Handle(AIS_InteractiveObject)& theIO,
   // If the selection problem happens again, it is possible to write a test scenario and create
   // a bug. The bug steps are the following:
   // Create two IO, activate them in 5 modes, select the first IO, deactivate 3 modes for both,
-  // with clicked SHIFT select the second object. The result is the selection of the first IO is lost.
+  // with clicked SHIFT select the second object.
+  // The result is the selection of the first IO is lost.
   TColStd_ListOfInteger aTColModes;
   aContext->ActivatedModes(theIO, aTColModes);
+  #ifdef VINSPECTOR
+  if (myContextCallBack) myContextCallBack->ActivatedModes(theIO, aTColModes);
+  #endif
   TColStd_ListIteratorOfListOfInteger itr( aTColModes );
   QIntList aModesActivatedForIO;
   bool isDeactivated = false;
   for (; itr.More(); itr.Next() ) {
     Standard_Integer aMode = itr.Value();
+    int aShapeMode = (aMode > 8)? aMode : AIS_Shape::SelectionType(aMode);
     if (!theModes.contains(aMode)) {
       deactivateAIS(theIO, aMode);
       isDeactivated = true;
@@ -833,34 +1301,49 @@ void XGUI_Displayer::activate(const Handle(AIS_InteractiveObject)& theIO,
   }
   if (isDeactivated) {
     // the selection from the previous activation modes should be cleared manually (#26172)
+    theIO->ClearSelected();
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->ClearSelected(theIO);
+    #endif
     aContext->LocalContext()->ClearOutdatedSelection(theIO, true);
-    if (theUpdateViewer)
-      updateViewer();
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->ClearOutdatedSelection(theIO);
+    #endif
+    ModuleBase_Tools::selectionInfo(aContext,
+            "XGUI_Displayer::activate -- ClearSelected/ClearOutdatedSelection");
+    // For performance issues
+    //if (theUpdateViewer)
+    //  updateViewer();
+    isActivationChanged = true;
   }
 
   // loading the interactive object allowing the decomposition
   if (aTColModes.IsEmpty()) {
     aContext->Load(theIO, -1, true);
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->Load(theIO);
+    #endif
   }
 
   // trihedron AIS check should be after the AIS loading.
   // If it is not loaded, it is steel selectable in the viewer.
-  Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast(theIO);
+  Handle(AIS_Trihedron) aTrihedron;
+  if (!isTrihedronActive())
+    aTrihedron = Handle(AIS_Trihedron)::DownCast(theIO);
   if (aTrihedron.IsNull()) {
-      //aContext->Load(anAISIO, -1, true);
       // In order to clear active modes list
     if (theModes.size() == 0) {
-      //aContext->Load(anAISIO, 0, true);
       activateAIS(theIO, 0, theUpdateViewer);
     } else {
       foreach(int aMode, theModes) {
-        //aContext->Load(anAISIO, aMode, true);
         if (!aModesActivatedForIO.contains(aMode)) {
           activateAIS(theIO, aMode, theUpdateViewer);
+          isActivationChanged = true;
         }
       }
     }
   }
+  return isActivationChanged;
 }
 
 bool XGUI_Displayer::customizeObject(ObjectPtr theObject)
@@ -885,12 +1368,13 @@ bool XGUI_Displayer::customizeObject(ObjectPtr theObject)
   }
   bool isCustomized = aCustomPrs.get() &&
                       aCustomPrs->customisePresentation(aResult, anAISObj, myCustomPrs);
-  myWorkshop->module()->customizeObject(theObject);
   return isCustomized;
 }
 
 
-QColor XGUI_Displayer::setObjectColor(ObjectPtr theObject, const QColor& theColor, bool theUpdateViewer)
+QColor XGUI_Displayer::setObjectColor(ObjectPtr theObject,
+                                      const QColor& theColor,
+                                      bool theUpdateViewer)
 {
   if (!isVisible(theObject))
     return Qt::black;
@@ -925,9 +1409,156 @@ std::string XGUI_Displayer::getResult2AISObjectMapInfo() const
     aPtrStr << "aObj = " << aObj.get() << ":";
     aPtrStr << "anAIS = " << aAISObj.get() << ":";
     aPtrStr << "[" << ModuleBase_Tools::objectInfo(aObj).toStdString().c_str() << "]";
-    
+
     aContent.append(aPtrStr.str().c_str());
   }
-  return QString("myResult2AISObjectMap: size = %1\n%2").arg(myResult2AISObjectMap.size()).
+  return QString("myResult2AISObjectMap: size = %1\n%2\n").arg(myResult2AISObjectMap.size()).
                                             arg(aContent.join("\n")).toStdString().c_str();
 }
+
+void XGUI_Displayer::getPresentations(const ObjectPtr& theObject,
+                                  NCollection_Map<Handle(AIS_InteractiveObject)>& thePresentations)
+{
+  ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
+  if (aResult.get()) {
+    AISObjectPtr aAISObj = getAISObject(aResult);
+    if (aAISObj.get() != NULL) {
+      Handle(AIS_InteractiveObject) anAIS = aAISObj->impl<Handle(AIS_InteractiveObject)>();
+      if (!anAIS.IsNull() && !thePresentations.Contains(anAIS))
+        thePresentations.Add(anAIS);
+    }
+  }
+  else {
+    FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
+    // find presentation of the feature
+    AISObjectPtr aAISObj = getAISObject(aFeature);
+    if (aAISObj.get() != NULL) {
+      Handle(AIS_InteractiveObject) anAIS = aAISObj->impl<Handle(AIS_InteractiveObject)>();
+      if (!anAIS.IsNull() && !thePresentations.Contains(anAIS))
+        thePresentations.Add(anAIS);
+    }
+    // find presentations of the feature results
+    std::list<ResultPtr> aResults;
+    ModelAPI_Tools::allResults(aFeature, aResults);
+    std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
+    for (; anIt != aLast; ++anIt) {
+      AISObjectPtr aAISObj = getAISObject(*anIt);
+      if (aAISObj.get() != NULL) {
+        Handle(AIS_InteractiveObject) anAIS = aAISObj->impl<Handle(AIS_InteractiveObject)>();
+        if (!anAIS.IsNull() && !thePresentations.Contains(anAIS))
+          thePresentations.Add(anAIS);
+      }
+    }
+  }
+}
+
+void XGUI_Displayer::activateTrihedron(bool theIsActive)
+{
+  myIsTrihedronActive = theIsActive;
+  if (!myIsTrihedronActive) {
+    deactivateTrihedron(true);
+  }
+}
+
+void XGUI_Displayer::displayTrihedron(bool theToDisplay) const
+{
+  Handle(AIS_InteractiveContext) aContext = AISContext();
+  if (aContext.IsNull())
+    return;
+
+  Handle(AIS_Trihedron) aTrihedron = myWorkshop->viewer()->trihedron();
+
+  if (theToDisplay) {
+    if (!aContext->IsDisplayed(aTrihedron))
+      aContext->Display(aTrihedron,
+                        0 /*wireframe*/,
+                        -1 /* selection mode */,
+                        Standard_True /* update viewer*/,
+                        Standard_False /* allow decomposition */,
+                        AIS_DS_Displayed /* xdisplay status */);
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->Display(aTrihedron);
+    #endif
+
+    if (!isTrihedronActive())
+      deactivateTrihedron(false);
+    else
+      activate(aTrihedron, myActiveSelectionModes, false);
+  } else {
+    deactivateTrihedron(false);
+    //aContext->LocalContext()->ClearOutdatedSelection(aTrihedron, true);
+    // the selection from the previous activation modes should be cleared manually (#26172)
+
+    aContext->Erase(aTrihedron);
+    #ifdef VINSPECTOR
+    if (myContextCallBack) myContextCallBack->Remove(aTrihedron);
+    #endif
+  }
+
+  updateViewer();
+}
+
+QIntList XGUI_Displayer::activeSelectionModes() const
+{
+  QIntList aModes;
+  foreach (int aMode, myActiveSelectionModes) {
+    // aMode < 9 is a Shape Enum values
+    aModes << ((aMode < 9)? AIS_Shape::SelectionType(aMode) : aMode);
+  }
+  return aModes;
+}
+
+#ifdef VINSPECTOR
+void XGUI_Displayer::setCallBack(VInspectorAPI_CallBack* theCallBack)
+{
+  myContextCallBack = theCallBack;
+}
+
+VInspectorAPI_CallBack* XGUI_Displayer::getCallBack() const
+{
+  return myContextCallBack;
+}
+#endif
+
+void XGUI_Displayer::AddOrRemoveSelectedShapes(Handle(AIS_InteractiveContext) theContext,
+                           const NCollection_DataMap<TopoDS_Shape,
+                           NCollection_Map<Handle(AIS_InteractiveObject)>>& theShapesToBeSelected)
+{
+  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;
+
+  /// It is very important to check that the owner is processed only once and has a map of
+  /// processed owners because SetSelected works as a switch.
+  /// If count of calls setSelectec is even, the object stays in the previous state
+  /// (selected, deselected)
+  /// OCCT: to write about the problem that active owners method returns one owner several times
+  QList<long> aSelectedIds; // Remember of selected address in order to avoid duplicates
+  for (; anOwnersIt.More(); anOwnersIt.Next()) {
+    anOwner = Handle(SelectMgr_EntityOwner)::DownCast (anOwnersIt.Value());
+    if (aSelectedIds.contains((long)anOwner.Access()))
+      continue;
+    aSelectedIds.append((long)anOwner.Access());
+
+    Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
+    if (!BROwnr.IsNull() && BROwnr->HasShape()) {
+      const TopoDS_Shape& aShape = BROwnr->Shape();
+      if (!aShape.IsNull() && theShapesToBeSelected.IsBound(aShape)) {
+        Handle(AIS_InteractiveObject) anOwnerPresentation =
+                                    Handle(AIS_InteractiveObject)::DownCast(anOwner->Selectable());
+        NCollection_Map<Handle(AIS_InteractiveObject)> aPresentations =
+                                    theShapesToBeSelected.Find(aShape);
+        if (aPresentations.Contains(anOwnerPresentation)) {
+          AIS_Selection::Selection(aSelectionName.ToCString())->Select(anOwner);
+          anOwner->SetSelected (Standard_True);
+        }
+      }
+    }
+  }
+  aLContext->HilightPicked(Standard_False);
+}