0027893: Visualization - AIS_InteractiveContext::SetSelected does not work
[occt.git] / src / AIS / AIS_LocalContext_1.cxx
index a7e22e8..6a2a088 100644 (file)
 //              - use of optimisation in SelectMgr_ViewerSelector
 //              -> Best management in detected entities...
 
-#define BUC60569       //GG_051199 Enable to select the local context 
-//                     in any case and especially in multi selection mode.
-//                     Note that right now when an hilighted owner is selected
-//                     this owner is unhilighted,this permits to see the selection!
-//                     Principle : an owner can have 3 state :
-//                     1 : The owner is selected and no more highlightable
-//                     0 : The owner is NOT selected
-//                     -1: The owner is selected but stay highlightable (NEW)
-
-// IMP230600   //GG Add protection on selection methodes
-//                     when nothing is selected
-
-#define BUC60726        //GG_040900 When nothing is detected, 
-//                     Clear the last temporary stuff in any case
-
-#define BUC60765       //GG_121000 Avoid to raise when the same selection 
-//                     is attached to several local context.
-
-#define BUC60771       //GG_261000     Avoid to crash after closing a view
-//                     containing a selected entity and creating a new one.
-
-#define BUC60774       //GG_261000     Returns right select status on
-//                     bounding-box selection type.
-
-#define BUC60818       //GG_300101     Enable detection even if
-//                     SetAutomaticHilight(FALSE) has been used.
-
-#define IMP300101       //GG Enable to use polygon highlighting
-
-#define BUC60876       //GG_050401 Clear selection always even
-//                     if the current highlight mode is not 0.
-
-#define BUC60953        //SAV_060701 For Select optimization. Selection by rectangle case.
-// for single selection no optimization done.
-
-#define IMP120701      //SZV made a shape valid for selection
-//                     when required.
-
-#define IMP160701       //SZV Add InitDetected(),MoreDetected(),NextDetected(),
-//                       DetectedCurrentShape(),DetectedCurrentObject()
-//                       methods
-
-#define OCC138          //VTN Avoding infinit loop in AddOrRemoveSelected method.
-
-#define OCC189          //SAV: 18/03/02 AIS_Selection::Objects() returns ListOfTransient
-// instead of array.
-
-#define USE_MAP         //san : 18/04/03 USE_MAP - additional datamap is used to speed up access 
-//to certain owners in AIS_Selection::myresult list  
-
-#define OCC9026                //AEL Performance optimization of the FindSelectedOwnerFromShape() method.
-
-#include <AIS_LocalContext.jxx>
-#include <StdSelect_BRepOwner.hxx>
-#include <TColStd_MapOfTransient.hxx>
-#include <TColStd_MapIteratorOfMapOfTransient.hxx>
-#include <Prs3d_Presentation.hxx>
-#include <Prs3d_Drawer.hxx>
-#include <Prs3d_ShadingAspect.hxx>
+#include <AIS_InteractiveContext.hxx>
+#include <AIS_InteractiveObject.hxx>
+#include <AIS_LocalContext.hxx>
 #include <AIS_LocalStatus.hxx>
-#include <StdPrs_WFShape.hxx>
+#include <AIS_Selection.hxx>
+#include <AIS_Shape.hxx>
+#include <Aspect_Grid.hxx>
+#include <Geom_Transformation.hxx>
 #include <Graphic3d_ArrayOfTriangles.hxx>
 #include <Graphic3d_Group.hxx>
+#include <NCollection_Map.hxx>
+#include <OSD_Environment.hxx>
+#include <Prs3d_Drawer.hxx>
+#include <Prs3d_Presentation.hxx>
+#include <Prs3d_ShadingAspect.hxx>
 #include <Select3D_SensitiveTriangulation.hxx>
 #include <SelectBasics_SensitiveEntity.hxx>
-#include <TCollection_AsciiString.hxx>
-#include <NCollection_Map.hxx>
-
-#ifdef OCC9026
-#include <SelectMgr_DataMapIteratorOfDataMapOfIntegerSensitive.hxx>
-#endif
+#include <SelectMgr_EntityOwner.hxx>
+#include <SelectMgr_Filter.hxx>
+#include <SelectMgr_OrFilter.hxx>
+#include <SelectMgr_SelectableObject.hxx>
 #include <SelectMgr_Selection.hxx>
+#include <SelectMgr_SelectionManager.hxx>
 #include <SelectMgr_SequenceOfOwner.hxx>
-#include <OSD_Environment.hxx>
-
-#include <Geom_Transformation.hxx>
-#include <AIS_Selection.hxx>
-#include <Aspect_Grid.hxx>
-#ifdef IMP120701
-#include <AIS_Shape.hxx>
-#endif
+#include <Standard_Transient.hxx>
+#include <StdSelect_BRepOwner.hxx>
+#include <StdSelect_ViewerSelector3d.hxx>
+#include <TCollection_AsciiString.hxx>
+#include <TColStd_ListIteratorOfListOfInteger.hxx>
+#include <TColStd_ListOfInteger.hxx>
+#include <TColStd_MapIteratorOfMapOfTransient.hxx>
+#include <TColStd_MapOfTransient.hxx>
+#include <V3d_View.hxx>
 
+namespace
+{
+  TopoDS_Shape AIS_myDummyShape;
+}
 
 static Standard_Integer GetHiMod(const Handle(AIS_InteractiveObject)& IO)
 {
   return IO->HasHilightMode() ? IO->HilightMode():0;
 }
 
+//=======================================================================
+//function : getHiStyle
+//purpose  :
+//=======================================================================
+const Handle(Graphic3d_HighlightStyle)& AIS_LocalContext::getHiStyle (const Handle(SelectMgr_SelectableObject)& theObj) const
+{
+  const Handle(Prs3d_Drawer)& aHiDrawer = theObj->HilightAttributes();
+  return !aHiDrawer.IsNull() && aHiDrawer->HasOwnHighlightStyle()
+    ? aHiDrawer->HighlightStyle() : myCTX->HighlightStyle();
+}
+
+//=======================================================================
+//function : getSelStyle
+//purpose  :
+//=======================================================================
+const Handle(Graphic3d_HighlightStyle)& AIS_LocalContext::getSelStyle (const Handle(AIS_InteractiveObject)& theObj) const
+{
+  const Handle(Prs3d_Drawer)& aHiDrawer = theObj->HilightAttributes();
+  return !aHiDrawer.IsNull() && aHiDrawer->HasOwnSelectionStyle()
+    ? aHiDrawer->SelectionStyle() : myCTX->SelectionStyle();
+}
+
 //==================================================
 // Function: MoveTo
 // Purpose :
@@ -126,6 +104,7 @@ AIS_StatusOfDetection AIS_LocalContext::MoveTo (const Standard_Integer  theXpix,
 
   myCurDetected = 0;
   myDetectedSeq.Clear();
+  myFilters->SetDisabledObjects (theView->View()->HiddenObjects());
   myMainVS->Pick (theXpix, theYpix, theView);
 
   const Standard_Integer aDetectedNb = myMainVS->NbPicked();
@@ -138,9 +117,9 @@ AIS_StatusOfDetection AIS_LocalContext::MoveTo (const Standard_Integer  theXpix,
       continue;
     }
 
-    myDetectedSeq.Append (aDetIter); // normallly they are already arranged in correct order...
+    myDetectedSeq.Append (aDetIter); // normally they are already arranged in correct order...
     Handle(AIS_InteractiveObject) anObj = Handle(AIS_InteractiveObject)::DownCast (anOwner->Selectable());
-    if (!Handle(AIS_Shape)::DownCast (anObj).IsNull())
+    if (!anObj.IsNull())
     {
       myAISDetectedSeq.Append (anObj);
     }
@@ -149,9 +128,10 @@ AIS_StatusOfDetection AIS_LocalContext::MoveTo (const Standard_Integer  theXpix,
   // result of courses..
   if (aDetectedNb == 0 || myDetectedSeq.IsEmpty())
   {
-    if (mylastindex != 0 && mylastindex <= myMapOfOwner.Extent())
+    if (mylastindex != 0 && mylastindex <= myMapOfOwner->Extent())
     {
-      Unhilight (myMapOfOwner (mylastindex), theView);
+      myMainPM->ClearImmediateDraw();
+      Unhilight (myMapOfOwner->FindKey (mylastindex), theView);
       if (theToRedrawImmediate)
       {
         theView->RedrawImmediate();
@@ -181,332 +161,333 @@ AIS_StatusOfDetection AIS_LocalContext::MoveTo (const Standard_Integer  theXpix,
   }
 }
 
-//==================================================
-// Function: 
-// Purpose :
-//==================================================
-AIS_StatusOfPick AIS_LocalContext::Select(const Standard_Boolean updateviewer)
+//=======================================================================
+//function : AddSelect
+//purpose  : 
+//=======================================================================
+AIS_StatusOfPick AIS_LocalContext::AddSelect (const Handle(SelectMgr_EntityOwner)& theObject)
 {
-  if(myAutoHilight)
-    UnhilightPicked(Standard_False);
-  
-  Standard_Integer DI = DetectedIndex();
-  AIS_Selection::SetCurrentSelection(mySelName.ToCString());
-  Standard_Integer NbSel = AIS_Selection::Extent();
+  mySelection->AddSelect (theObject);
+
+  Standard_Integer aSelNum = mySelection->Extent();
+  return (aSelNum == 1) ? AIS_SOP_OneSelected
+                        : (aSelNum > 1) ? AIS_SOP_SeveralSelected
+                                        : AIS_SOP_Error;
+}
+
+//=======================================================================
+//function : Select
+//purpose  : 
+//=======================================================================
+AIS_StatusOfPick AIS_LocalContext::Select (const Standard_Boolean toUpdateViewer)
+{
+  if (myAutoHilight)
+  {
+    UnhilightPicked (Standard_False);
+  }
 
-  if(DI<=0){
-    ClearSelected(updateviewer);
-    return NbSel== 0 ? AIS_SOP_NothingSelected : AIS_SOP_Removed;
+  Standard_Integer aDetIndex = DetectedIndex();
+  if (aDetIndex <= 0)
+  {
+    ClearSelected (toUpdateViewer);
+    return mySelection->IsEmpty() ? AIS_SOP_NothingSelected : AIS_SOP_Removed;
   }
 
-  const Handle(SelectMgr_EntityOwner)& EO = myMapOfOwner(DI);
+  const Handle(SelectMgr_EntityOwner)& anOwner = myMapOfOwner->FindKey (aDetIndex);
+
+  ClearSelected (Standard_False);
+
+  if (!anOwner->IsSelected()) // anOwner is not selected
+  {
+    anOwner->SetSelected (Standard_True);
+    mySelection->Select (anOwner);
+  }
 
-#ifdef BUC60569
-  ClearSelected(Standard_False);
-  Standard_Integer state = EO->State();
-  if( state < 1 ){
-    EO->State(1);
-    if( state == 0 ) AIS_Selection::Select(EO);
-  }
-#else
-  if(!IsSelected(EO))
-    AIS_Selection::ClearAndSelect(EO);
-#endif
-    
   if (myAutoHilight)
   {
     const Handle(V3d_Viewer)& aViewer = myCTX->CurrentViewer();
-    for (aViewer->InitActiveViews(); aViewer->MoreActiveViews(); aViewer->NextActiveViews())
+    for (V3d_ListOfViewIterator anActiveViewIter (aViewer->ActiveViewIterator()); anActiveViewIter.More(); anActiveViewIter.Next())
     {
-      Unhilight (EO, aViewer->ActiveView());
+      Unhilight (anOwner, anActiveViewIter.Value());
     }
 
     // advanced selection highlighting mechanism
-    if (!EO->IsAutoHilight() && EO->HasSelectable())
+    if (!anOwner->IsAutoHilight() && anOwner->HasSelectable())
     {
-      Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(EO->Selectable());
+      Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(anOwner->Selectable());
       UpdateSelected (anIO, Standard_False);
     }
 
-    if (updateviewer)
+    if (toUpdateViewer)
     {
       myCTX->CurrentViewer()->Update();
     }
   }
-  return ( AIS_Selection::Extent() == 1)? AIS_SOP_OneSelected : AIS_SOP_SeveralSelected ;
+
+  return (mySelection->Extent() == 1) ? AIS_SOP_OneSelected : AIS_SOP_SeveralSelected;
 }
-//==================================================
-// Function: 
-// Purpose :
-//==================================================
-AIS_StatusOfPick AIS_LocalContext::Select(const Standard_Integer XPMin,
-                                         const Standard_Integer YPMin,
-                                         const Standard_Integer XPMax,
-                                         const Standard_Integer YPMax, 
-                                         const Handle(V3d_View)& aView,
-                                         const Standard_Boolean updateviewer)
+
+//=======================================================================
+//function : Select
+//purpose  : 
+//=======================================================================
+AIS_StatusOfPick AIS_LocalContext::Select (const Standard_Integer  theXPMin,
+                                           const Standard_Integer  theYPMin,
+                                           const Standard_Integer  theXPMax,
+                                           const Standard_Integer  theYPMax,
+                                           const Handle(V3d_View)& theView,
+                                           const Standard_Boolean  toUpdateViewer)
 {
-  if(aView->Viewer()== myCTX->CurrentViewer()){
-    myMainVS->Pick( XPMin,YPMin,XPMax,YPMax,aView);
-    if (myAutoHilight) UnhilightPicked(Standard_False);
-    
-    AIS_Selection::SetCurrentSelection(mySelName.ToCString());
-    Standard_Integer LastExt = AIS_Selection::Extent();
-    
-    myMainVS->Init();
-    if(!myMainVS->More()) {
-      ClearSelected(updateviewer);
-      mylastindex=0;
-      return LastExt == 0 ? AIS_SOP_NothingSelected:AIS_SOP_Removed;
+  if (theView->Viewer() == myCTX->CurrentViewer())
+  {
+    myMainVS->Pick (theXPMin, theYPMin, theXPMax, theYPMax, theView);
+    if (myAutoHilight)
+    {
+      UnhilightPicked (Standard_False);
     }
 
-    ClearSelected(Standard_False);
-   
-    for(myMainVS->Init();myMainVS->More();myMainVS->Next()){
-      const Handle(SelectMgr_EntityOwner)& OWNR = myMainVS->Picked();
-      if(myFilters->IsOk(OWNR)){
-       // it can be helpfil to classify this owner immediately...
-#ifdef BUC60569
-         Standard_Integer state = OWNR->State();
-         if( state < 1 ){
-#ifdef BUC60953
-            if( state == 0 ) AIS_Selection::Select(OWNR);
-            OWNR->State(1);
-#else
-            OWNR->State(1);
-            if( state == 0 ) AIS_Selection::Select(OWNR);
-#endif //BUC60953
-         }
-#else //BUC60569
-         if(!IsSelected(OWNR)){
-           OWNR->State(1);
-           AIS_Selection::Select(OWNR);
-         }
-#endif //BUC60569
+    Standard_Integer aSelNum = mySelection->Extent();
+    if (myMainVS->NbPicked() == 0)
+    {
+      ClearSelected (toUpdateViewer);
+      mylastindex = 0;
+      return aSelNum == 0 ? AIS_SOP_NothingSelected : AIS_SOP_Removed;
+    }
+
+    ClearSelected (Standard_False);
+
+    for (Standard_Integer aPickIter = 1; aPickIter <= myMainVS->NbPicked(); ++aPickIter)
+    {
+      const Handle(SelectMgr_EntityOwner)& anOwner = myMainVS->Picked (aPickIter);
+      if (myFilters->IsOk (anOwner))
+      {
+        // it can be helpful to classify this owner immediately...
+        if (!anOwner->IsSelected())
+        {
+          anOwner->SetSelected (Standard_True);
+          mySelection->Select (anOwner);
+        }
       }
     }
-    if (myAutoHilight) 
-      HilightPicked(updateviewer);
-  }
-#ifdef BUC60774
-  Standard_Integer NS = AIS_Selection::Extent();
-  if( NS == 1 ) return AIS_SOP_OneSelected;
-  else if( NS > 1 ) return AIS_SOP_SeveralSelected;
-#endif
-  return AIS_SOP_Error;
-}
 
+    if (myAutoHilight)
+    {
+      HilightPicked (toUpdateViewer);
+    }
+  }
+
+  Standard_Integer aSelNum = mySelection->Extent();
 
+  return (aSelNum == 1) ? AIS_SOP_OneSelected
+                        : (aSelNum > 1) ? AIS_SOP_SeveralSelected
+                                        : AIS_SOP_Error;
+}
 
 //==================================================
-// Function: 
-// Purpose :
+// Function: Select
+// Purpose : Selection by polyline
 //==================================================
-AIS_StatusOfPick AIS_LocalContext::ShiftSelect(const Standard_Boolean updateviewer)
+AIS_StatusOfPick AIS_LocalContext::Select (const TColgp_Array1OfPnt2d& thePolyline,
+                                           const Handle(V3d_View)& theView,
+                                           const Standard_Boolean toUpdateViewer)
+{
+  if (theView->Viewer() == myCTX->CurrentViewer())
+  {
+    myMainVS->Pick (thePolyline, theView);
+
+    Standard_Integer aLastSelNum = mySelection->Extent();
+    if (myMainVS->NbPicked() == 0)
+    {
+      // Nothing is selected clear selection.
+      ClearSelected (toUpdateViewer);
+      mylastindex = 0;
+
+      // Return state to know if something was unselected
+      return aLastSelNum == 0 ? AIS_SOP_NothingSelected : AIS_SOP_Removed;
+    }
+
+    if (myAutoHilight)
+    {
+      UnhilightPicked (Standard_False);
+    }
+
+    // Clear previous selection without update to process this selection
+    ClearSelected (Standard_False);
+
+    for (Standard_Integer aPickIter = 1; aPickIter <= myMainVS->NbPicked(); ++aPickIter)
+    {
+      const Handle(SelectMgr_EntityOwner)& anOwner = myMainVS->Picked (aPickIter);
+      if (myFilters->IsOk (anOwner))
+      {
+        // it can be helpful to classify this owner immediately...
+        if (!anOwner->IsSelected())
+        {
+          mySelection->AddSelect (anOwner);
+          anOwner->SetSelected (Standard_True);
+        }
+      }
+    }
+
+    if (myAutoHilight)
+    {
+      HilightPicked (toUpdateViewer);
+    }
+  }
+
+  Standard_Integer aSelNum = mySelection->Extent();
+  return (aSelNum == 1) ? AIS_SOP_OneSelected
+                        : (aSelNum > 1) ? AIS_SOP_SeveralSelected
+                                        : AIS_SOP_Error;
+}
+
+//=======================================================================
+//function : ShiftSelect
+//purpose  : 
+//=======================================================================
+AIS_StatusOfPick AIS_LocalContext::ShiftSelect (const Standard_Boolean toUpdateViewer)
 {
-  Standard_Integer I = DetectedIndex();
-  if(I>0){
-    
-    AIS_Selection::SetCurrentSelection(mySelName.ToCString());
-#ifdef BUC60774
-    Standard_Integer NbSel = AIS_Selection::Extent();
-#endif
-    const Handle(SelectMgr_EntityOwner)& EO  = myMapOfOwner(I);
-#ifdef BUC60569
-    Standard_Integer mod = EO->State()==0 ? -1 : 0;
-#else
-    Standard_Integer mod = EO->State()==0 ? 1 : 0;
-#endif
-
-#ifdef BUC60953
-    AIS_Selection::Select(EO);
-    EO->State(mod);
-#else
-    EO->State(mod);
-
-    AIS_Selection::Select(EO);
-#endif
-    
+  Standard_Integer aDetIndex = DetectedIndex();
+
+  if(aDetIndex > 0)
+  {
+    Standard_Integer aSelNum = mySelection->Extent();
+    const Handle(SelectMgr_EntityOwner)& anOwner = myMapOfOwner->FindKey (aDetIndex);
+    Standard_Boolean toSelect = anOwner->IsSelected() ? Standard_False : Standard_True;
+    mySelection->Select (anOwner);
+    anOwner->SetSelected (toSelect);
+
     if(myAutoHilight)
     {
+      myMainPM->ClearImmediateDraw();
       const Handle(V3d_Viewer)& aViewer = myCTX->CurrentViewer();
-      for (aViewer->InitActiveViews(); aViewer->MoreActiveViews(); aViewer->NextActiveViews())
+      for (V3d_ListOfViewIterator anActiveViewIter (aViewer->ActiveViewIterator()); anActiveViewIter.More(); anActiveViewIter.Next())
       {
-        Unhilight (EO, aViewer->ActiveView());
+        Unhilight (anOwner, anActiveViewIter.Value());
       }
 
       // advanced selection highlighting mechanism
-      if (!EO->IsAutoHilight() && EO->HasSelectable())
+      if (!anOwner->IsAutoHilight() && anOwner->HasSelectable())
       {
-        Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast (EO->Selectable());
+        Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast (anOwner->Selectable());
         UpdateSelected (anIO, Standard_False);
       }
 
-      if (updateviewer)
+      if (toUpdateViewer)
       {
         myCTX->CurrentViewer()->Update();
       }
     } 
-#ifdef BUC60774
-    Standard_Integer NS = AIS_Selection::Extent();
+
+    Standard_Integer NS = mySelection->Extent();
     if( NS == 1 ) return AIS_SOP_OneSelected;
     else if( NS > 1 ) return AIS_SOP_SeveralSelected;
-    return NbSel== 0 ? AIS_SOP_NothingSelected : AIS_SOP_Removed;
-#endif
+    return aSelNum == 0 ? AIS_SOP_NothingSelected : AIS_SOP_Removed;
   }
   return AIS_SOP_Error;
 }
-//==================================================
-// Function: the already selected objects are unselected
-// Purpose : others are selected.
-//==================================================
-AIS_StatusOfPick AIS_LocalContext::ShiftSelect(const Standard_Integer XPMin,
-                                  const Standard_Integer YPMin,
-                                  const Standard_Integer XPMax,
-                                  const Standard_Integer YPMax, 
-                                  const Handle(V3d_View)& aView,
-                                  const Standard_Boolean updateviewer)
+
+//=======================================================================
+//function : ShiftSelect
+//purpose  : 
+//=======================================================================
+AIS_StatusOfPick AIS_LocalContext::ShiftSelect (const Standard_Integer  theXPMin,
+                                                const Standard_Integer  theYPMin,
+                                                const Standard_Integer  theXPMax,
+                                                const Standard_Integer  theYPMax,
+                                                const Handle(V3d_View)& theView,
+                                                const Standard_Boolean  toUpdateViewer)
 {
   myMainPM->ClearImmediateDraw();
 
-  if(aView->Viewer()== myCTX->CurrentViewer()) {
-    myMainVS->Pick( XPMin,YPMin,XPMax,YPMax,aView);
-#ifdef BUC60774
-    AIS_Selection::SetCurrentSelection(mySelName.ToCString());
-    Standard_Integer LastExt = AIS_Selection::Extent();
-#endif
-    myMainVS->Init();
-    if(!myMainVS->More()) 
-#ifdef BUC60774
-      return LastExt == 0 ? AIS_SOP_NothingSelected:AIS_SOP_Removed;
-#else
-      return AIS_SOP_NothingSelected; // no effet if click on empty space
-#endif
-
-    AIS_Selection::SetCurrentSelection(mySelName.ToCString());
-    if (myAutoHilight) UnhilightPicked(Standard_False);
-    
-    for(myMainVS->Init();myMainVS->More();myMainVS->Next()){
-      const Handle(SelectMgr_EntityOwner)& EO = myMainVS->Picked();
-      if(myFilters->IsOk(EO)){
-#ifdef BUC60569
-        Standard_Integer mod = EO->State()==0 ? -1 : 0;
-#else
-       Standard_Integer mod = EO->State()==0 ? 1 : 0;
-#endif
-
-#ifdef BUC60953
-       AIS_Selection::Select(EO);
-       EO->State(mod);
-#else
-       EO->State(mod);
-       AIS_Selection::Select(EO);
-#endif
-      }
+  if (theView->Viewer() == myCTX->CurrentViewer())
+  {
+    myMainVS->Pick (theXPMin, theYPMin, theXPMax, theYPMax, theView);
+
+    Standard_Integer aLastSelNum = mySelection->Extent();
+    if (myMainVS->NbPicked() == 0)
+    {
+      // Nothing is selected clear selection, but don't clear the selection
+      // as it is shift selection and previous selection matters.
+      // Return state to know if something was unselected
+      return aLastSelNum == 0 ? AIS_SOP_NothingSelected : AIS_SOP_Removed;
     }
-    if (myAutoHilight) HilightPicked(updateviewer);
-    
-  }
-#ifdef BUC60774
-  Standard_Integer NS = AIS_Selection::Extent();
-  if( NS == 1 ) return AIS_SOP_OneSelected;
-  else if( NS > 1 ) return AIS_SOP_SeveralSelected;
-#endif
-  return AIS_SOP_Error;
-}
 
-//==================================================
-// Function: Select
-// Purpose : Selection by polyline
-//==================================================
-AIS_StatusOfPick AIS_LocalContext::Select(const TColgp_Array1OfPnt2d& aPolyline,
-                                         const Handle(V3d_View)& aView,
-                                         const Standard_Boolean updateviewer)
-{
-  if(aView->Viewer()== myCTX->CurrentViewer()){
-    myMainVS->Pick(aPolyline,aView);
-    if (myAutoHilight) UnhilightPicked(Standard_False);
-    
-    AIS_Selection::SetCurrentSelection(mySelName.ToCString());
-    Standard_Integer LastExt = AIS_Selection::Extent();
-    
-    myMainVS->Init();
-    if(!myMainVS->More()) {
-      ClearSelected(updateviewer);
-      mylastindex=0;
-      return LastExt == 0 ? AIS_SOP_NothingSelected:AIS_SOP_Removed;
+    if (myAutoHilight)
+    {
+      UnhilightPicked (Standard_False);
     }
 
-    ClearSelected(Standard_False);
-
-    for(myMainVS->Init();myMainVS->More();myMainVS->Next()){
-      const Handle(SelectMgr_EntityOwner)& OWNR = myMainVS->Picked();
-      if(myFilters->IsOk(OWNR)){
-       // it can be helpfil to classify this owner immediately...
-#ifdef BUC60953
-        Standard_Integer state = OWNR->State();
-        if( state < 1 ){
-          if( state == 0 ) AIS_Selection::AddSelect(OWNR);
-          OWNR->State(1);
-        }
-#else 
-       if(!IsSelected(OWNR)){
-         OWNR->State(1);
-         AIS_Selection::AddSelect(OWNR);
-       }
-#endif //BUC60953
+    for (Standard_Integer aPickIter = 1; aPickIter <= myMainVS->NbPicked(); ++aPickIter)
+    {
+      const Handle(SelectMgr_EntityOwner)& anOwner = myMainVS->Picked (aPickIter);
+      if(myFilters->IsOk (anOwner))
+      {
+        Standard_Boolean toSelect = anOwner->IsSelected() ? Standard_False : Standard_True;
+        mySelection->Select (anOwner);
+        anOwner->SetSelected (toSelect);
       }
     }
 
-    if (myAutoHilight) 
-      HilightPicked(updateviewer);
+    if (myAutoHilight)
+    {
+      HilightPicked (toUpdateViewer);
+    }
   }
-#ifdef BUC60774
-  Standard_Integer NS = AIS_Selection::Extent();
-  if( NS == 1 ) return AIS_SOP_OneSelected;
-  else if( NS > 1 ) return AIS_SOP_SeveralSelected;
-#endif
-  return AIS_SOP_Error;
+
+  Standard_Integer aSelNum = mySelection->Extent();
+
+  return (aSelNum == 1) ? AIS_SOP_OneSelected
+                        : (aSelNum > 1) ? AIS_SOP_SeveralSelected
+                                        : AIS_SOP_Error;
 }
 
 //==================================================
 // Function: Select
 // Purpose : Selection by polyline
 //==================================================
-AIS_StatusOfPick AIS_LocalContext::ShiftSelect( const TColgp_Array1OfPnt2d& aPolyline,
-                                                const Handle(V3d_View)& aView,
-                                                const Standard_Boolean updateviewer )
+AIS_StatusOfPick AIS_LocalContext::ShiftSelect (const TColgp_Array1OfPnt2d& thePolyline,
+                                                const Handle(V3d_View)&     theView,
+                                                const Standard_Boolean      toUpdateViewer)
 {
-    if( aView->Viewer() == myCTX->CurrentViewer() ) {
-        myMainVS->Pick( aPolyline, aView );
-        
-        AIS_Selection::SetCurrentSelection( mySelName.ToCString() );
-        Standard_Integer LastExt = AIS_Selection::Extent();
-        myMainVS->Init();
-        if( !myMainVS->More() ) 
-            return LastExt == 0 ? AIS_SOP_NothingSelected : AIS_SOP_Removed;
-        
-        AIS_Selection::SetCurrentSelection( mySelName.ToCString() );
-        
-        if ( myAutoHilight )
-            UnhilightPicked( Standard_False );
-        for( myMainVS->Init(); myMainVS->More(); myMainVS->Next() ) {
-            const Handle(SelectMgr_EntityOwner)& EO = myMainVS->Picked();
-            if( myFilters->IsOk( EO ) ) {
-                Standard_Integer mod = EO->State() == 0 ? -1 : 0;
-                AIS_Selection::Select(EO);
-                EO->State( mod );
-            }
-        }
-        if ( myAutoHilight )
-            HilightPicked( updateviewer );
+  if (theView->Viewer() == myCTX->CurrentViewer())
+  {
+    myMainVS->Pick (thePolyline, theView);
+
+    Standard_Integer aLastSelNum = mySelection->Extent();
+    if (myMainVS->NbPicked() == 0)
+    {
+      // Nothing is selected clear selection, but don't clear the selection
+      // as it is shift selection and previous selection matters.
+      // Return state to know if something was unselected
+      return aLastSelNum == 0 ? AIS_SOP_NothingSelected : AIS_SOP_Removed;
+    }
+
+    if (myAutoHilight)
+    {
+      UnhilightPicked (Standard_False);
     }
-    Standard_Integer NS = AIS_Selection::Extent();
-    if( NS == 1 ) 
-        return AIS_SOP_OneSelected;
-    else if( NS > 1 ) 
-        return AIS_SOP_SeveralSelected;
-    return AIS_SOP_Error;
+
+    for (Standard_Integer aPickIter = 1; aPickIter <= myMainVS->NbPicked(); ++aPickIter)
+    {
+      const Handle(SelectMgr_EntityOwner)& anOwner = myMainVS->Picked (aPickIter);
+      if (myFilters->IsOk (anOwner))
+      {
+        Standard_Boolean toSelect = anOwner->IsSelected() ? Standard_False : Standard_True;
+        mySelection->Select (anOwner);
+        anOwner->SetSelected (toSelect);
+      }
+    }
+    if (myAutoHilight)
+    {
+      HilightPicked (toUpdateViewer);
+    }
+  }
+
+  Standard_Integer aSelNum = mySelection->Extent();
+
+  return (aSelNum == 1) ? AIS_SOP_OneSelected
+                        : (aSelNum > 1) ? AIS_SOP_SeveralSelected
+                                        : AIS_SOP_Error;
 }
 
 //==================================================
@@ -523,8 +504,8 @@ void AIS_LocalContext::Hilight (const Handle(SelectMgr_EntityOwner)& theOwner,
 
   const Standard_Integer aHilightMode = GetHiMod (Handle(AIS_InteractiveObject)::DownCast (theOwner->Selectable()));
   myMainPM->BeginImmediateDraw();
-  theOwner->HilightWithColor (myMainPM, myCTX->HilightColor(), aHilightMode);
-  myMainPM->EndImmediateDraw (theView);
+  theOwner->HilightWithColor (myMainPM, getHiStyle (theOwner->Selectable()), aHilightMode);
+  myMainPM->EndImmediateDraw (theView->Viewer());
 }
 
 //==================================================
@@ -539,13 +520,13 @@ void AIS_LocalContext::Unhilight (const Handle(SelectMgr_EntityOwner)& theOwner,
     return;
   }
 
-  myMainPM->ClearImmediateDraw();
-  const Standard_Integer aHilightMode = GetHiMod (Handle(AIS_InteractiveObject)::DownCast (theOwner->Selectable()));
+  const Handle(AIS_InteractiveObject)& anObj = Handle(AIS_InteractiveObject)::DownCast (theOwner->Selectable());
+  const Standard_Integer aHilightMode = GetHiMod (anObj);
   if (IsSelected (theOwner))
   {
     if (theOwner->IsAutoHilight())
     {
-      theOwner->HilightWithColor (myMainPM, myCTX->SelectionColor(), aHilightMode);
+      theOwner->HilightWithColor (myMainPM, getSelStyle (anObj), aHilightMode);
     }
   }
   else
@@ -556,147 +537,92 @@ void AIS_LocalContext::Unhilight (const Handle(SelectMgr_EntityOwner)& theOwner,
 
 //=======================================================================
 //function : HilightPicked
-//purpose  : 
+//purpose  :
 //=======================================================================
-void AIS_LocalContext::HilightPicked(const Standard_Boolean updateviewer)
+void AIS_LocalContext::HilightPicked (const Standard_Boolean theToUpdateviewer)
 {
-  Standard_Boolean updMain(Standard_False);
-
-  Handle(AIS_Selection) Sel = AIS_Selection::Selection(mySelName.ToCString());
-#ifdef BUC60765
-  if( Sel.IsNull() ) return;
-#endif
-
-  typedef NCollection_DataMap <Handle(SelectMgr_SelectableObject), NCollection_Handle<SelectMgr_SequenceOfOwner> > SelectMgr_DataMapOfObjectOwners;
+  if (mySelection.IsNull())
+  {
+    return;
+  }
+  
+  typedef NCollection_Shared<SelectMgr_SequenceOfOwner> SelectMgr_HSequenceOfOwner;
+  typedef NCollection_DataMap <Handle(SelectMgr_SelectableObject), Handle(SelectMgr_HSequenceOfOwner) > SelectMgr_DataMapOfObjectOwners;
   SelectMgr_DataMapOfObjectOwners aMap;
 
-  Handle (PrsMgr_PresentationManager3d) PM = myMainPM;
-  
   // to avoid problems when there is a loop searching for selected objects...
-#if !defined OCC189 && !defined USE_MAP
-  const TColStd_Array1OfTransient& Obj = Sel->Objects()->Array1();
-  for(Standard_Integer i =Obj.Lower();i<=Sel->NbStored();i++)
-  {
-    const Handle(Standard_Transient)& Tr = Obj(i);
-#else
-  const AIS_NListTransient& Obj = Sel->Objects();
-  AIS_NListTransient::Iterator anIter( Obj );
-  for(; anIter.More(); anIter.Next())
+  for (AIS_NListOfEntityOwner::Iterator aSelIter (mySelection->Objects()); aSelIter.More(); aSelIter.Next())
   {
-    const Handle(Standard_Transient)& Tr = anIter.Value();
-#endif
-    if(!Tr.IsNull()){
-      const Handle(SelectMgr_EntityOwner)& Ownr =
-        *((const Handle(SelectMgr_EntityOwner)*) &Tr);
-      Handle(AIS_InteractiveObject) IO;
-      if(Ownr->HasSelectable()){
-       Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(Ownr);
-       if(BROwnr.IsNull() || !BROwnr->ComesFromDecomposition()){
-         Handle(SelectMgr_SelectableObject) SO  = Ownr->Selectable();
-         IO = *((Handle(AIS_InteractiveObject)*)&SO);
-         updMain = Standard_True;
-       }
-       else
-         updMain = Standard_True;
-      }
-      else
-       updMain = Standard_True;
-      Handle(SelectMgr_SelectableObject) SO = Ownr->Selectable();
-      Standard_Integer HM = GetHiMod(*((Handle(AIS_InteractiveObject)*)&SO));
-      if ( Ownr->IsAutoHilight() )
-        Ownr->HilightWithColor(PM,myCTX->SelectionColor(),HM);
-      else if ( aMap.IsBound (SO) )
-        aMap(SO)->Append ( Ownr );        
-      else {
-        NCollection_Handle<SelectMgr_SequenceOfOwner> aSeq = new SelectMgr_SequenceOfOwner;
-        aSeq->Append ( Ownr );
-        aMap.Bind ( SO, aSeq );
-      }      
+    const Handle(SelectMgr_EntityOwner)& anOwner = aSelIter.Value();
+    Handle(SelectMgr_SelectableObject) aSelObj = anOwner->Selectable();
+    if (anOwner->IsAutoHilight())
+    {
+      Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(aSelObj);
+      const Standard_Integer aHighMode = GetHiMod (anIO);
+      anOwner->HilightWithColor (myMainPM, getSelStyle (anIO), aHighMode);
+      continue;
+    }
+
+    Handle(SelectMgr_HSequenceOfOwner) aSeq;
+    if (aMap.Find (aSelObj, aSeq))
+    {
+      aSeq->Append (anOwner);
+    }
+    else
+    {
+      aSeq = new SelectMgr_HSequenceOfOwner();
+      aSeq->Append (anOwner);
+      aMap.Bind (aSelObj, aSeq);
     }
   }
 
-  for ( SelectMgr_DataMapOfObjectOwners::Iterator aMapIter(aMap); 
-        aMapIter.More(); aMapIter.Next() )
+  for (SelectMgr_DataMapOfObjectOwners::Iterator aMapIter (aMap); aMapIter.More(); aMapIter.Next())
   {
     aMapIter.Key()->HilightSelected (myMainPM, *aMapIter.Value());
   }
 
-  if (updateviewer)
+  if (theToUpdateviewer)
   {
     myCTX->CurrentViewer()->Update();
   }
 }
 
 //==================================================
-// Function: 
+// Function: UnhilightPicked
 // Purpose :
 //==================================================
-void AIS_LocalContext::UnhilightPicked (const Standard_Boolean updateviewer)
+void AIS_LocalContext::UnhilightPicked (const Standard_Boolean theToUpdateViewer)
 {
   myMainPM->ClearImmediateDraw();
+  if (mySelection.IsNull())
+  {
+    return;
+  }
 
-  Standard_Boolean updMain(Standard_False);
-
-  Handle(AIS_Selection) Sel = AIS_Selection::Selection(mySelName.ToCString());
-#ifdef BUC60765
-  if( Sel.IsNull() ) return;
-#endif
-  Handle (PrsMgr_PresentationManager3d) PM = myMainPM;
   NCollection_Map<Handle(SelectMgr_SelectableObject)> anObjMap;
-  
-#if !defined OCC189 && !defined USE_MAP  
-  const TColStd_Array1OfTransient& Obj = Sel->Objects()->Array1();
-  for(Standard_Integer i =Obj.Lower();i<=Sel->NbStored();i++){
-    const Handle(Standard_Transient)& Tr = Obj(i);
-#else
-  const AIS_NListTransient& Obj = Sel->Objects();
-  AIS_NListTransient::Iterator anIter( Obj );
-  for(; anIter.More(); anIter.Next()){
-    const Handle(Standard_Transient)& Tr = anIter.Value();
-#endif
-    if(!Tr.IsNull()){
-      const Handle(SelectMgr_EntityOwner)& Ownr =
-        *((const Handle(SelectMgr_EntityOwner)*) &Tr);
-      Standard_Integer HM(0);
-      if(Ownr->HasSelectable()){
-#ifdef BUC60876
-       Handle(SelectMgr_SelectableObject) SO  = Ownr->Selectable();
-       Handle(AIS_InteractiveObject) IO = *((Handle(AIS_InteractiveObject)*)&SO);
-        anObjMap.Add (IO);
-
-        HM = GetHiMod(IO);
-#endif
-       Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(Ownr);
-       if(BROwnr.IsNull() || !BROwnr->ComesFromDecomposition()){
-#ifndef BUC60876
-         Handle(SelectMgr_SelectableObject) SO  = Ownr->Selectable();
-         Handle(AIS_InteractiveObject) IO = *((Handle(AIS_InteractiveObject)*)&SO);
-         HM = GetHiMod(IO);
-#endif
-         updMain = Standard_True;
-       }
-       else
-         updMain = Standard_True;
-      }
-      Ownr->Unhilight(PM,HM);
-    }
+  for (AIS_NListOfEntityOwner::Iterator aSelIter (mySelection->Objects()); aSelIter.More(); aSelIter.Next())
+  {
+    const Handle(SelectMgr_EntityOwner)& anOwner = aSelIter.Value();
+    Handle(SelectMgr_SelectableObject) aSelObj = anOwner->Selectable();
+    Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast (aSelObj);
+    anObjMap.Add (aSelObj);
+    Standard_Integer aHighMode = GetHiMod (anIO);
+    anOwner->Unhilight (myMainPM, aHighMode);
   }
-  
-  for (NCollection_Map<Handle(SelectMgr_SelectableObject)>::Iterator anIter1 ( anObjMap ); 
-        anIter1.More(); anIter1.Next() )
+
+  for (NCollection_Map<Handle(SelectMgr_SelectableObject)>::Iterator aMapIter (anObjMap);
+       aMapIter.More(); aMapIter.Next())
   {
-    if ( !anIter1.Key()->IsAutoHilight() )
-      anIter1.Key()->ClearSelected();
+    if (!aMapIter.Key()->IsAutoHilight())
+    {
+      aMapIter.Key()->ClearSelected();
+    }
   }
 
-  if(updateviewer){
-#ifdef BUC60774
+  if (theToUpdateViewer)
+  {
     myCTX->CurrentViewer()->Update();
-#else
-    if(updMain) myCTX->CurrentViewer()->Update();
-#endif
   }
-  
 }
 
 //=======================================================================
@@ -713,15 +639,9 @@ Standard_Boolean AIS_LocalContext::IsSelected(const Handle(AIS_InteractiveObject
 //purpose  : 
 //=======================================================================
 
-Standard_Boolean AIS_LocalContext::IsSelected(const Handle(SelectMgr_EntityOwner)& Ownr) const 
+Standard_Boolean AIS_LocalContext::IsSelected (const Handle(SelectMgr_EntityOwner)& theOwner) const 
 {
-  if (Ownr.IsNull()) return Standard_False;
-#ifdef BUC60569
-  Standard_Boolean state = (Ownr->State()!=0);
-#else
-  Standard_Boolean state = (Ownr->State()==1);
-#endif
-  return state;
+  return !theOwner.IsNull() && theOwner->IsSelected();
 }
 
 //==================================================
@@ -731,8 +651,7 @@ Standard_Boolean AIS_LocalContext::IsSelected(const Handle(SelectMgr_EntityOwner
 void AIS_LocalContext::
 InitSelected()
 {
-  AIS_Selection::SetCurrentSelection(mySelName.ToCString());
-  AIS_Selection::CurrentSelection()->Init();
+  mySelection->Init();
 }
 
 //==================================================
@@ -742,7 +661,7 @@ InitSelected()
 Standard_Boolean AIS_LocalContext::
 MoreSelected() const 
 {
-  return AIS_Selection::CurrentSelection()->More();
+  return mySelection->More();
 }
 
 //==================================================
@@ -752,87 +671,93 @@ MoreSelected() const
 void AIS_LocalContext::
 NextSelected()
 {
-  AIS_Selection::CurrentSelection()->Next();
+  mySelection->Next();
 }
 
 //==================================================
-// Function: 
+// Function: HasShape
 // Purpose :
 //==================================================
-Standard_Boolean AIS_LocalContext::
-HasShape() const 
+Standard_Boolean AIS_LocalContext::HasShape() const
 {
-  Handle(Standard_Transient) Tr = AIS_Selection::CurrentSelection()->Value();
-  if( Tr.IsNull() ) return Standard_False;
-  Handle(SelectMgr_EntityOwner) EO = *((Handle(SelectMgr_EntityOwner)*)&Tr);
-  Handle(StdSelect_BRepOwner) BRO = Handle(StdSelect_BRepOwner)::DownCast(EO);
-  if(BRO.IsNull()) return Standard_False;
-  Standard_Boolean hasshape = BRO->HasShape();
-  Standard_Boolean comes = BRO->ComesFromDecomposition();
-  return (hasshape&&comes);
+  if (!mySelection->More())
+  {
+    return Standard_False;
+  }
+
+  Handle(StdSelect_BRepOwner) aBROwner = Handle(StdSelect_BRepOwner)::DownCast(mySelection->Value());
+  return !aBROwner.IsNull()
+       && aBROwner->HasShape()
+       && aBROwner->ComesFromDecomposition();
+}
+
+//================================================================
+// Function : HasSelectedShape
+// Purpose  : Checks if there is a selected shape regardless of its decomposition status
+//================================================================
+Standard_Boolean AIS_LocalContext::HasSelectedShape() const
+{
+  if (!mySelection->More())
+  {
+    return Standard_False;
+  }
+
+  Handle(StdSelect_BRepOwner) aBrepOwner = Handle(StdSelect_BRepOwner)::DownCast (mySelection->Value());
+  return !aBrepOwner.IsNull()
+      && aBrepOwner->HasShape();
 }
 
 //==================================================
-// Function: 
+// Function: SelectedShape
 // Purpose :
 //==================================================
-const TopoDS_Shape& AIS_LocalContext::
-SelectedShape() const 
+TopoDS_Shape AIS_LocalContext::SelectedShape() const 
 {
-  static TopoDS_Shape aSh;
-  Handle(Standard_Transient) Tr = AIS_Selection::CurrentSelection()->Value();
-  Handle(SelectMgr_EntityOwner) EO = *((Handle(SelectMgr_EntityOwner)*)&Tr);
-  Handle(StdSelect_BRepOwner) BRO = Handle(StdSelect_BRepOwner)::DownCast(EO);
-  if( BRO.IsNull() ) 
+  if (!mySelection->More())
   {
-    return aSh;
+    return TopoDS_Shape();
   }
-  return BRO->Shape();
+
+  Handle(StdSelect_BRepOwner) aBRO = Handle(StdSelect_BRepOwner)::DownCast(mySelection->Value());
+  if (aBRO.IsNull())
+  {
+    return TopoDS_Shape();
+  }
+
+  return aBRO->Shape().Located (aBRO->Location() * aBRO->Shape().Location());
 }
 
 //==================================================
-// Function: 
+// Function: SelectedInteractive
 // Purpose :
 //==================================================
-Handle(AIS_InteractiveObject) AIS_LocalContext::
-SelectedInteractive() const 
+Handle(AIS_InteractiveObject) AIS_LocalContext::SelectedInteractive() const
 {
-  Handle(AIS_InteractiveObject) IO;
-  Handle(Standard_Transient) Tr = AIS_Selection::CurrentSelection()->Value();
-  if( !Tr.IsNull() ) {
-    Handle(SelectMgr_EntityOwner) EO = *((Handle(SelectMgr_EntityOwner)*)&Tr);
-    Handle(SelectMgr_SelectableObject) SO;
-    if(EO->HasSelectable()){
-      SO = EO->Selectable();
-      IO = *((Handle(AIS_InteractiveObject)*)&SO);
-    }
-  }
-  return IO;
+  return !mySelection->More()
+       ?  Handle(AIS_InteractiveObject)()
+       :  Handle(AIS_InteractiveObject)::DownCast (mySelection->Value()->Selectable());
 }
+
 //==================================================
-// Function: 
+// Function: SelectedOwner
 // Purpose :
 //==================================================
-Handle(SelectMgr_EntityOwner) AIS_LocalContext::
-SelectedOwner() const 
+Handle(SelectMgr_EntityOwner) AIS_LocalContext::SelectedOwner() const
 {
-  Handle(SelectMgr_EntityOwner) EO;
-  Handle(Standard_Transient) Tr = AIS_Selection::CurrentSelection()->Value();
-  if( !Tr.IsNull() )
-       EO = *((Handle(SelectMgr_EntityOwner)*)&Tr);
-  return EO;
+  return !mySelection->More()
+       ?  Handle(SelectMgr_EntityOwner)()
+       :  mySelection->Value();
 }
 
 //==================================================
 // Function: 
 // Purpose :
 //==================================================
-Standard_Boolean AIS_LocalContext::
-HasApplicative() const 
+Standard_Boolean AIS_LocalContext::HasApplicative() const
 {
-  Handle(AIS_InteractiveObject) IO = SelectedInteractive();
-  if( IO.IsNull() ) return Standard_False;
-  return IO->HasOwner();
+  Handle(AIS_InteractiveObject) anIO = SelectedInteractive();
+  return !anIO.IsNull()
+       && anIO->HasOwner();
 }
 
 //==================================================
@@ -868,15 +793,13 @@ void AIS_LocalContext::UpdateSelected(const Handle(AIS_InteractiveObject)& anobj
   if (anobj.IsNull() || anobj->IsAutoHilight())
     return;
 
-  AIS_Selection::SetCurrentSelection(mySelName.ToCString());
-  Handle(AIS_Selection) Sel = AIS_Selection::CurrentSelection();
-
   SelectMgr_SequenceOfOwner aSeq;
-  for ( Sel->Init(); Sel->More(); Sel->Next() ){
-    Handle(SelectMgr_EntityOwner) aOwner = Handle(SelectMgr_EntityOwner)::DownCast(Sel->Value());
-
-    if ( !aOwner.IsNull() && aOwner->HasSelectable() && aOwner->Selectable() == anobj )
-      aSeq.Append( aOwner );
+  for (AIS_NListOfEntityOwner::Iterator aSelIter (mySelection->Objects()); aSelIter.More(); aSelIter.Next())
+  {
+    if (aSelIter.Value()->IsSameSelectable (anobj))
+    {
+      aSeq.Append (aSelIter.Value());
+    }
   }
 
   if ( aSeq.Length() )
@@ -893,30 +816,205 @@ void AIS_LocalContext::UpdateSelected(const Handle(AIS_InteractiveObject)& anobj
 // Function: ClearSelected
 // Purpose :
 //==================================================
-void AIS_LocalContext::ClearSelected(const Standard_Boolean updateviewer)
+void AIS_LocalContext::ClearSelected (const Standard_Boolean updateviewer)
 {
   UnhilightPicked(updateviewer);
-  AIS_Selection::SetCurrentSelection(mySelName.ToCString());
-
-  Handle(AIS_Selection) Sel = AIS_Selection::CurrentSelection();
-#if !defined OCC189 && !defined USE_MAP   
-  const TColStd_Array1OfTransient& Obj = Sel->Objects()->Array1();
-  for(Standard_Integer i =Obj.Lower();i<=Sel->NbStored();i++){
-    const Handle(Standard_Transient)& Tr = Obj(i);
-#else
-  const AIS_NListTransient& Obj = Sel->Objects();
-  AIS_NListTransient::Iterator anIter( Obj );
-  for(; anIter.More(); anIter.Next()){
-    const Handle(Standard_Transient)& Tr = anIter.Value();
-#endif
-    if(!Tr.IsNull()){
-      (*((const Handle(SelectMgr_EntityOwner)*)&Tr))->State(0);
-    }
+  for (AIS_NListOfEntityOwner::Iterator aSelIter (mySelection->Objects()); aSelIter.More(); aSelIter.Next())
+  {
+    aSelIter.Value()->SetSelected (Standard_False);
   }
-  AIS_Selection::Select();
+  mySelection->Clear();
   mylastindex = 0;
 }
 
+//==================================================
+// Function: ClearOutdatedSelection
+// Purpose :
+//==================================================
+void AIS_LocalContext::ClearOutdatedSelection (const Handle(AIS_InteractiveObject)& theIO,
+                                               const Standard_Boolean toClearDeactivated)
+{
+  // 1. Collect selectable entities
+  SelectMgr_IndexedMapOfOwner aValidOwners;
+
+  const TColStd_ListOfInteger& aModes = SelectionModes (theIO);
+
+  TColStd_ListIteratorOfListOfInteger aModeIter (aModes);
+  for (; aModeIter.More(); aModeIter.Next())
+  {
+    int aMode = aModeIter.Value();
+    if (!theIO->HasSelection(aMode))
+    {
+      continue;
+    }
+
+    if (toClearDeactivated && !mySM->IsActivated(theIO, aMode, myMainVS))
+    {
+      continue;
+    }
+
+    Handle(SelectMgr_Selection) aSelection = theIO->Selection(aMode);
+    for (aSelection->Init(); aSelection->More(); aSelection->Next())
+    {
+      Handle(SelectBasics_SensitiveEntity) anEntity = aSelection->Sensitive()->BaseSensitive();
+      if (anEntity.IsNull())
+      {
+        continue;
+      }
+
+      Handle(SelectMgr_EntityOwner) anOwner =
+        Handle(SelectMgr_EntityOwner)::DownCast (anEntity->OwnerId());
+
+      if (anOwner.IsNull())
+      {
+        continue;
+      }
+
+      aValidOwners.Add(anOwner);
+    }
+  }
+
+  // 2. Refresh context's detection and selection and keep only active owners.
+  // Keep last detected object for lastindex initialization.
+  Handle(SelectMgr_EntityOwner) aLastPicked;
+  if (IsValidIndex (mylastindex))
+  {
+    aLastPicked = myMapOfOwner->FindKey (mylastindex);
+  }
+
+  // Remove entity owners from detected sequences
+  for (Standard_Integer anIdx = 1; anIdx <= myDetectedSeq.Length(); ++anIdx)
+  {
+    Handle(SelectMgr_EntityOwner) anOwner = myMainVS->Picked (myDetectedSeq (anIdx));
+    if (anOwner.IsNull() || !anOwner->IsSameSelectable (theIO) || aValidOwners.Contains (anOwner))
+    {
+      continue;
+    }
+
+    myDetectedSeq.Remove (anIdx--);
+
+    if (anIdx < myCurDetected)
+    {
+      myCurDetected--;
+    }
+  }
+  myCurDetected = Max (myCurDetected, 1);
+
+  Standard_Boolean isAISRemainsDetected = Standard_False;
+
+  // 3. AIS_Selection : remove entity owners from AIS_Selection
+  const Handle(V3d_Viewer)& aViewer = myCTX->CurrentViewer();
+  NCollection_List<Handle(SelectMgr_EntityOwner)> aRemoveEntites;
+  for (AIS_NListOfEntityOwner::Iterator aSelIter (mySelection->Objects()); aSelIter.More(); aSelIter.Next())
+  {
+    Handle(SelectMgr_EntityOwner) anOwner = aSelIter.Value();
+    if (!anOwner->IsSameSelectable (theIO))
+    {
+      continue;
+    }
+
+    if (aValidOwners.Contains (anOwner))
+    {
+      isAISRemainsDetected = Standard_True;
+    }
+    else
+    {
+      aRemoveEntites.Append (anOwner);
+      anOwner->SetSelected (Standard_False);
+      for (V3d_ListOfViewIterator anActiveViewIter (aViewer->ActiveViewIterator()); anActiveViewIter.More(); anActiveViewIter.Next())
+      {
+        Unhilight (anOwner, anActiveViewIter.Value());
+      }
+    }
+  }
+
+  for (NCollection_List<Handle(SelectMgr_EntityOwner)>::Iterator anIterRemove (aRemoveEntites);
+       anIterRemove.More(); anIterRemove.Next())
+  {
+    mySelection->Select (anIterRemove.Value());
+  }
+
+  // 4. AIS_LocalContext - myMapOfOwner : remove entity owners from myMapOfOwner
+  SelectMgr_IndexedMapOfOwner anOwnersToKeep;
+  for (Standard_Integer anIdx = 1; anIdx <= myMapOfOwner->Extent(); anIdx++)
+  {
+    Handle(SelectMgr_EntityOwner) anOwner = myMapOfOwner->FindKey (anIdx);
+    if (anOwner.IsNull())
+    {
+      continue;
+    }
+
+    if (!anOwner->IsSameSelectable (theIO) || aValidOwners.Contains (anOwner))
+    {
+      anOwnersToKeep.Add (anOwner);
+    }
+    else
+    {
+      for (V3d_ListOfViewIterator anActiveViewIter (aViewer->ActiveViewIterator()); anActiveViewIter.More(); anActiveViewIter.Next())
+      {
+        Unhilight (anOwner, anActiveViewIter.Value());
+      }
+    }
+  }
+  myMapOfOwner->Clear();
+  myMapOfOwner->Assign (anOwnersToKeep);
+
+  if (myDetectedSeq.IsEmpty() && !aLastPicked.IsNull())
+  {
+    myMainPM->ClearImmediateDraw();
+    mylastindex = 0;
+  }
+  else if (!aLastPicked.IsNull())
+  {
+    // For a case when the last detected owner was unhilighted and removed as outdated we
+    // need to check if there were other detected owners with less priority. If yes then
+    // one from the remaining should be treated.
+    Standard_Integer anIndex = 1, aDetectedSeqLength = myDetectedSeq.Length();
+    for (; anIndex <= aDetectedSeqLength; anIndex++)
+    {
+      if (aLastPicked == myMainVS->Picked (myDetectedSeq.Value(anIndex)))
+      {
+        break; // detected owner was not removed
+      }
+    }
+    if (anIndex <= aDetectedSeqLength)
+    {
+      // Last detected owner was not removed, update mylastindex variable
+      mylastindex = myMapOfOwner->FindIndex (aLastPicked);
+    }
+    else
+    {
+      // Last detected owner was removed. First object from sequence become detected.
+      // Pass any active view because in current implementation the highlighting is
+      // synchronized in all view.
+      manageDetected (myMainVS->Picked (myDetectedSeq.First()),
+                      aViewer->ActiveViewIterator().Value(),
+                      Standard_False);
+    }
+  }
+
+  // Renew iterator of ::DetectedCurrentObject()
+  if (!isAISRemainsDetected)
+  {
+    // Remove the interactive object from detected sequences
+    for (Standard_Integer anIdx = 1; anIdx <= myAISDetectedSeq.Length(); ++anIdx)
+    {
+      Handle(AIS_InteractiveObject) aDetectedIO = myAISDetectedSeq.Value (anIdx);
+      if (aDetectedIO.IsNull() || aDetectedIO != theIO)
+      {
+        continue;
+      }
+
+      myAISDetectedSeq.Remove (anIdx--);
+
+      if (anIdx < myAISCurDetected)
+      {
+        myAISCurDetected--;
+      }
+    }
+    myAISCurDetected = Max (myAISCurDetected, 1);
+  }
+}
 
 //=======================================================================
 //function : SetSelected
@@ -931,32 +1029,22 @@ void AIS_LocalContext::SetSelected(const Handle(AIS_InteractiveObject)& anIObj,
   //1st case, owner already <anIObj> as owner  
   // and not separated is found...
 
-  Handle(AIS_Selection) sel = AIS_Selection::Selection(mySelName.ToCString());
-  //Standard_Boolean found(Standard_False);
-  Handle(Standard_Transient) Tr;
   Handle(SelectMgr_EntityOwner) EO = FindSelectedOwnerFromIO(anIObj);
   if(EO.IsNull()){
-    //check if in selection number 0 there is an owner that can be triturated...
-    if(anIObj->HasSelection(0)){
-      const Handle(SelectMgr_Selection)& SIOBJ = anIObj->Selection(0);
-      SIOBJ->Init();
-      if(SIOBJ->More()){
-       Handle(SelectBasics_EntityOwner) BO = SIOBJ->Sensitive()->OwnerId();
-       EO = *((Handle(SelectMgr_EntityOwner)*)&BO);
-      }
+    //check if global selection there is an owner that can be triturated...
+    if (anIObj->HasSelection (anIObj->GlobalSelectionMode()))
+    {
+      EO = anIObj->GlobalSelOwner();
     }
     if(EO.IsNull()) 
-      EO = new SelectMgr_EntityOwner(anIObj);
+      EO = new SelectMgr_EntityOwner((const Handle(SelectMgr_SelectableObject)&)anIObj);
   }
   
   ClearSelected(Standard_False);
-#ifdef OCC138 
-  AIS_Selection::Select(EO);
-  EO->State(1);
-#else
-  EO->State(1);
-  AIS_Selection::Select(EO);
-#endif
+
+  mySelection->Select(EO);
+  EO->SetSelected (Standard_True);
+
   HilightPicked(updateviewer);
 }
 
@@ -974,42 +1062,25 @@ void AIS_LocalContext::AddOrRemoveSelected(const Handle(AIS_InteractiveObject)&
   Handle(SelectMgr_EntityOwner) EO;
 
   EO = FindSelectedOwnerFromIO(anIObj);
-#ifndef OCC138
-  if(!EO.IsNull())
-    EO->State(0);
-  else{
-#else
-  if(EO.IsNull()) {
-#endif
-    if(anIObj->HasSelection(0)){
-      const Handle(SelectMgr_Selection)& SIOBJ = anIObj->Selection(0);
-      SIOBJ->Init();
-      if(SIOBJ->More()){
-       Handle(SelectBasics_EntityOwner) BO = SIOBJ->Sensitive()->OwnerId();
-       EO = *((Handle(SelectMgr_EntityOwner)*)&BO);
-      }
+
+  if (EO.IsNull())
+  {
+    if(anIObj->HasSelection (anIObj->GlobalSelectionMode()))
+    {
+      EO = anIObj->GlobalSelOwner();
+    }
+    if(EO.IsNull())
+    {
+      EO = new SelectMgr_EntityOwner((const Handle(SelectMgr_SelectableObject)&)anIObj);
     }
-    if(EO.IsNull()) 
-      EO = new SelectMgr_EntityOwner(anIObj);
-#ifndef OCC138
-    EO->State(1);
-#endif
   }
-  
-//  cout<<"AIS_LocalContext::AddOrRemoveSelected : Selection = "<<mySelName<<endl;
-  const Handle(AIS_Selection)& S = AIS_Selection::Selection(mySelName.ToCString());
-#ifdef OCC138
-  if(!S.IsNull()) {
-    AIS_SelectStatus aStatus = S->Select(EO);
-    if(aStatus == AIS_SS_Added)
-      EO->State(1);
-    else
-      EO->State(0);
+
+  if (!mySelection.IsNull())
+  {
+    AIS_SelectStatus aStatus = mySelection->Select(EO);
+    EO->SetSelected (aStatus == AIS_SS_Added);
   }
-#else
-  if(!S.IsNull())
-    S->Select(EO);
-#endif
+
   HilightPicked(updateviewer);
 }
 
@@ -1020,42 +1091,33 @@ void AIS_LocalContext::AddOrRemoveSelected(const Handle(AIS_InteractiveObject)&
 void AIS_LocalContext::AddOrRemoveSelected(const TopoDS_Shape& Sh,
                                           const Standard_Boolean updateviewer)
 {     
-  UnhilightPicked(Standard_False);
+  UnhilightPicked (Standard_False);
   Handle(SelectMgr_EntityOwner) EO = FindSelectedOwnerFromShape(Sh);
-  if(!EO.IsNull()){
-//    cout<<"AIS_LocalContext::AddOrRemoveSelected(sh) : Selection = "<<mySelName<<endl;
-    
-#ifdef OCC138
-    AIS_Selection::Selection(mySelName.ToCString())->Select(EO);
-    EO->State(1);
-#else
-    EO->State(1);
-    AIS_Selection::Selection(mySelName.ToCString())->Select(EO);
-#endif
+  if (!EO.IsNull())
+  {
+    mySelection->Select(EO);
+    EO->SetSelected (Standard_True);
   }
-  HilightPicked(updateviewer);
+  HilightPicked (updateviewer);
 }
 
-void AIS_LocalContext::AddOrRemoveSelected(const Handle(SelectMgr_EntityOwner)& Ownr,
-                                          const Standard_Boolean updateviewer)
-{     
-  //Not Yet Implemented
+void AIS_LocalContext::AddOrRemoveSelected (const Handle(SelectMgr_EntityOwner)& theOwner,
+                                          const Standard_Boolean toUpdateViewer)
+{
   if(myAutoHilight)
-  UnhilightPicked(Standard_False);
-//  cout<<"AIS_LocalContext::AddOrRemoveSelected(ownr) : Selection = "<<mySelName<<endl;
+  {
+    UnhilightPicked (Standard_False);
+  }
 
-  Standard_Integer mod = Ownr->State()==0 ? 1 : 0;
-#ifdef OCC138
-  AIS_Selection::Selection(mySelName.ToCString())->Select(Ownr);
+  Standard_Boolean toSelect = theOwner->IsSelected() ? Standard_False : Standard_True;
+
+  mySelection->Select(theOwner);
+  theOwner->SetSelected (toSelect);
 
-  Ownr->State(mod);  
-#else
-  Ownr->State(mod);
-  
-  AIS_Selection::Selection(mySelName.ToCString())->Select(Ownr);
-#endif
   if(myAutoHilight)
-  HilightPicked(updateviewer);
+  {
+    HilightPicked (toUpdateViewer);
+  }
 }
 
 //==================================================
@@ -1068,6 +1130,7 @@ void AIS_LocalContext::manageDetected (const Handle(SelectMgr_EntityOwner)& theP
 {
   if (thePickOwner.IsNull())
   {
+    myMainPM->ClearImmediateDraw();
     if (theToRedrawImmediate)
     {
       theView->RedrawImmediate();
@@ -1107,9 +1170,9 @@ void AIS_LocalContext::manageDetected (const Handle(SelectMgr_EntityOwner)& theP
   //
   //=======================================================================================================
 
-  const Standard_Integer aNewIndex = myMapOfOwner.Contains  (thePickOwner)
-                                   ? myMapOfOwner.FindIndex (thePickOwner)
-                                   : myMapOfOwner.Add       (thePickOwner);
+  const Standard_Integer aNewIndex = myMapOfOwner->Contains  (thePickOwner)
+                                   ? myMapOfOwner->FindIndex (thePickOwner)
+                                   : myMapOfOwner->Add       (thePickOwner);
 
   // For the advanced mesh selection mode the owner indices comparison
   // is not effective because in that case only one owner manage the
@@ -1119,17 +1182,17 @@ void AIS_LocalContext::manageDetected (const Handle(SelectMgr_EntityOwner)& theP
   if (aNewIndex != mylastindex
    || thePickOwner->IsForcedHilight())
   {
+    myMainPM->ClearImmediateDraw();
     if (mylastindex != 0
-     && mylastindex <= myMapOfOwner.Extent())
+     && mylastindex <= myMapOfOwner->Extent())
     {
-      const Handle(SelectMgr_EntityOwner)& aLastOwner = myMapOfOwner (mylastindex);
+      const Handle(SelectMgr_EntityOwner)& aLastOwner = myMapOfOwner->FindKey (mylastindex);
       Unhilight (aLastOwner, theView);
     }
 
     if (myAutoHilight)
     {
-      if (thePickOwner->State() <= 0
-       || myCTX->ToHilightSelected())
+      if (!thePickOwner->IsSelected() || myCTX->ToHilightSelected())
       {
         Hilight (thePickOwner, theView);
       }
@@ -1142,7 +1205,7 @@ void AIS_LocalContext::manageDetected (const Handle(SelectMgr_EntityOwner)& theP
     mylastindex = aNewIndex;
   }
 
-  if (mylastindex)
+  if (mylastindex != 0)
   {
     mylastgood = mylastindex;
   }
@@ -1167,14 +1230,13 @@ Standard_Boolean AIS_LocalContext::HasDetectedShape() const
 const TopoDS_Shape&
 AIS_LocalContext::DetectedShape() const
 {
-  static TopoDS_Shape bidsh;
   if(mylastindex != 0)
   {
-    Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(myMapOfOwner(mylastindex));
-    if(BROwnr.IsNull()) return bidsh;
+    Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(myMapOfOwner->FindKey (mylastindex));
+    if(BROwnr.IsNull()) return AIS_myDummyShape;
     return BROwnr->Shape();
   }
-  return bidsh;
+  return AIS_myDummyShape;
 }                                          
 
 //=======================================================================
@@ -1187,8 +1249,8 @@ AIS_LocalContext::DetectedInteractive() const
 {
   Handle(AIS_InteractiveObject) Iobj;
   if(IsValidIndex(mylastindex)){
-    Handle(SelectMgr_SelectableObject) SO = myMapOfOwner.FindKey(mylastindex)->Selectable();
-    Iobj = *((Handle(AIS_InteractiveObject)*) &SO);
+    Handle(SelectMgr_SelectableObject) SO = myMapOfOwner->FindKey(mylastindex)->Selectable();
+    Iobj = Handle(AIS_InteractiveObject)::DownCast (SO);
   }
   return Iobj;
 }
@@ -1200,7 +1262,7 @@ Handle(SelectMgr_EntityOwner) AIS_LocalContext::DetectedOwner() const
 {
   Handle(SelectMgr_EntityOwner) bid;
   if(!IsValidIndex(mylastindex)) return bid;
-  return myMapOfOwner.FindKey(mylastindex);
+  return myMapOfOwner->FindKey(mylastindex);
 }
 
 
@@ -1211,7 +1273,7 @@ Handle(SelectMgr_EntityOwner) AIS_LocalContext::DetectedOwner() const
 
 Standard_Boolean AIS_LocalContext::ComesFromDecomposition(const Standard_Integer PickedIndex) const 
 {
-  const Handle(SelectMgr_EntityOwner)& OWN = myMapOfOwner.FindKey(PickedIndex);
+  const Handle(SelectMgr_EntityOwner)& OWN = myMapOfOwner->FindKey(PickedIndex);
   Handle(SelectMgr_SelectableObject) aSel  = OWN->Selectable();
   if (myActiveObjects.IsBound (aSel)) { // debug of jmi
     const Handle(AIS_LocalStatus)& Stat      = myActiveObjects(aSel);    
@@ -1220,27 +1282,6 @@ Standard_Boolean AIS_LocalContext::ComesFromDecomposition(const Standard_Integer
   return Standard_False;
 }
 
-
-//=======================================================================
-//function : DisplayAreas
-//purpose  : 
-//=======================================================================
-
-void AIS_LocalContext::DisplayAreas(const Handle(V3d_View)& aviou)
-{
-    myMainVS->DisplayAreas(aviou);
-}
-
-//=======================================================================
-//function : ClearAreas
-//purpose  : 
-//=======================================================================
-
-void AIS_LocalContext::ClearAreas(const Handle(V3d_View)& aviou)
-{
-    myMainVS->ClearAreas(aviou);
-}
-
 //=======================================================================
 //function : DisplaySensitive
 //purpose  : 
@@ -1268,8 +1309,8 @@ void AIS_LocalContext::ClearSensitive(const Handle(V3d_View)& aviou)
 //=======================================================================
 Standard_Boolean AIS_LocalContext::IsShape(const Standard_Integer Index) const
 {
-  
-  if(Handle(StdSelect_BRepOwner)::DownCast(myMapOfOwner.FindKey(Index)).IsNull())
+  Handle(SelectMgr_EntityOwner) aEO (myMapOfOwner->FindKey(Index));
+  if (aEO.IsNull() || ! aEO->IsKind(STANDARD_TYPE(StdSelect_BRepOwner)))
     return Standard_False;
   return 
     ComesFromDecomposition(Index);
@@ -1277,14 +1318,12 @@ Standard_Boolean AIS_LocalContext::IsShape(const Standard_Integer Index) const
 
 Standard_Boolean AIS_LocalContext::IsValidForSelection(const Handle(AIS_InteractiveObject)& anIObj) const 
 {
-
-#ifdef IMP120701
+  const Handle(SelectMgr_SelectableObject)& aSelObj = anIObj; // to avoid ambiguity
   // Shape was not transfered from AIS_Shape to EntityOwner
   Handle(AIS_Shape) shape = Handle(AIS_Shape)::DownCast(anIObj);
   if( !shape.IsNull() ) 
-    return myFilters->IsOk(new StdSelect_BRepOwner(shape->Shape(),shape));
-#endif
-  return myFilters->IsOk(new SelectMgr_EntityOwner(anIObj));
+    return myFilters->IsOk(new StdSelect_BRepOwner(shape->Shape(), aSelObj));
+  return myFilters->IsOk(new SelectMgr_EntityOwner(aSelObj));
 }
 
 
@@ -1306,7 +1345,7 @@ Standard_Integer AIS_LocalContext::HilightNextDetected (const Handle(V3d_View)&
   {
     myCurDetected = 1;
   }
-  Handle(SelectMgr_EntityOwner) anOwner = myMainVS->Picked (myCurDetected);
+  Handle(SelectMgr_EntityOwner) anOwner = myMainVS->Picked (myDetectedSeq (myCurDetected));
   if (anOwner.IsNull())
   {
     return 0;
@@ -1327,11 +1366,12 @@ Standard_Integer AIS_LocalContext::HilightPreviousDetected (const Handle(V3d_Vie
     return 0;
   }
 
+  const Standard_Integer aLen = myDetectedSeq.Length();
   if (--myCurDetected < 1)
   {
-    myCurDetected = 1;
+    myCurDetected = aLen;
   }
-  Handle(SelectMgr_EntityOwner) anOwner = myMainVS->Picked (myCurDetected);
+  Handle(SelectMgr_EntityOwner) anOwner = myMainVS->Picked (myDetectedSeq (myCurDetected));
   if (anOwner.IsNull())
   {
     return 0;
@@ -1353,13 +1393,13 @@ Standard_Boolean AIS_LocalContext::UnhilightLastDetected (const Handle(V3d_View)
   }
 
   myMainPM->BeginImmediateDraw();
-  const Handle(SelectMgr_EntityOwner)& anOwner = myMapOfOwner (mylastindex);
+  const Handle(SelectMgr_EntityOwner)& anOwner = myMapOfOwner->FindKey (mylastindex);
   const Standard_Integer aHilightMode = anOwner->HasSelectable()
                                       ? GetHiMod (Handle(AIS_InteractiveObject)::DownCast (anOwner->Selectable()))
                                       : 0;
 
-  myMapOfOwner (mylastindex)->Unhilight (myMainPM, aHilightMode);
-  myMainPM->EndImmediateDraw (theView);
+  myMapOfOwner->FindKey (mylastindex)->Unhilight (myMainPM, aHilightMode);
+  myMainPM->EndImmediateDraw (theView->Viewer());
   mylastindex = 0;
   return Standard_True;
 }
@@ -1368,46 +1408,30 @@ Standard_Boolean AIS_LocalContext::UnhilightLastDetected (const Handle(V3d_View)
 //function : FindSelectedOwnerFromIO
 //purpose  : it is checked if one of the selected owners really presents IObj
 //=======================================================================
-Handle(SelectMgr_EntityOwner) AIS_LocalContext::FindSelectedOwnerFromIO
-                          (const Handle(AIS_InteractiveObject)& anIObj) const 
+Handle(SelectMgr_EntityOwner) AIS_LocalContext::FindSelectedOwnerFromIO (const Handle(AIS_InteractiveObject)& theObj) const
 {
   Handle(SelectMgr_EntityOwner) EO,bid;
-  if (anIObj.IsNull()) return EO;
-  
-  Handle(AIS_Selection) Sel = AIS_Selection::Selection(mySelName.ToCString());
-  if(Sel.IsNull()) {
-#ifdef DEB
-    cout<<"\t\tAIS_LocalCOntext::FindSelectedOwnerFromShape : Selection "
-        <<mySelName<<" Nulle "<<endl;
-#endif
-    return EO;
+  if (theObj.IsNull()
+   || mySelection.IsNull())
+  {
+    return Handle(SelectMgr_EntityOwner)();
   }
-  Standard_Boolean found(Standard_False);
-#if !defined OCC189 && !defined USE_MAP     
-  const TColStd_Array1OfTransient& Obj = Sel->Objects()->Array1();
-  for(Standard_Integer i =Obj.Lower();i<=Sel->NbStored();i++){
-    const Handle(Standard_Transient)& Tr = Obj(i);
-#else
-  const AIS_NListTransient& Obj = Sel->Objects();
-  AIS_NListTransient::Iterator anIter( Obj );
-  for(; anIter.More(); anIter.Next()){
-    const Handle(Standard_Transient)& Tr = anIter.Value();
-#endif
-    if(!Tr.IsNull()){
-      EO = *((Handle(SelectMgr_EntityOwner)*)&Tr);
-      if(EO->HasSelectable()){
-       Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(EO);
-       if(BROwnr.IsNull() || !BROwnr->ComesFromDecomposition()){
-         if (anIObj == EO->Selectable()){
-           found =Standard_True;
-           break;
-         }
-       }
-      }
+
+  for (AIS_NListOfEntityOwner::Iterator aSelIter (mySelection->Objects()); aSelIter.More(); aSelIter.Next())
+  {
+    if (!aSelIter.Value()->IsSameSelectable (theObj))
+    {
+      continue;
+    }
+
+    Handle(StdSelect_BRepOwner) aBROwner = Handle(StdSelect_BRepOwner)::DownCast(aSelIter.Value());
+    if (aBROwner.IsNull()
+    || !aBROwner->ComesFromDecomposition())
+    {
+      return aSelIter.Value();
     }
   }
-  if(found)  return EO;
-  return bid;
+  return Handle(SelectMgr_EntityOwner)();
 }
 
 //=======================================================================
@@ -1416,28 +1440,21 @@ Handle(SelectMgr_EntityOwner) AIS_LocalContext::FindSelectedOwnerFromIO
 //=======================================================================
 Handle(SelectMgr_EntityOwner) AIS_LocalContext::FindSelectedOwnerFromShape(const TopoDS_Shape& sh) const 
 {
-#ifdef OCC9026
   Handle(SelectMgr_EntityOwner) EO, bid;
-#else
-  Handle(SelectMgr_EntityOwner) EO;
-#endif
   if (sh.IsNull()) return EO;
   
-  Handle(AIS_Selection) Sel = AIS_Selection::Selection(mySelName.ToCString());
-  if(Sel.IsNull()) {
-#ifdef DEB
-    cout<<"\t\tAIS_LocalCOntext::FindSelectedOwnerFromShape : Selection "<<mySelName<<" Nulle "<<endl;
-#endif
+  if(mySelection.IsNull()) {
     return EO;
   }
   
   Standard_Boolean found(Standard_False);
 
-#ifdef OCC9026
   if (!found) {
-    SelectMgr_DataMapIteratorOfDataMapOfIntegerSensitive aSensitiveIt (myMainVS->Primitives());
-    for (; aSensitiveIt.More(); aSensitiveIt.Next()) {
-      EO = Handle(SelectMgr_EntityOwner)::DownCast (aSensitiveIt.Value()->OwnerId());
+    NCollection_List<Handle(SelectBasics_EntityOwner)> anActiveOwners;
+    myMainVS->ActiveOwners (anActiveOwners);
+    for (NCollection_List<Handle(SelectBasics_EntityOwner)>::Iterator anOwnersIt (anActiveOwners); anOwnersIt.More(); anOwnersIt.Next())
+    {
+      EO = Handle(SelectMgr_EntityOwner)::DownCast (anOwnersIt.Value());
       Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(EO);
       if (!BROwnr.IsNull() && BROwnr->HasShape() && BROwnr->Shape() == sh) {
         found = Standard_True;
@@ -1445,38 +1462,15 @@ Handle(SelectMgr_EntityOwner) AIS_LocalContext::FindSelectedOwnerFromShape(const
       }
     }
   }
-#else
-#if !defined OCC189 && !defined USE_MAP   
-  const TColStd_Array1OfTransient& Obj = Sel->Objects()->Array1();
-  for(Standard_Integer i =Obj.Lower();i<=Sel->NbStored();i++){
-    const Handle(Standard_Transient)& Tr = Obj(i);
-#else
-  const AIS_NListTransient& Obj = Sel->Objects();
-  AIS_NListTransient::Iterator anIter( Obj );
-  for(; anIter.More(); anIter.Next()){
-    const Handle(Standard_Transient)& Tr = anIter.Value();
-#endif
-    if(!Tr.IsNull()){
-      
-      EO = *((Handle(SelectMgr_EntityOwner)*)&Tr);
-      if(EO->HasShape())
-       if ( EO->Shape() == sh)
-         found =Standard_True;
-          break;
-    }
-  }
-#endif
 
   if(found)  return EO;
   return bid;
 }
 
-#ifdef IMP160701
 //=======================================================================
 //function : AIS_LocalContext::InitDetected
 //purpose  :
 //=======================================================================
-
 void AIS_LocalContext::InitDetected()
 {
   myAISCurDetected = myAISDetectedSeq.Length()? 1 : 0;
@@ -1486,47 +1480,56 @@ void AIS_LocalContext::InitDetected()
 //function : AIS_LocalContext::MoreDetected
 //purpose  :
 //=======================================================================
-
 Standard_Boolean AIS_LocalContext::MoreDetected() const
 {
   return (myAISCurDetected > 0 && myAISCurDetected <= myAISDetectedSeq.Length());
 }
 
-
 //=======================================================================
 //function : AIS_LocalContext::NextDetected
 //purpose  :
 //=======================================================================
-
 void AIS_LocalContext::NextDetected()
 {
-  if (MoreDetected()) myAISCurDetected++;
+  myAISCurDetected++;
 }
 
 //=======================================================================
 //function : DetectedCurrentShape
 //purpose  :
 //=======================================================================
-
 const TopoDS_Shape& AIS_LocalContext::DetectedCurrentShape() const
 {
-  static TopoDS_Shape bidsh;
-  if (MoreDetected())
-    return Handle(AIS_Shape)::DownCast(myAISDetectedSeq(myAISCurDetected))->Shape();
-  return bidsh;
-}
+  Handle(AIS_Shape) aCurrentShape = Handle(AIS_Shape)::DownCast (DetectedCurrentObject());
 
+  if (aCurrentShape.IsNull())
+  {
+    return AIS_myDummyShape;
+  }
+
+  return aCurrentShape->Shape();
+}
 //=======================================================================
 //function : DetectedCurrentObject
 //purpose  :
 //=======================================================================
-
 Handle(AIS_InteractiveObject) AIS_LocalContext::DetectedCurrentObject() const
 {
-  Handle(AIS_InteractiveObject) theIObj;
-  if (MoreDetected())
-    theIObj = myAISDetectedSeq(myAISCurDetected);
+  return MoreDetected() ? myAISDetectedSeq(myAISCurDetected) : NULL;
+}
 
-  return theIObj;
+//=======================================================================
+//function : RestoreActivatedModes
+//purpose  :
+//=======================================================================
+void AIS_LocalContext::RestoreActivatedModes() const
+{
+  for (AIS_DataMapOfSelStat::Iterator anIter (myActiveObjects); anIter.More(); anIter.Next())
+  {
+    const TColStd_ListOfInteger& anActivatedModes = anIter.Value()->SelectionModes();
+    for (TColStd_ListIteratorOfListOfInteger aModesIter (anActivatedModes); aModesIter.More(); aModesIter.Next())
+    {
+      mySM->Activate (anIter.Key(), aModesIter.Value(), myMainVS);
+    }
+  }
 }
-#endif