Salome HOME
Issue #2206 Avoid the ability to cancel the current sketch when saving,
[modules/shaper.git] / src / PartSet / PartSet_SketcherMgr.cpp
index be2d63ec498a65dbb7d865696ba1823332e79bd0..88334e9ee5b4eee569cb3c1b624283e4cf63e653 100755 (executable)
@@ -1,18 +1,33 @@
-// Copyright (C) 2014-20xx CEA/DEN, EDF R&D
-
-// File:        PartSet_SketcherMgr.cpp
-// Created:     19 Dec 2014
-// Author:      Vitaly SMETANNIKOV
+// Copyright (C) 2014-2017  CEA/DEN, EDF R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+//
+// See http://www.salome-platform.org/ or
+// email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
+//
 
 #include "PartSet_SketcherMgr.h"
-#include "PartSet_SketcherReetntrantMgr.h"
+#include "PartSet_SketcherReentrantMgr.h"
 #include "PartSet_Module.h"
-#include "PartSet_WidgetPoint2d.h"
-#include "PartSet_WidgetPoint2dDistance.h"
+#include "PartSet_MouseProcessor.h"
 #include "PartSet_Tools.h"
 #include "PartSet_WidgetSketchLabel.h"
 #include "PartSet_WidgetEditor.h"
 #include "PartSet_ResultSketchPrs.h"
+#include "PartSet_ExternalPointsMgr.h"
+#include "PartSet_PreviewSketchPlane.h"
 
 #include <XGUI_ModuleConnector.h>
 #include <XGUI_Displayer.h>
@@ -24,6 +39,7 @@
 #include <XGUI_PropertyPanel.h>
 #include <XGUI_ViewerProxy.h>
 #include <XGUI_OperationMgr.h>
+#include <XGUI_ErrorMgr.h>
 #include <XGUI_Tools.h>
 
 #include <ModuleBase_IPropertyPanel.h>
@@ -37,6 +53,8 @@
 #include <ModuleBase_Operation.h>
 #include <ModuleBase_WidgetEditor.h>
 #include <ModuleBase_ViewerPrs.h>
+#include <ModuleBase_Tools.h>
+#include <ModuleBase_ResultPrs.h>
 
 #include <GeomDataAPI_Point2D.h>
 
@@ -58,7 +76,7 @@
 #include <SketchPlugin_ConstraintEqual.h>
 #include <SketchPlugin_ConstraintTangent.h>
 #include <SketchPlugin_ConstraintCoincidence.h>
-#include <SketchPlugin_ConstraintFillet.h>
+#include <SketchPlugin_Fillet.h>
 #include <SketchPlugin_ConstraintMirror.h>
 #include <SketchPlugin_ConstraintAngle.h>
 #include <SketchPlugin_ConstraintCollinear.h>
@@ -66,6 +84,7 @@
 #include <SketchPlugin_MultiRotation.h>
 #include <SketchPlugin_MultiTranslation.h>
 #include <SketchPlugin_IntersectionPoint.h>
+#include <SketchPlugin_Projection.h>
 
 #include <SketcherPrs_Tools.h>
 
 #include <ModelAPI_Session.h>
 #include <ModelAPI_AttributeString.h>
 
+#include <ModelAPI_Validator.h>
+#include <ModelAPI_Tools.h>
+
 #include <QMouseEvent>
 #include <QApplication>
 #include <QCursor>
 #include <QMessageBox>
+#include <QMainWindow>
 
 //#define DEBUG_DO_NOT_BY_ENTER
+//#define DEBUG_SKETCHER_ENTITIES
+//#define DEBUG_SKETCH_ENTITIES_ON_MOVE
 
 //#define DEBUG_CURSOR
 
-/// Returns list of unique objects by sum of objects from List1 and List2
-/*QList<ModuleBase_ViewerPrsPtr> getSumList(const QList<ModuleBase_ViewerPrsPtr>& theList1,
-                                       const QList<ModuleBase_ViewerPrsPtr>& theList2)
-{
-  QList<ModuleBase_ViewerPrsPtr> aRes;
-  foreach (ModuleBase_ViewerPrsPtr aPrs, theList1) {
-    if (!aRes.contains(aPrs))
-      aRes.append(aPrs);
-  }
-  foreach (ModuleBase_ViewerPrsPtr aPrs, theList2) {
-    if (!aRes.contains(aPrs))
-      aRes.append(aPrs);
-  }
-  return aRes;
-}*/
-
-// Fills the list of features the list of selected presentations.
-// \param theList a list of selected presentations
-// \param theSketch a sketch to project a vertex shape of a presentation to the plane
-// and find the corresponded attribute
-// \param theFeatureList  an output list of features
-void fillFeatureList(const QList<ModuleBase_ViewerPrsPtr>& theList,
-                     const FeaturePtr theSketch,
-                     QList<FeaturePtr>& theFeatureList)
-{
-  QList<ModuleBase_ViewerPrsPtr> aRes;
-
-  QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theList.begin(),
-                                              aLast = theList.end();
-  for (; anIt != aLast; anIt++)
-  {
-    ModuleBase_ViewerPrsPtr aPrs = *anIt;
-    FeaturePtr aFeature = ModelAPI_Feature::feature(aPrs->object());
-    if (aFeature.get()  && !theFeatureList.contains(aFeature))
-      theFeatureList.append(aFeature);
-  }
-}
-
 /// Fills attribute and result lists by the selected owner. In case if the attribute is found,
-/// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge, put the function
-/// result as is to the list of results.
+/// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge,
+/// put the function result as is to the list of results.
 /// \param theOwner a viewer selected owner
 /// \param theFeature a feature, where the attribute is searched
 /// \param theSketch a current sketch
@@ -138,8 +125,9 @@ void fillFeatureList(const QList<ModuleBase_ViewerPrsPtr>& theList,
 void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
                             const FeaturePtr& theFeature, const FeaturePtr& theSketch,
                             const ResultPtr& theResult,
-                            std::set<AttributePtr>& aSelectedAttributes,
-                            std::set<ResultPtr>& aSelectedResults)
+                            std::set<AttributePtr>& theSelectedAttributes,
+                            std::set<ResultPtr>& theSelectedResults,
+                            TopTools_MapOfShape& theShapes)
 {
   Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(theOwner);
   if (aBRepOwner.IsNull())
@@ -148,25 +136,26 @@ void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
                                                                     aBRepOwner->Selectable());
   if (aBRepOwner->HasShape()) {
     const TopoDS_Shape& aShape = aBRepOwner->Shape();
+    theShapes.Add(aShape);
     TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
     if (aShapeType == TopAbs_VERTEX) {
       AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature,
                                                                     aShape, theSketch);
       if (aPntAttr.get() != NULL)
-        aSelectedAttributes.insert(aPntAttr);
+        theSelectedAttributes.insert(aPntAttr);
     }
     else if (aShapeType == TopAbs_EDGE &&
-             aSelectedResults.find(theResult) == aSelectedResults.end()) {
-      aSelectedResults.insert(theResult);
+             theSelectedResults.find(theResult) == theSelectedResults.end()) {
+      theSelectedResults.insert(theResult);
     }
   }
 }
 
 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
-  : QObject(theModule), myModule(theModule), myIsDragging(false), myDragDone(false),
-    myIsMouseOverWindow(false),
+  : QObject(theModule), myModule(theModule), myIsEditLaunching(false), myIsDragging(false),
+    myDragDone(false), myIsMouseOverWindow(false),
     myIsMouseOverViewProcessed(true), myPreviousUpdateViewerEnabled(true),
-    myIsPopupMenuActive(false)
+    myIsPopupMenuActive(false), myExternalPointsMgr(0)
 {
   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
@@ -192,6 +181,8 @@ PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
+
+  mySketchPlane = new PartSet_PreviewSketchPlane();
 }
 
 PartSet_SketcherMgr::~PartSet_SketcherMgr()
@@ -222,7 +213,7 @@ void PartSet_SketcherMgr::onEnterViewPort()
     }
   }
 
-  if (!isNestedCreateOperation(getCurrentOperation()))
+  if (!isNestedCreateOperation(getCurrentOperation(), activeSketch()))
     return;
 
   operationMgr()->onValidateOperation();
@@ -259,7 +250,7 @@ void PartSet_SketcherMgr::onLeaveViewPort()
 #endif
   }
 
-  if (!isNestedCreateOperation(getCurrentOperation()))
+  if (!isNestedCreateOperation(getCurrentOperation(), activeSketch()))
     return;
 
   // the method should be performed if the popup menu is called,
@@ -296,13 +287,15 @@ void PartSet_SketcherMgr::onLeaveViewPort()
   aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
 }
 
+/*
+//Temporary commented as we do not modify values in property panel
 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
 {
-  if (!isNestedEditOperation(getCurrentOperation()) ||
+  if (!isNestedEditOperation(getCurrentOperation(), myModule->sketchMgr()->activeSketch()) ||
       myModule->sketchReentranceMgr()->isInternalEditActive())
     return;
   // it is necessary to save current selection in order to restore it after the values are modifed
-  storeSelection();
+  storeSelection(ST_SelectAndHighlightType);
 
   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
@@ -312,16 +305,16 @@ void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
 
 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
 {
-  if (!isNestedEditOperation(getCurrentOperation()) ||
+  if (!isNestedEditOperation(getCurrentOperation(), myModule->sketchMgr()->activeSketch()) ||
       myModule->sketchReentranceMgr()->isInternalEditActive()) {
     myModule->sketchReentranceMgr()->updateInternalEditActiveState();
     return;
   }
-  // it is necessary to restore current selection in order to restore it after the values are modified
+  // it is necessary to restore current selection in order to restore it after values are modified
   restoreSelection();
   myCurrentSelection.clear();
 
-  // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
+  // 3. the flag to disable the update viewer should be set in order to avoid blinking in the
   // viewer happens by deselect/select the modified objects. The flag should be restored after
   // the selection processing. The update viewer should be also called.
   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
@@ -329,23 +322,20 @@ void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
   aDisplayer->updateViewer();
-
-
 }
+*/
 
 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
 {
+  // Clear dragging mode
+  myIsDragging = false;
+
   if (myModule->sketchReentranceMgr()->processMousePressed(theWnd, theEvent))
     return;
-
   //get2dPoint(theWnd, theEvent, myClickedPoint);
-
   if (!(theEvent->buttons() & Qt::LeftButton))
     return;
 
-  // Clear dragging mode
-  myIsDragging = false;
-
   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
   if (!aViewer->canDragByMouse())
@@ -383,15 +373,11 @@ void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseE
       return;
 
     Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
-    if (!aContext.IsNull()) {
-      // MoveTo in order to highlight current object
-      aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
-    }
     // Remember highlighted objects for editing
     ModuleBase_ISelection* aSelect = aWorkshop->selection();
 
     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
-    storeSelection(!aHasShift);
+    storeSelection(aHasShift ? ST_SelectAndHighlightType : ST_HighlightType, myCurrentSelection);
 
     if (myCurrentSelection.empty()) {
       if (isSketchOpe && (!isSketcher))
@@ -403,50 +389,71 @@ void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseE
     // Init flyout point for radius rotation
     FeaturePtr aFeature = myCurrentSelection.begin().key();
 
+    get2dPoint(theWnd, theEvent, myCurrentPoint);
     if (isSketcher) {
       myIsDragging = true;
-      get2dPoint(theWnd, theEvent, myCurrentPoint);
       myDragDone = false;
 
       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
       launchEditing();
       if (aFeature.get() != NULL) {
-        std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
+        std::shared_ptr<SketchPlugin_Feature> aSPFeature =
                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
-      if (aSPFeature.get() && aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID()) {
+        if (aSPFeature.get() &&
+          (aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID() ||
+           aSPFeature->getKind() == SketchPlugin_ConstraintAngle::ID())) {
           DataPtr aData = aSPFeature->data();
           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
-          std::shared_ptr<GeomDataAPI_Point2D> aFPAttr = 
+          std::shared_ptr<GeomDataAPI_Point2D> aFPAttr =
             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
         }
       }
     } else if (isSketchOpe && isEditing) {
       // If selected another object commit current result
+      bool aPrevLaunchingState = myIsEditLaunching;
+      /// store editing state for Edit operation in order to do not clear highlight by restart
+      /// of edit operation.
+      /// Internal edit should not be stored as editing operation as the result will be a
+      /// creation operation, where previous selection should not be used(and will be cleared)
+      myIsEditLaunching = !myModule->sketchReentranceMgr()->isInternalEditActive();
       aFOperation->commit();
 
       myIsDragging = true;
-      get2dPoint(theWnd, theEvent, myCurrentPoint);
       myDragDone = false;
 
       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
-
-      // this is temporary commented in order to avoid the following wrong case:
-      // Distance constraint is under edition, double click on the digit -> nothing happens
-      // because QApplication::processEvents() calls onMouseDoubleClick, which try to show editor
-      // but as the prev edit is commited an new one is not started, editor is not shown.
-      // This is necessary in order to finalize previous operation
-      //QApplication::processEvents();
       launchEditing();
+      myIsEditLaunching = aPrevLaunchingState;
+      if (aFeature.get() != NULL) {
+        std::shared_ptr<SketchPlugin_Feature> aSPFeature =
+                  std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
+        if (aSPFeature.get() &&
+          (aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID() ||
+           aSPFeature->getKind() == SketchPlugin_ConstraintAngle::ID())) {
+          DataPtr aData = aSPFeature->data();
+          AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
+          std::shared_ptr<GeomDataAPI_Point2D> aFPAttr =
+            std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
+          aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
+        }
+      }
     }
   }
 }
 
 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
 {
+  bool aWasDragging = myIsDragging;
+  myIsDragging = false;
+
   if (myModule->sketchReentranceMgr()->processMouseReleased(theWnd, theEvent))
     return;
 
+  // if mouse is pressed when it was over view and at release the mouse is out of view, do nothing
+  if (!myIsMouseOverViewProcessed)
+    return;
+
   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
   if (!aViewer->canDragByMouse())
@@ -454,65 +461,72 @@ void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouse
   ModuleBase_Operation* aOp = getCurrentOperation();
   if (aOp) {
     if (isNestedSketchOperation(aOp)) {
-      //get2dPoint(theWnd, theEvent, myClickedPoint);
-
       // Only for sketcher operations
-      if (myIsDragging) {
+      if (aWasDragging) {
         if (myDragDone) {
-          //aOp->commit();
+          /// the previous selection is lost by mouse release in the viewer(Select method), but
+          /// it is still stored in myCurrentSelection. So, it is possible to restore selection
+          /// It is important for drag(edit with mouse) of sketch entities.
+          restoreSelection(myCurrentSelection);
           myCurrentSelection.clear();
-          /*Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
-          if (!aContext.IsNull()) {
-          // Reselect edited object
-          aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
-          if (theEvent->modifiers() & Qt::ShiftModifier)
-            aContext->ShiftSelect();
-          else
-            aContext->Select();
-          */
         }
       }
     }
   }
 
   aWorkshop->viewer()->enableDrawMode(myPreviousDrawModeEnabled);
-  myIsDragging = false;
+
+  ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
+  PartSet_MouseProcessor* aProcessor = dynamic_cast<PartSet_MouseProcessor*>(anActiveWidget);
+  if (aProcessor)
+    aProcessor->mouseReleased(theWnd, theEvent);
 }
 
 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
 {
+#ifdef DEBUG_SKETCH_ENTITIES_ON_MOVE
+  CompositeFeaturePtr aSketch = activeSketch();
+  if (aSketch.get()) {
+    std::cout << "mouse move SKETCH FEATURES [" << aSketch->numberOfSubs() << "]:" << std::endl;
+    QStringList anInfo;
+    for (int i = 0, aNbSubs = aSketch->numberOfSubs(); i < aNbSubs; i++) {
+      //std::cout << getFeatureInfo(aSketch->subFeature(i), false) << std::endl;
+      anInfo.append(ModuleBase_Tools::objectInfo(aSketch->subFeature(i)));
+    }
+    QString anInfoStr = anInfo.join("\n");
+    qDebug(QString("%1").arg(anInfo.size()).arg(anInfoStr).toStdString().c_str());
+  }
+#endif
+
   if (myModule->sketchReentranceMgr()->processMouseMoved(theWnd, theEvent))
     return;
 
-  if (isNestedCreateOperation(getCurrentOperation()) && !myIsMouseOverViewProcessed) {
-    myIsMouseOverViewProcessed = true;
+  if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
     // 1. perform the widget mouse move functionality and display the presentation
     // the mouse move should be processed in the widget, if it can in order to visualize correct
     // presentation. These widgets correct the feature attribute according to the mouse position
-    ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
-    PartSet_WidgetPoint2D* aPoint2DWdg = dynamic_cast<PartSet_WidgetPoint2D*>(anActiveWidget);
-    if (aPoint2DWdg) {
-      aPoint2DWdg->onMouseMove(theWnd, theEvent);
-    }
-    PartSet_WidgetPoint2dDistance* aDistanceWdg = dynamic_cast<PartSet_WidgetPoint2dDistance*>
-                                                                (anActiveWidget);
-    if (aDistanceWdg) {
-      aDistanceWdg->onMouseMove(theWnd, theEvent);
-    }
-    // the feature is to be erased here, but it is correct to call canDisplayObject because
-    // there can be additional check (e.g. editor widget in distance constraint)
-    ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
-                                                                             (getCurrentOperation());
-    if (aFOperation) {
-      FeaturePtr aFeature = aFOperation->feature();
-      visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
+    ModuleBase_ModelWidget* anActiveWidget = myModule->activeWidget();
+    PartSet_MouseProcessor* aProcessor = dynamic_cast<PartSet_MouseProcessor*>(anActiveWidget);
+    if (aProcessor)
+      aProcessor->mouseMoved(theWnd, theEvent);
+    if (!myIsMouseOverViewProcessed) {
+      myIsMouseOverViewProcessed = true;
+
+      // the feature is to be erased here, but it is correct to call canDisplayObject because
+      // there can be additional check (e.g. editor widget in distance constraint)
+      ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
+                                                 (getCurrentOperation());
+      if (aFOperation) {
+        FeaturePtr aFeature = aFOperation->feature();
+        visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
+      }
     }
   }
-
   //myClickedPoint.clear();
 
   if (myIsDragging) {
-    // 1. the current selection is saved in the mouse press method in order to restore it after moving
+    // 1. the current selection is saved in the mouse press method in order to restore it after
+    //    moving
     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
     // deselected). This flag should be restored in the slot, processed the mouse release signal.
@@ -525,15 +539,18 @@ void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEve
 
     Handle(V3d_View) aView = theWnd->v3dView();
     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
-    double aX, aY;
-    PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, aY);
-    double dX =  aX - myCurrentPoint.myCurX;
-    double dY =  aY - myCurrentPoint.myCurY;
+    Point aMousePnt;
+    get2dPoint(theWnd, theEvent, aMousePnt);
+
+    std::shared_ptr<GeomAPI_Pnt2d> anOriginalPosition = std::shared_ptr<GeomAPI_Pnt2d>(
+                            new GeomAPI_Pnt2d(myCurrentPoint.myCurX, myCurrentPoint.myCurY));
+    std::shared_ptr<GeomAPI_Pnt2d> aCurrentPosition = std::shared_ptr<GeomAPI_Pnt2d>(
+                            new GeomAPI_Pnt2d(aMousePnt.myCurX, aMousePnt.myCurY));
 
     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
-    // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
+    // 3. the flag to disable the update viewer should be set in order to avoid blinking in the
     // viewer happens by deselect/select the modified objects. The flag should be restored after
     // the selection processing. The update viewer should be also called.
     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
@@ -547,7 +564,7 @@ void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEve
     for (; anIt != aLast; anIt++) {
       FeaturePtr aFeature = anIt.key();
 
-      std::set<AttributePtr> anAttributes = anIt.value().first;
+      std::set<AttributePtr> anAttributes = anIt.value().myAttributes;
       // Process selection by attribute: the priority to the attribute
       if (!anAttributes.empty()) {
         std::set<AttributePtr>::const_iterator anAttIt = anAttributes.begin(),
@@ -559,13 +576,19 @@ void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEve
           std::string aAttrId = anAttr->id();
           DataPtr aData = aFeature->data();
           if (aData->isValid()) {
-            std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
+            std::shared_ptr<GeomDataAPI_Point2D> aPoint =
               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
             if (aPoint.get() != NULL) {
               bool isImmutable = aPoint->setImmutable(true);
-              aPoint->move(dX, dY);
+
+              std::shared_ptr<ModelAPI_ObjectMovedMessage> aMessage = std::shared_ptr
+                       <ModelAPI_ObjectMovedMessage>(new ModelAPI_ObjectMovedMessage(this));
+              aMessage->setMovedAttribute(aPoint);
+              aMessage->setOriginalPosition(anOriginalPosition);
+              aMessage->setCurrentPosition(aCurrentPosition);
+              Events_Loop::loop()->send(aMessage);
+
               isModified = true;
-              ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
               aPoint->setImmutable(isImmutable);
             }
           }
@@ -575,9 +598,13 @@ void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEve
         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
         if (aSketchFeature) {
-          aSketchFeature->move(dX, dY);
+          std::shared_ptr<ModelAPI_ObjectMovedMessage> aMessage = std::shared_ptr
+                    <ModelAPI_ObjectMovedMessage>(new ModelAPI_ObjectMovedMessage(this));
+          aMessage->setMovedObject(aFeature);
+          aMessage->setOriginalPosition(anOriginalPosition);
+          aMessage->setCurrentPosition(aCurrentPosition);
+          Events_Loop::loop()->send(aMessage);
           isModified = true;
-          ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
         }
       }
     }
@@ -585,18 +612,18 @@ void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEve
     // were changed here
     if (isModified) {
       aCurrentOperation->onValuesChanged();
+      Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
     }
-    Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
 
     // 5. it is necessary to save current selection in order to restore it after the features moving
-    restoreSelection();
+    restoreSelection(myCurrentSelection);
     // 6. restore the update viewer flag and call this update
     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
     aDisplayer->updateViewer();
 
     myDragDone = true;
-    myCurrentPoint.setValue(aX, aY);
+    myCurrentPoint = aMousePnt;
   }
 }
 
@@ -613,7 +640,8 @@ void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMo
       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
       // Find corresponded widget to activate value editing
       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
-        if (aWgt->attributeID() == "ConstraintValue") {
+        if (aWgt->attributeID() == SketchPlugin_Constraint::VALUE() ||
+            aWgt->attributeID() == SketchPlugin_ConstraintAngle::ANGLE_VALUE_ID()) {
           PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
           if (anEditor)
             anEditor->showPopupEditor();
@@ -629,7 +657,7 @@ void PartSet_SketcherMgr::onApplicationStarted()
   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
   XGUI_Workshop* aWorkshop = aConnector->workshop();
-  PartSet_SketcherReetntrantMgr* aReentranceMgr = myModule->sketchReentranceMgr();
+  PartSet_SketcherReentrantMgr* aReentranceMgr = myModule->sketchReentranceMgr();
 
   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
   if (aPropertyPanel) {
@@ -679,7 +707,7 @@ void PartSet_SketcherMgr::onAfterContextMenu()
   myIsPopupMenuActive = false;
 }
 
-void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent, 
+void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent,
                                      Point& thePoint)
 {
   Handle(V3d_View) aView = theWnd->v3dView();
@@ -693,10 +721,17 @@ void PartSet_SketcherMgr::launchEditing()
 {
   if (!myCurrentSelection.empty()) {
     FeaturePtr aFeature = myCurrentSelection.begin().key();
-    std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
+    std::shared_ptr<SketchPlugin_Feature> aSPFeature =
               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
     if (aSPFeature) {
-      myModule->editFeature(aSPFeature);
+      if (!aSPFeature->isExternal())
+        myModule->editFeature(aSPFeature);
+      else {
+        FeaturePtr aProjectionFeature = PartSet_Tools::findRefsToMeFeature(aFeature,
+                                                        SketchPlugin_Projection::ID());
+        if (aProjectionFeature.get())
+          myModule->editFeature(aProjectionFeature);
+      }
     }
   }
 }
@@ -714,14 +749,14 @@ bool PartSet_SketcherMgr::sketchSolverError()
 
 QString PartSet_SketcherMgr::getFeatureError(const FeaturePtr& theFeature)
 {
-  QString anError = "";
+  QString anError;
   if (!theFeature.get() || !theFeature->data()->isValid())
     return anError;
 
   CompositeFeaturePtr aSketch = activeSketch();
   if (aSketch.get() && aSketch == theFeature) {
-    AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
-    anError = aAttributeString->value().c_str();
+    std::string aSolverError = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR())->value();
+    anError = ModuleBase_Tools::translate(aSketch->getKind(), aSolverError);
   }
   return anError;
 }
@@ -732,47 +767,40 @@ void PartSet_SketcherMgr::clearClickedFlags()
   myCurrentPoint.clear();
 }
 
-const QStringList& PartSet_SketcherMgr::sketchOperationIdList()
-{
-  static QStringList aIds;
-  if (aIds.size() == 0) {
-    aIds << SketchPlugin_Line::ID().c_str();
-    aIds << SketchPlugin_Point::ID().c_str();
-    aIds << SketchPlugin_Arc::ID().c_str();
-    aIds << SketchPlugin_Circle::ID().c_str();
-    aIds << SketchPlugin_ConstraintFillet::ID().c_str();
-    aIds << SketchPlugin_IntersectionPoint::ID().c_str();
-    // TODO
-    // SketchRectangle is a python feature, so its ID is passed just as a string
-    aIds << "SketchRectangle";
-    aIds.append(constraintsIdList());
+const QStringList& PartSet_SketcherMgr::replicationsIdList()
+{
+  static QStringList aReplicationIds;
+  if (aReplicationIds.size() == 0) {
+    aReplicationIds << SketchPlugin_ConstraintMirror::ID().c_str();
+    aReplicationIds << SketchPlugin_MultiRotation::ID().c_str();
+    aReplicationIds << SketchPlugin_MultiTranslation::ID().c_str();
   }
-  return aIds;
+  return aReplicationIds;
 }
 
 const QStringList& PartSet_SketcherMgr::constraintsIdList()
 {
-  static QStringList aIds;
-  if (aIds.size() == 0) {
-    aIds << SketchPlugin_ConstraintLength::ID().c_str();
-    aIds << SketchPlugin_ConstraintDistance::ID().c_str();
-    aIds << SketchPlugin_ConstraintRigid::ID().c_str();
-    aIds << SketchPlugin_ConstraintRadius::ID().c_str();
-    aIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
-    aIds << SketchPlugin_ConstraintParallel::ID().c_str();
-    aIds << SketchPlugin_ConstraintHorizontal::ID().c_str();
-    aIds << SketchPlugin_ConstraintVertical::ID().c_str();
-    aIds << SketchPlugin_ConstraintEqual::ID().c_str();
-    aIds << SketchPlugin_ConstraintTangent::ID().c_str();
-    aIds << SketchPlugin_ConstraintCoincidence::ID().c_str();
-    aIds << SketchPlugin_ConstraintMirror::ID().c_str();
-    aIds << SketchPlugin_ConstraintAngle::ID().c_str();
-    aIds << SketchPlugin_MultiRotation::ID().c_str();
-    aIds << SketchPlugin_MultiTranslation::ID().c_str();
-    aIds << SketchPlugin_ConstraintCollinear::ID().c_str();
-    aIds << SketchPlugin_ConstraintMiddle::ID().c_str();
+  static QStringList aConstraintIds;
+  if (aConstraintIds.size() == 0) {
+    aConstraintIds << SketchPlugin_ConstraintLength::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintDistance::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintRigid::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintRadius::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintParallel::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintHorizontal::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintVertical::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintEqual::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintTangent::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintCoincidence::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintAngle::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintCollinear::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintMiddle::ID().c_str();
+    aConstraintIds << SketchPlugin_ConstraintMirror::ID().c_str();
+    aConstraintIds << SketchPlugin_MultiTranslation::ID().c_str();
+    aConstraintIds << SketchPlugin_MultiRotation::ID().c_str();
   }
-  return aIds;
+  return aConstraintIds;
 }
 
 void PartSet_SketcherMgr::sketchSelectionModes(QIntList& theModes)
@@ -802,24 +830,59 @@ bool PartSet_SketcherMgr::isSketchOperation(ModuleBase_Operation* theOperation)
   return theOperation && theOperation->id().toStdString() == SketchPlugin_Sketch::ID();
 }
 
-bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation)
+bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation) const
+{
+  bool aNestedSketch = false;
+
+  FeaturePtr anActiveSketch = activeSketch();
+  if (anActiveSketch.get() && theOperation) {
+    ModuleBase_Operation* aSketchOperation = operationMgr()->findOperation(
+                                                              anActiveSketch->getKind().c_str());
+    ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
+                                                                                  (theOperation);
+    if (aSketchOperation && aFOperation) {
+      FeaturePtr aFeature = aFOperation->feature();
+      if (aFeature.get()) {
+        QStringList aGrantedOpIds = aSketchOperation->grantedOperationIds();
+        aNestedSketch = aGrantedOpIds.contains(aFeature->getKind().c_str());
+      }
+    }
+  }
+  return aNestedSketch;
+}
+
+bool PartSet_SketcherMgr::isNestedSketchFeature(const QString& theFeatureKind) const
 {
-  return theOperation &&
-         PartSet_SketcherMgr::sketchOperationIdList().contains(theOperation->id());
+  bool aNestedSketch = false;
+
+  FeaturePtr anActiveSketch = activeSketch();
+  if (anActiveSketch.get()) {
+    ModuleBase_Operation* aSketchOperation = operationMgr()->findOperation(
+                                                              anActiveSketch->getKind().c_str());
+    if (aSketchOperation) {
+      QStringList aGrantedOpIds = aSketchOperation->grantedOperationIds();
+      aNestedSketch = aGrantedOpIds.contains(theFeatureKind);
+    }
+  }
+  return aNestedSketch;
 }
 
-bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation)
+bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation,
+                                                  const CompositeFeaturePtr& theSketch) const
 {
   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
                                                                (theOperation);
-  return aFOperation && !aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
+  return aFOperation && !aFOperation->isEditOperation() &&
+         isNestedSketchOperation(aFOperation);
 }
 
-bool PartSet_SketcherMgr::isNestedEditOperation(ModuleBase_Operation* theOperation)
+bool PartSet_SketcherMgr::isNestedEditOperation(ModuleBase_Operation* theOperation,
+                                                const CompositeFeaturePtr& theSketch) const
 {
   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
                                                                (theOperation);
-  return aFOperation && aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
+  return aFOperation && aFOperation->isEditOperation() &&
+    isNestedSketchOperation(aFOperation);
 }
 
 bool PartSet_SketcherMgr::isEntity(const std::string& theId)
@@ -830,6 +893,13 @@ bool PartSet_SketcherMgr::isEntity(const std::string& theId)
          (theId == SketchPlugin_Circle::ID());
 }
 
+bool PartSet_SketcherMgr::isExternalFeature(const FeaturePtr& theFeature)
+{
+  std::shared_ptr<SketchPlugin_Feature> aSPFeature =
+          std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
+  return aSPFeature.get() && aSPFeature->isExternal();
+}
+
 bool PartSet_SketcherMgr::isDistanceOperation(ModuleBase_Operation* theOperation)
 {
   std::string anId = theOperation ? theOperation->id().toStdString() : "";
@@ -856,8 +926,8 @@ void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
 
   // Display all sketcher sub-Objects
   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFOperation->feature());
+  mySketchPlane->createSketchPlane(myCurrentSketch, myModule->workshop());
   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
-  aConnector->workshop()->displayer()->activateTrihedron(true);
 
   // Hide sketcher result
   std::list<ResultPtr> aResults = myCurrentSketch->results();
@@ -867,16 +937,73 @@ void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
   }
   myCurrentSketch->setDisplayed(false);
 
+  // Remove invalid sketch entities
+  std::set<FeaturePtr> anInvalidFeatures;
+  ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
+  for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
+    FeaturePtr aFeature = myCurrentSketch->subFeature(i);
+    if (aFeature.get()) {
+      if (!aFactory->validate(aFeature))
+        anInvalidFeatures.insert(aFeature);
+    }
+  }
+  if (!anInvalidFeatures.empty()) {
+    std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
+    ModelAPI_Tools::findAllReferences(anInvalidFeatures, aReferences, false);
+
+    std::set<FeaturePtr>::const_iterator anIt = anInvalidFeatures.begin(),
+                                         aLast = anInvalidFeatures.end();
+    // separate features to references to parameter features and references to others
+    QStringList anInvalidFeatureNames;
+    for (; anIt != aLast; anIt++) {
+      FeaturePtr aFeature = *anIt;
+      if (aFeature.get())
+        anInvalidFeatureNames.append(aFeature->name().c_str());
+    }
+    std::string aPrefixInfo = QString("Invalid features of the sketch will be deleted: %1.\n\n").
+                                  arg(anInvalidFeatureNames.join(", ")).toStdString().c_str();
+    std::set<FeaturePtr> aFeatureRefsToDelete;
+    if (ModuleBase_Tools::askToDelete(anInvalidFeatures, aReferences, aConnector->desktop(),
+                                      aFeatureRefsToDelete, aPrefixInfo)) {
+      if (!aFeatureRefsToDelete.empty())
+        anInvalidFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
+      ModelAPI_Tools::removeFeatures(anInvalidFeatures, true);
+      Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
+      // TODO: call the next method in the XGUI_OperationMgr::onOperationStarted().
+      workshop()->errorMgr()->updateAcceptAllAction(myCurrentSketch);
+    }
+  }
+
+  // update state of overconstraint listener should be done before sketch features/results
+  // display (as the display will ask custom color from the listener)
+  myModule->overconstraintListener()->setActive(true);
   // Display sketcher objects
+  QStringList anInfo;
+  Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
+  const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
+#ifdef DEBUG_SKETCHER_ENTITIES
+    anInfo.append(ModuleBase_Tools::objectInfo(aFeature));
+#endif
     std::list<ResultPtr> aResults = aFeature->results();
     std::list<ResultPtr>::const_iterator aIt;
     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
-      (*aIt)->setDisplayed(true);
+      if ((*aIt)->isDisplayed())
+        // Display object if it was created outside of GUI
+        aECreator->sendUpdated((*aIt), EVENT_DISP);
+      else
+        (*aIt)->setDisplayed(true);
     }
-    aFeature->setDisplayed(true);
+    if (aFeature->isDisplayed())
+      aECreator->sendUpdated(aFeature, EVENT_DISP);
+    else
+      aFeature->setDisplayed(true);
   }
+#ifdef DEBUG_SKETCHER_ENTITIES
+  QString anInfoStr = anInfo.join(";\t");
+  qDebug(QString("startSketch: %1, %2").arg(anInfo.size()).arg(anInfoStr).toStdString().c_str());
+#endif
 
   if(myCirclePointFilter.IsNull()) {
     myCirclePointFilter = new PartSet_CirclePointFilter(myModule->workshop());
@@ -884,7 +1011,7 @@ void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
 
   myModule->workshop()->viewer()->addSelectionFilter(myCirclePointFilter);
 
-  if (myPlaneFilter.IsNull()) 
+  if (myPlaneFilter.IsNull())
     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
 
   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
@@ -898,6 +1025,8 @@ void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
   // plane filter
   if (aPln.get())
     aConnector->activateModuleSelectionModes();
+
+  myExternalPointsMgr = new PartSet_ExternalPointsMgr(myModule->workshop(), myCurrentSketch);
 }
 
 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
@@ -907,6 +1036,11 @@ void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
 
+  if (myExternalPointsMgr) {
+    delete myExternalPointsMgr;
+    myExternalPointsMgr = 0;
+  }
+
   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
 
   DataPtr aData = myCurrentSketch->data();
@@ -914,12 +1048,12 @@ void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
     // The sketch was aborted
     myCurrentSketch = CompositeFeaturePtr();
+    mySketchPlane->eraseSketchPlane(myModule->workshop());
     // TODO: move this outside of if-else
     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
 
     // Erase all sketcher objects
-    QStringList aSketchIds = sketchOperationIdList();
     QObjectPtrList aObjects = aDisplayer->displayedObjects();
     foreach (ObjectPtr aObj, aObjects) {
       DataPtr aObjData = aObj->data();
@@ -956,8 +1090,9 @@ void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
     }
     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
       myCurrentSketch->setDisplayed(true);
-    
+
     myCurrentSketch = CompositeFeaturePtr();
+    mySketchPlane->eraseSketchPlane(myModule->workshop());
 
     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
@@ -966,7 +1101,6 @@ void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
   }
   // restore the module selection modes, which were changed on startSketch
   aConnector->activateModuleSelectionModes();
-  aConnector->workshop()->displayer()->activateTrihedron(false);
 }
 
 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
@@ -984,19 +1118,36 @@ void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
 
 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
 {
+  previewSketchPlane()->updatePlaneSize(activeSketch(), myModule->workshop());
   myIsMouseOverViewProcessed = true;
   operationMgr()->onValidateOperation();
-  if (canChangeCursor(theOperation)) {
+  // when sketch nested operation is stopped the cursor should be restored unconditionally
+  //if (canChangeCursor(theOperation)) {
     QApplication::restoreOverrideCursor();
 #ifdef DEBUG_CURSOR
     qDebug("stopNestedSketch() : None");
 #endif
+  //}
+  /// improvement to deselect automatically all eventual selected objects, when
+  // returning to the neutral point of the Sketcher
+  bool isClearSelectionPossible = true;
+  if (myIsEditLaunching) {
+    ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
+                                                                          (theOperation);
+    if (aFOperation) {
+      FeaturePtr aFeature = aFOperation->feature();
+      if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
+        isClearSelectionPossible = false;
+      }
+    }
   }
+  if (isClearSelectionPossible)
+    workshop()->selector()->clearSelection();
 }
 
 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
 {
-  if (isNestedCreateOperation(theOperation)) {
+  if (isNestedCreateOperation(theOperation, activeSketch())) {
     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
                                                                              (theOperation);
     if (aFOperation) {
@@ -1022,7 +1173,7 @@ bool PartSet_SketcherMgr::operationActivatedByPreselection()
 {
   bool isOperationStopped = false;
   ModuleBase_Operation* anOperation = getCurrentOperation();
-  if(anOperation && PartSet_SketcherMgr::isNestedSketchOperation(anOperation)) {
+  if(anOperation && isNestedSketchOperation(anOperation)) {
     // Set final definitions if they are necessary
     //propertyPanelDefined(aOperation);
     /// Commit sketcher operations automatically
@@ -1031,8 +1182,12 @@ bool PartSet_SketcherMgr::operationActivatedByPreselection()
     bool aCanCommitOperation = true;
     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
                                                                             (anOperation);
-    if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation))
-      aCanCommitOperation = setDistanceValueByPreselection(anOperation, myModule->workshop());
+    if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation)) {
+      bool aValueAccepted = setDistanceValueByPreselection(anOperation, myModule->workshop(),
+                                                           aCanCommitOperation);
+      if (!aValueAccepted)
+        return isOperationStopped;
+    }
 
     if (aCanCommitOperation)
       isOperationStopped = anOperation->commit();
@@ -1046,12 +1201,12 @@ bool PartSet_SketcherMgr::operationActivatedByPreselection()
 
 bool PartSet_SketcherMgr::canUndo() const
 {
-  return isNestedCreateOperation(getCurrentOperation());
+  return isNestedCreateOperation(getCurrentOperation(), activeSketch());
 }
 
 bool PartSet_SketcherMgr::canRedo() const
 {
-  return isNestedCreateOperation(getCurrentOperation());
+  return isNestedCreateOperation(getCurrentOperation(), activeSketch());
 }
 
 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
@@ -1059,19 +1214,7 @@ bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
   bool aCanErase = true;
   // when the sketch operation is active, results of sketch sub-feature can not be hidden
   if (myCurrentSketch.get()) {
-    ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
-    if (aResult.get()) {
-      // Display sketcher objects
-      for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
-
-        FeaturePtr aFeature = myCurrentSketch->subFeature(i);
-        std::list<ResultPtr> aResults = aFeature->results();
-        std::list<ResultPtr>::const_iterator anIt;
-        for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
-          aCanErase = *anIt != aResult;
-        }
-      }
-    }
+    return !isObjectOfSketch(theObject);
   }
   return aCanErase;
 }
@@ -1083,12 +1226,17 @@ bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
   bool aHasActiveSketch = activeSketch().get() != NULL;
   if (aHasActiveSketch) {
     // 1. the sketch feature should not be displayed during the sketch active operation
-    // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch 
+    // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch
     // nested features can be visualized
     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
     if (aFeature.get() != NULL && aFeature == activeSketch()) {
       aCanDisplay = false;
     }
+    std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
+                            std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
+    /// some sketch entities should be never shown, e.g. projection feature
+    if (aSketchFeature.get())
+      aCanDisplay = aSketchFeature->canBeDisplayed();
   }
   else { // there are no an active sketch
     // 2. sketch sub-features should not be visualized if the sketch operation is not active
@@ -1104,43 +1252,47 @@ bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
 
   // 3. the method should not filter the objects, which are not related to the current operation.
   // The object is filtered just if it is a current operation feature or this feature result
-  bool isObjectFound = false;
-  ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
-                                                               (getCurrentOperation());
-  if (aFOperation) {
-    FeaturePtr aFeature = aFOperation->feature();
-    if (aFeature.get()) {
-      std::list<ResultPtr> aResults = aFeature->results();
-      if (theObject == aFeature)
-        isObjectFound = true;
-      else {
-        std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
-        for (; anIt != aLast && !isObjectFound; anIt++) {
-          isObjectFound = *anIt == theObject;
+  if (aCanDisplay) {
+    bool isObjectFound = false;
+    ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
+                                                                 (getCurrentOperation());
+    if (aFOperation) {
+      FeaturePtr aFeature = aFOperation->feature();
+      if (aFeature.get()) {
+        std::list<ResultPtr> aResults = aFeature->results();
+        if (theObject == aFeature)
+          isObjectFound = true;
+        else {
+          std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
+          for (; anIt != aLast && !isObjectFound; anIt++) {
+            isObjectFound = *anIt == theObject;
+          }
         }
       }
     }
-  }
-  if (isObjectFound) {
-    // 4. For created nested feature operation do not display the created feature if
-    // the mouse curstor leaves the OCC window.
-    // The correction cases, which ignores this condition:
-    // a. the property panel values modification
-    // b. the popup menu activated
-    // c. widget editor control
-    #ifndef DEBUG_DO_NOT_BY_ENTER
-    if (aCanDisplay && isNestedCreateOperation(getCurrentOperation())) {
-      ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
-      ModuleBase_WidgetEditor* anEditorWdg = anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
-      // the active widget editor should not influence here. The presentation should be visible always
-      // when this widget is active.
-      if (!anEditorWdg && !myIsPopupMenuActive) {
-        // during a nested create operation, the feature is redisplayed only if the mouse over view
-        // of there was a value modified in the property panel after the mouse left the view
-        aCanDisplay = canDisplayCurrentCreatedFeature();
+    if (isObjectFound) {
+      // 4. For created nested feature operation do not display the created feature if
+      // the mouse curstor leaves the OCC window.
+      // The correction cases, which ignores this condition:
+      // a. the property panel values modification
+      // b. the popup menu activated
+      // c. widget editor control
+      #ifndef DEBUG_DO_NOT_BY_ENTER
+      if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
+        ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
+        ModuleBase_WidgetEditor* anEditorWdg =
+          anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
+        // the active widget editor should not influence here. The presentation should be visible
+        // always when this widget is active.
+        if (!anEditorWdg && !myIsPopupMenuActive) {
+          // during a nested create operation, the feature is redisplayed only
+          // if the mouse over view
+          // of there was a value modified in the property panel after the mouse left the view
+          aCanDisplay = canDisplayCurrentCreatedFeature();
+        }
       }
+      #endif
     }
-    #endif
   }
 
   // checks the sketcher constraints visibility according to active sketch check box states
@@ -1202,7 +1354,7 @@ bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
   return aSwitchedOn;
 }
 
-void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
+/*void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
 {
   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
                                                                            (getCurrentOperation());
@@ -1278,7 +1430,7 @@ will be hidden: %1. Would you like to delete them?")
       }
     }
   }
-}
+}*/
 
 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
 {
@@ -1293,7 +1445,7 @@ bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
 
 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
 {
-  return isNestedCreateOperation(theOperation) ||
+  return isNestedCreateOperation(theOperation, activeSketch()) ||
          myModule->sketchReentranceMgr()->isInternalEditActive();
 }
 
@@ -1319,16 +1471,18 @@ bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
 
 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
 {
-  if (myPlaneFilter.IsNull()) 
+  if (myPlaneFilter.IsNull())
    myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
 
   myPlaneFilter->setPlane(thePln);
 }
 
 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
-                                                         ModuleBase_IWorkshop* theWorkshop)
+                                                         ModuleBase_IWorkshop* theWorkshop,
+                                                         bool& theCanCommitOperation)
 {
   bool isValueAccepted = false;
+  theCanCommitOperation = false;
 
   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
                                                                               (theOperation);
@@ -1390,6 +1544,7 @@ bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* t
             }
             anEditor->setCursorPosition(aX, anY);
             isValueAccepted = anEditor->showPopupEditor(false);
+            theCanCommitOperation = true;
           }
         }
       }
@@ -1398,54 +1553,6 @@ bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* t
   return isValueAccepted;
 }
 
-void PartSet_SketcherMgr::getCurrentSelection(const FeaturePtr& theFeature,
-                                              const FeaturePtr& theSketch,
-                                              ModuleBase_IWorkshop* theWorkshop,
-                                              FeatureToSelectionMap& theSelection)
-{
-  if (theFeature.get() == NULL)
-    return;
-
-  std::set<AttributePtr> aSelectedAttributes;
-  std::set<ResultPtr> aSelectedResults;
-
-  ModuleBase_IViewer* aViewer = theWorkshop->viewer();
-  Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
-  if (!aContext.IsNull()) {
-    XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
-    XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
-
-    std::list<ResultPtr> aResults = theFeature->results();
-    std::list<ResultPtr>::const_iterator aIt;
-    for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
-    {
-      ResultPtr aResult = *aIt;
-      AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
-      if (aAISObj.get() == NULL)
-        continue;
-      Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
-      for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
-      {
-        Handle(SelectMgr_EntityOwner) anOwner = aContext->SelectedOwner();
-        if (anOwner->Selectable() != anAISIO)
-          continue;
-        getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
-                               aSelectedAttributes, aSelectedResults);
-      }
-      for (aContext->InitDetected(); aContext->MoreDetected(); aContext->NextDetected()) {
-        Handle(SelectMgr_EntityOwner) anOwner = aContext->DetectedOwner();
-        if (anOwner.IsNull())
-          continue;
-        if (anOwner->Selectable() != anAISIO)
-          continue;
-        getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
-                               aSelectedAttributes, aSelectedResults);
-      }
-    }
-  }
-  theSelection[theFeature] = std::make_pair(aSelectedAttributes, aSelectedResults);
-}
-
 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
                                              const FeaturePtr& theSketch,
                                              ModuleBase_IWorkshop* theWorkshop,
@@ -1456,8 +1563,9 @@ void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
     return;
 
   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
-  std::set<AttributePtr> aSelectedAttributes = anIt.value().first;
-  std::set<ResultPtr> aSelectedResults = anIt.value().second;
+  SelectionInfo anInfo = anIt.value();
+  std::set<AttributePtr> aSelectedAttributes = anInfo.myAttributes;
+  std::set<ResultPtr> aSelectedResults = anInfo.myResults;
 
   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
 
@@ -1481,52 +1589,88 @@ void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
   // 2. found the feature results's owners
   std::list<ResultPtr> aResults = theFeature->results();
   std::list<ResultPtr>::const_iterator aIt;
-  for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
-  {
+
+  bool isSameShape = false;
+  if (aResults.size() > 0) {
+    ResultPtr aFirstResult = theFeature->firstResult();
+    if (aFirstResult.get() && aFirstResult->shape().get()) {
+      TopoDS_Shape aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
+      isSameShape = aFirstShape.IsEqual(anInfo.myFirstResultShape);
+    }
+  }
+  for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
     ResultPtr aResult = *aIt;
     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
     if (aAISObj.get() == NULL)
-      continue; 
+      continue;
     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
 
-    SelectMgr_IndexedMapOfOwner aSelectedOwners;  
+    SelectMgr_IndexedMapOfOwner aSelectedOwners;
     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
+    bool aFoundLocalShape = false;
     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
-      Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
-      if ( anOwner.IsNull() || !anOwner->HasShape() )
+      Handle(StdSelect_BRepOwner) anOwner =
+        Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
+      if ( anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
         continue;
       const TopoDS_Shape& aShape = anOwner->Shape();
       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
       if (aShapeType == TopAbs_VERTEX) {
-        AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
+        AttributePtr aPntAttr =
+          PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
         if (aPntAttr.get() != NULL &&
-            aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end()) {
+            aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end())
+          theOwnersToSelect.Add(anOwner);
+        else if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
           theOwnersToSelect.Add(anOwner);
         }
       }
       else if (aShapeType == TopAbs_EDGE) {
-        bool aFound = aSelectedResults.find(aResult) != aSelectedResults.end();
-        if (aSelectedResults.find(aResult) != aSelectedResults.end() &&
-            theOwnersToSelect.FindIndex(anOwner) <= 0)
+        if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
+          // try to restore local selection on Shape result
+          // we can do this only if the shape was not changed
           theOwnersToSelect.Add(anOwner);
+          aFoundLocalShape = true;
+          break;
+        }
+      }
+    }
+    if (!aFoundLocalShape) {
+      // result owners are put in the list of selection only if local selected shapes were not
+      // found
+      if (aSelectedResults.find(aResult) != aSelectedResults.end()) {
+        for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
+          Handle(StdSelect_BRepOwner) anOwner =
+            Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
+          if ( anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
+            continue;
+            // select whole result
+            theOwnersToSelect.Add(anOwner);
+        }
       }
     }
   }
 }
 
-void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget, const bool isToConnect)
+void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
+                                                 const bool isToConnect)
 {
+  //Temporary commented as we do not modify values in property panel
   if (isToConnect) {
-    connect(theWidget, SIGNAL(beforeValuesChanged()),
-            this, SLOT(onBeforeValuesChangedInPropertyPanel()));
+    //connect(theWidget, SIGNAL(beforeValuesChanged()),
+    //        this, SLOT(onBeforeValuesChangedInPropertyPanel()));
+    //connect(theWidget, SIGNAL(afterValuesChanged()),
+    //        this, SLOT(onAfterValuesChangedInPropertyPanel()));
     connect(theWidget, SIGNAL(afterValuesChanged()),
-            this, SLOT(onAfterValuesChangedInPropertyPanel()));
+            myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
   }
   else {
-    disconnect(theWidget, SIGNAL(beforeValuesChanged()),
-                this, SLOT(onBeforeValuesChangedInPropertyPanel()));
+    //disconnect(theWidget, SIGNAL(beforeValuesChanged()),
+    //            this, SLOT(onBeforeValuesChangedInPropertyPanel()));
+    //disconnect(theWidget, SIGNAL(afterValuesChanged()),
+    //            this, SLOT(onAfterValuesChangedInPropertyPanel()));
     disconnect(theWidget, SIGNAL(afterValuesChanged()),
-                this, SLOT(onAfterValuesChangedInPropertyPanel()));
+               myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
   }
 }
 
@@ -1536,7 +1680,7 @@ void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
                                                                            (getCurrentOperation());
   if (aFOperation) {
     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
-        PartSet_SketcherMgr::isNestedSketchOperation(aFOperation) &&
+        isNestedSketchOperation(aFOperation) &&
         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
       FeaturePtr aFeature = aFOperation->feature();
       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
@@ -1549,8 +1693,20 @@ void PartSet_SketcherMgr::customizePresentation(const ObjectPtr& theObject)
   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
                                                                            (getCurrentOperation());
   if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
-                      PartSet_SketcherMgr::isNestedSketchOperation(aFOperation)))
+                      isNestedSketchOperation(aFOperation)))
     SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
+
+  // update entities selection priorities
+  FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
+  if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
+    // update priority for feature
+    updateSelectionPriority(aFeature, aFeature);
+    // update priority for results of the feature
+    std::list<ResultPtr> aResults = aFeature->results();
+    std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLastIt = aResults.end();
+    for (; anIt != aLastIt; anIt++)
+      updateSelectionPriority(*anIt, aFeature);
+  }
 }
 
 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
@@ -1609,52 +1765,97 @@ void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
 }
 
-void PartSet_SketcherMgr::storeSelection(const bool theHighlightedOnly)
+void PartSet_SketcherMgr::storeSelection(const SelectionType theType,
+                        PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
 {
   if (!myCurrentSketch.get())
     return;
 
   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
   ModuleBase_ISelection* aSelect = aWorkshop->selection();
-  QList<ModuleBase_ViewerPrsPtr> aHighlighted = aSelect->getHighlighted();
+  QList<ModuleBase_ViewerPrsPtr> aStoredPrs;
 
-  QList<FeaturePtr> aFeatureList;
-  if (theHighlightedOnly) {
-    fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
-  }
-  else {
-    fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
+  if (theType == ST_HighlightType || theType == ST_SelectAndHighlightType)
+    aStoredPrs = aSelect->getHighlighted();
 
-    QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(ModuleBase_ISelection::AllControls);
-    fillFeatureList(aSelected, myCurrentSketch, aFeatureList);
+  QList<FeaturePtr> aFeatureList;
+  if (theType == ST_SelectAndHighlightType || theType == ST_SelectType) {
+    QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(
+                                                              ModuleBase_ISelection::AllControls);
+    aStoredPrs.append(aSelected);
   }
 
   // 1. it is necessary to save current selection in order to restore it after the features moving
-  myCurrentSelection.clear();
-  QList<FeaturePtr>::const_iterator anIt = aFeatureList.begin(), aLast = aFeatureList.end();
+  theCurrentSelection.clear();
+
+  QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = aStoredPrs.begin(),
+                                                aLast = aStoredPrs.end();
+
+  CompositeFeaturePtr aSketch = activeSketch();
   for (; anIt != aLast; anIt++) {
-    getCurrentSelection(*anIt, myCurrentSketch, aWorkshop, myCurrentSelection);
+    ModuleBase_ViewerPrsPtr aPrs = *anIt;
+    ObjectPtr anObject = aPrs->object();
+    if (!anObject.get())
+      continue;
+
+    ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
+    FeaturePtr aFeature;
+    if (aResult.get())
+      aFeature = ModelAPI_Feature::feature(aResult);
+    else
+      aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
+
+    if (!aFeature.get())
+      continue;
+
+    std::set<AttributePtr> aSelectedAttributes;
+    std::set<ResultPtr> aSelectedResults;
+    SelectionInfo anInfo;
+    if (theCurrentSelection.find(aFeature) != theCurrentSelection.end())
+      anInfo = theCurrentSelection.find(aFeature).value();
+
+    TopoDS_Shape aFirstShape;
+    ResultPtr aFirstResult = aFeature->firstResult();
+    if (aFirstResult.get() && aFirstResult->shape().get())
+      aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
+    anInfo.myFirstResultShape = aFirstShape;
+    Handle(SelectMgr_EntityOwner) anOwner = aPrs->owner();
+    if (aResult.get()) {
+      getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
+          anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
+    }
+    else {
+      std::list<ResultPtr> aResults = aFeature->results();
+      std::list<ResultPtr>::const_iterator aIt;
+      for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
+        ResultPtr aResult = *aIt;
+        getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
+          anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
+      }
+    }
+    theCurrentSelection[aFeature] = anInfo;
   }
-  //qDebug(QString("  storeSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
+  //qDebug(QString("  storeSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
 }
 
-void PartSet_SketcherMgr::restoreSelection()
+void PartSet_SketcherMgr::restoreSelection(
+                                PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
 {
   if (!myCurrentSketch.get())
     return;
 
-  //qDebug(QString("restoreSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
+  //qDebug(QString("restoreSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
-  FeatureToSelectionMap::const_iterator aSIt = myCurrentSelection.begin(),
-                                        aSLast = myCurrentSelection.end();
+  FeatureToSelectionMap::const_iterator aSIt = theCurrentSelection.begin(),
+                                        aSLast = theCurrentSelection.end();
   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
+  anOwnersToSelect.Clear();
   for (; aSIt != aSLast; aSIt++) {
-    anOwnersToSelect.Clear();
-    getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, myCurrentSelection,
-                        anOwnersToSelect);
-    aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
+    getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, theCurrentSelection,
+                       anOwnersToSelect);
   }
+  aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
 }
 
 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
@@ -1692,15 +1893,65 @@ void PartSet_SketcherMgr::updateBySketchParameters(
     }
     break;
     case PartSet_Tools::Expressions: {
-      /// call all sketch features redisplay, the expression state will be corrected in customize
-      /// of distance presentation
-      Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
-      PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
+      if (aPrevState != theState) {
+        /// call all sketch features redisplay, the expression state will be corrected in customize
+        /// of distance presentation
+        Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
+        PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
+      }
     }
     break;
   }
 }
 
+void PartSet_SketcherMgr::updateSelectionPriority(ObjectPtr theObject,
+                                                  FeaturePtr theFeature)
+{
+  if (!theObject.get() || !theFeature.get())
+    return;
+
+  AISObjectPtr anAIS = workshop()->displayer()->getAISObject(theObject);
+  Handle(AIS_InteractiveObject) anAISIO;
+  if (anAIS.get() != NULL) {
+    anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
+  }
+
+  if (!anAISIO.IsNull()) { // the presentation for the object is visualized
+    int anAdditionalPriority = 0;
+    // current feature
+    std::shared_ptr<SketchPlugin_Feature> aSPFeature =
+            std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
+    if (aSPFeature.get() != NULL) {
+      // 1. Vertices
+      // 2. Simple segments
+      // 3. External objects (violet color)
+      // 4. Auxiliary segments (dotted)
+      // StdSelect_BRepSelectionTool::Load uses priority calculating:
+      // Standard_Integer aPriority =
+      // (thePriority == -1) ? GetStandardPriority (theShape, theType) : thePriority;
+      // Priority of Vertex is 8, edge(segment) is 7.
+      // It might be not corrected as provides the condition above.
+      bool isExternal = aSPFeature->isExternal();
+      bool isAuxiliary = PartSet_Tools::isAuxiliarySketchEntity(aSPFeature);
+      // current feature
+      if (!isExternal && !isAuxiliary)
+        anAdditionalPriority = 30;
+      // external feature
+      if (isExternal)
+        anAdditionalPriority = 20;
+      // auxiliary feature
+      if (isAuxiliary) {
+        anAdditionalPriority = 10; /// auxiliary objects should have less priority that
+        // edges/vertices of local selection on not-sketch objects
+      }
+      Handle(ModuleBase_ResultPrs) aResult = Handle(ModuleBase_ResultPrs)::DownCast(anAISIO);
+      if (!aResult.IsNull()) {
+        aResult->setAdditionalSelectionPriority(anAdditionalPriority);
+      }
+    }
+  }
+}
+
 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
 {
   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();