]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_SketcherMgr.cpp
Salome HOME
Validators return InfoMessage instead of string as an error
[modules/shaper.git] / src / PartSet / PartSet_SketcherMgr.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        PartSet_SketcherMgr.cpp
4 // Created:     19 Dec 2014
5 // Author:      Vitaly SMETANNIKOV
6
7 #include "PartSet_SketcherMgr.h"
8 #include "PartSet_SketcherReetntrantMgr.h"
9 #include "PartSet_Module.h"
10 #include "PartSet_WidgetPoint2d.h"
11 #include "PartSet_WidgetPoint2dDistance.h"
12 #include "PartSet_Tools.h"
13 #include "PartSet_WidgetSketchLabel.h"
14 #include "PartSet_WidgetEditor.h"
15 #include "PartSet_ResultSketchPrs.h"
16
17 #include <XGUI_ModuleConnector.h>
18 #include <XGUI_Displayer.h>
19 #include <XGUI_Workshop.h>
20 #include <XGUI_ContextMenuMgr.h>
21 #include <XGUI_Selection.h>
22 #include <XGUI_SelectionMgr.h>
23 #include <XGUI_ModuleConnector.h>
24 #include <XGUI_PropertyPanel.h>
25 #include <XGUI_ViewerProxy.h>
26 #include <XGUI_OperationMgr.h>
27 #include <XGUI_Tools.h>
28
29 #include <ModuleBase_IPropertyPanel.h>
30 #include <ModuleBase_ISelection.h>
31 #include <ModuleBase_IViewer.h>
32 #include <ModuleBase_IWorkshop.h>
33 #include <ModuleBase_IViewWindow.h>
34 #include <ModuleBase_ModelWidget.h>
35 #include <ModuleBase_Operation.h>
36 #include <ModuleBase_OperationFeature.h>
37 #include <ModuleBase_Operation.h>
38 #include <ModuleBase_WidgetEditor.h>
39 #include <ModuleBase_ViewerPrs.h>
40 #include <ModuleBase_Tools.h>
41 #include <ModuleBase_ResultPrs.h>
42
43 #include <GeomDataAPI_Point2D.h>
44
45 #include <Events_Loop.h>
46
47 #include <SketchPlugin_Line.h>
48 #include <SketchPlugin_Sketch.h>
49 #include <SketchPlugin_Point.h>
50 #include <SketchPlugin_Arc.h>
51 #include <SketchPlugin_Circle.h>
52 #include <SketchPlugin_ConstraintLength.h>
53 #include <SketchPlugin_ConstraintDistance.h>
54 #include <SketchPlugin_ConstraintParallel.h>
55 #include <SketchPlugin_ConstraintPerpendicular.h>
56 #include <SketchPlugin_ConstraintRadius.h>
57 #include <SketchPlugin_ConstraintRigid.h>
58 #include <SketchPlugin_ConstraintHorizontal.h>
59 #include <SketchPlugin_ConstraintVertical.h>
60 #include <SketchPlugin_ConstraintEqual.h>
61 #include <SketchPlugin_ConstraintTangent.h>
62 #include <SketchPlugin_ConstraintCoincidence.h>
63 #include <SketchPlugin_ConstraintFillet.h>
64 #include <SketchPlugin_ConstraintMirror.h>
65 #include <SketchPlugin_ConstraintAngle.h>
66 #include <SketchPlugin_ConstraintCollinear.h>
67 #include <SketchPlugin_ConstraintMiddle.h>
68 #include <SketchPlugin_MultiRotation.h>
69 #include <SketchPlugin_MultiTranslation.h>
70 #include <SketchPlugin_IntersectionPoint.h>
71
72 #include <SketcherPrs_Tools.h>
73
74 #include <SelectMgr_IndexedMapOfOwner.hxx>
75 #include <StdSelect_BRepOwner.hxx>
76
77 //#include <AIS_DimensionSelectionMode.hxx>
78 #include <AIS_Shape.hxx>
79 #include <AIS_Dimension.hxx>
80
81 #include <ModelAPI_Events.h>
82 #include <ModelAPI_Session.h>
83 #include <ModelAPI_AttributeString.h>
84
85 #include <ModelAPI_Validator.h>
86 #include <ModelAPI_Tools.h>
87
88 #include <QMouseEvent>
89 #include <QApplication>
90 #include <QCursor>
91 #include <QMessageBox>
92 #include <QMainWindow>
93
94 //#define DEBUG_DO_NOT_BY_ENTER
95
96 //#define DEBUG_CURSOR
97
98 /// Returns list of unique objects by sum of objects from List1 and List2
99 /*QList<ModuleBase_ViewerPrsPtr> getSumList(const QList<ModuleBase_ViewerPrsPtr>& theList1,
100                                        const QList<ModuleBase_ViewerPrsPtr>& theList2)
101 {
102   QList<ModuleBase_ViewerPrsPtr> aRes;
103   foreach (ModuleBase_ViewerPrsPtr aPrs, theList1) {
104     if (!aRes.contains(aPrs))
105       aRes.append(aPrs);
106   }
107   foreach (ModuleBase_ViewerPrsPtr aPrs, theList2) {
108     if (!aRes.contains(aPrs))
109       aRes.append(aPrs);
110   }
111   return aRes;
112 }*/
113
114 // Fills the list of features the list of selected presentations.
115 // \param theList a list of selected presentations
116 // \param theSketch a sketch to project a vertex shape of a presentation to the plane
117 // and find the corresponded attribute
118 // \param theFeatureList  an output list of features
119 void fillFeatureList(const QList<ModuleBase_ViewerPrsPtr>& theList,
120                      const FeaturePtr theSketch,
121                      QList<FeaturePtr>& theFeatureList)
122 {
123   QList<ModuleBase_ViewerPrsPtr> aRes;
124
125   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theList.begin(),
126                                               aLast = theList.end();
127   for (; anIt != aLast; anIt++)
128   {
129     ModuleBase_ViewerPrsPtr aPrs = *anIt;
130     FeaturePtr aFeature = ModelAPI_Feature::feature(aPrs->object());
131     if (aFeature.get()  && !theFeatureList.contains(aFeature))
132       theFeatureList.append(aFeature);
133   }
134 }
135
136 /// Fills attribute and result lists by the selected owner. In case if the attribute is found,
137 /// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge, put the function
138 /// result as is to the list of results.
139 /// \param theOwner a viewer selected owner
140 /// \param theFeature a feature, where the attribute is searched
141 /// \param theSketch a current sketch
142 /// \param theSelectedAttribute an output list of attributes
143 /// \param theSelectedResults an output list of edge results
144 void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
145                             const FeaturePtr& theFeature, const FeaturePtr& theSketch,
146                             const ResultPtr& theResult,
147                             std::set<AttributePtr>& aSelectedAttributes,
148                             std::set<ResultPtr>& aSelectedResults)
149 {
150   Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(theOwner);
151   if (aBRepOwner.IsNull())
152     return;
153   Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(
154                                                                     aBRepOwner->Selectable());
155   if (aBRepOwner->HasShape()) {
156     const TopoDS_Shape& aShape = aBRepOwner->Shape();
157     TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
158     if (aShapeType == TopAbs_VERTEX) {
159       AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature,
160                                                                     aShape, theSketch);
161       if (aPntAttr.get() != NULL)
162         aSelectedAttributes.insert(aPntAttr);
163     }
164     else if (aShapeType == TopAbs_EDGE &&
165              aSelectedResults.find(theResult) == aSelectedResults.end()) {
166       aSelectedResults.insert(theResult);
167     }
168   }
169 }
170
171 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
172   : QObject(theModule), myModule(theModule), myIsDragging(false), myDragDone(false),
173     myIsMouseOverWindow(false),
174     myIsMouseOverViewProcessed(true), myPreviousUpdateViewerEnabled(true),
175     myIsPopupMenuActive(false)
176 {
177   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
178   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
179
180   myPreviousDrawModeEnabled = true;//aViewer->isSelectionEnabled();
181
182   connect(aViewer, SIGNAL(mousePress(ModuleBase_IViewWindow*, QMouseEvent*)),
183           this, SLOT(onMousePressed(ModuleBase_IViewWindow*, QMouseEvent*)));
184
185   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)),
186           this, SLOT(onMouseReleased(ModuleBase_IViewWindow*, QMouseEvent*)));
187
188   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
189           this, SLOT(onMouseMoved(ModuleBase_IViewWindow*, QMouseEvent*)));
190
191   connect(aViewer, SIGNAL(mouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)),
192           this, SLOT(onMouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)));
193
194   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
195   XGUI_Workshop* aWorkshop = aConnector->workshop();
196   connect(aWorkshop, SIGNAL(applicationStarted()), this, SLOT(onApplicationStarted()));
197
198   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
199   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
200   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
201 }
202
203 PartSet_SketcherMgr::~PartSet_SketcherMgr()
204 {
205   if (!myPlaneFilter.IsNull())
206     myPlaneFilter.Nullify();
207 }
208
209 void PartSet_SketcherMgr::onEnterViewPort()
210 {
211   // 1. if the mouse over window, update the next flag. Do not perform update visibility of
212   // created feature because it should be done in onMouseMove(). Some widgets watch
213   // the mouse move and use the cursor position to update own values. If the presentaion is
214   // redisplayed before this update, the feature presentation jumps from reset value to current.
215   myIsMouseOverWindow = true;
216
217   #ifdef DEBUG_DO_NOT_BY_ENTER
218   return;
219   #endif
220
221   if (canChangeCursor(getCurrentOperation())) {
222     QCursor* aCurrentCursor = QApplication::overrideCursor();
223     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
224       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
225 #ifdef DEBUG_CURSOR
226       qDebug("onEnterViewPort() : Qt::CrossCursor");
227 #endif
228     }
229   }
230
231   if (!isNestedCreateOperation(getCurrentOperation()))
232     return;
233
234   operationMgr()->onValidateOperation();
235
236   // we need change displayed state of the current operation feature
237   // if the feature is presentable, e.g. distance construction. It has no results, so workshop does
238   // not accept a signal about the result created. Nothing is shown until mouse is moved out/in view
239   // port. If the isDisplayed flag is true, the presentable feature is displayed as soon as the
240   // presentation becomes valid and redisplay happens
241   //ModuleBase_Operation* aOperation = getCurrentOperation();
242   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
243                                                                            (getCurrentOperation());
244   if (aFOperation) {
245     FeaturePtr aFeature = aFOperation->feature();
246     if (aFeature.get() && aFeature->data()->isValid()) {
247       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature), false);
248     }
249   }
250 }
251
252 void PartSet_SketcherMgr::onLeaveViewPort()
253 {
254   myIsMouseOverViewProcessed = false;
255   myIsMouseOverWindow = false;
256
257   #ifdef DEBUG_DO_NOT_BY_ENTER
258   return;
259   #endif
260
261   if (canChangeCursor(getCurrentOperation())) {
262     QApplication::restoreOverrideCursor();
263 #ifdef DEBUG_CURSOR
264     qDebug("onLeaveViewPort() : None");
265 #endif
266   }
267
268   if (!isNestedCreateOperation(getCurrentOperation()))
269     return;
270
271   // the method should be performed if the popup menu is called,
272   // the reset of the current widget should not happen
273   if (myIsPopupMenuActive)
274     return;
275
276   // it is important to validate operation here only if sketch entity create operation is active
277   // because at this operation we reacts to the mouse leave/enter view port
278   operationMgr()->onValidateOperation();
279
280   // 2. if the mouse IS NOT over window, reset the active widget value and hide the presentation
281   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
282   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
283   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
284   // disable the viewer update in order to avoid visualization of redisplayed feature in viewer
285   // obtained after reset value
286   bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
287   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
288   if (anActiveWidget)
289     anActiveWidget->reset();
290
291   // hides the presentation of the current operation feature
292   // the feature is to be erased here, but it is correct to call canDisplayObject because
293   // there can be additional check (e.g. editor widget in distance constraint)
294   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
295                                                                            (getCurrentOperation());
296   if (aFOperation) {
297     FeaturePtr aFeature = aFOperation->feature();
298     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
299   }
300   // we should update viewer after the presentation are hidden in the viewer
301   // otherwise the reset presentation(line) appears in the viewer(by quick move from viewer to PP)
302   aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
303 }
304
305 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
306 {
307   if (!isNestedEditOperation(getCurrentOperation()) ||
308       myModule->sketchReentranceMgr()->isInternalEditActive())
309     return;
310   // it is necessary to save current selection in order to restore it after the values are modifed
311   storeSelection();
312
313   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
314   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
315   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
316   myPreviousUpdateViewerEnabled = aDisplayer->enableUpdateViewer(false);
317 }
318
319 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
320 {
321   if (!isNestedEditOperation(getCurrentOperation()) ||
322       myModule->sketchReentranceMgr()->isInternalEditActive()) {
323     myModule->sketchReentranceMgr()->updateInternalEditActiveState();
324     return;
325   }
326   // it is necessary to restore current selection in order to restore it after the values are modified
327   restoreSelection();
328   myCurrentSelection.clear();
329
330   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
331   // viewer happens by deselect/select the modified objects. The flag should be restored after
332   // the selection processing. The update viewer should be also called.
333   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
334   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
335   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
336   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
337   aDisplayer->updateViewer();
338
339
340 }
341
342 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
343 {
344   if (myModule->sketchReentranceMgr()->processMousePressed(theWnd, theEvent))
345     return;
346
347   //get2dPoint(theWnd, theEvent, myClickedPoint);
348
349   if (!(theEvent->buttons() & Qt::LeftButton))
350     return;
351
352   // Clear dragging mode
353   myIsDragging = false;
354
355   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
356   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
357   if (!aViewer->canDragByMouse())
358     return;
359
360   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
361                                                                (getCurrentOperation());
362   if (!aFOperation)
363     return;
364
365   if (aFOperation->isEditOperation()) {
366     // If the current widget is a selector, do nothing, it processes the mouse press
367     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
368     if(anActiveWidget && anActiveWidget->isViewerSelector()) {
369       return;
370     }
371   }
372
373   // Use only for sketch operations
374   if (myCurrentSketch) {
375     if (!PartSet_Tools::sketchPlane(myCurrentSketch))
376       return;
377
378     bool isSketcher = isSketchOperation(aFOperation);
379     bool isSketchOpe = isNestedSketchOperation(aFOperation);
380
381     // Avoid non-sketch operations
382     if ((!isSketchOpe) && (!isSketcher))
383       return;
384
385     bool isEditing = aFOperation->isEditOperation();
386
387     // Ignore creation sketch operation
388     if ((!isSketcher) && (!isEditing))
389       return;
390
391     Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
392     // Remember highlighted objects for editing
393     ModuleBase_ISelection* aSelect = aWorkshop->selection();
394
395     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
396     storeSelection(!aHasShift);
397
398     if (myCurrentSelection.empty()) {
399       if (isSketchOpe && (!isSketcher))
400         // commit previous operation
401         if (!aFOperation->commit())
402           aFOperation->abort();
403       return;
404     }
405     // Init flyout point for radius rotation
406     FeaturePtr aFeature = myCurrentSelection.begin().key();
407
408     if (isSketcher) {
409       myIsDragging = true;
410       get2dPoint(theWnd, theEvent, myCurrentPoint);
411       myDragDone = false;
412
413       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
414       launchEditing();
415       if (aFeature.get() != NULL) {
416         std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
417                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
418       if (aSPFeature.get() && aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID()) {
419           DataPtr aData = aSPFeature->data();
420           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
421           std::shared_ptr<GeomDataAPI_Point2D> aFPAttr = 
422             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
423           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
424         }
425       }
426     } else if (isSketchOpe && isEditing) {
427       // If selected another object commit current result
428       aFOperation->commit();
429
430       myIsDragging = true;
431       get2dPoint(theWnd, theEvent, myCurrentPoint);
432       myDragDone = false;
433
434       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
435
436       launchEditing();
437       restoreSelection();
438     }
439   }
440 }
441
442 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
443 {
444   if (myModule->sketchReentranceMgr()->processMouseReleased(theWnd, theEvent))
445     return;
446
447   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
448   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
449   if (!aViewer->canDragByMouse())
450     return;
451   ModuleBase_Operation* aOp = getCurrentOperation();
452   if (aOp) {
453     if (isNestedSketchOperation(aOp)) {
454       //get2dPoint(theWnd, theEvent, myClickedPoint);
455
456       // Only for sketcher operations
457       if (myIsDragging) {
458         if (myDragDone) {
459           //aOp->commit();
460           myCurrentSelection.clear();
461           /*Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
462           if (!aContext.IsNull()) {
463           // Reselect edited object
464           aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
465           if (theEvent->modifiers() & Qt::ShiftModifier)
466             aContext->ShiftSelect();
467           else
468             aContext->Select();
469           */
470         }
471       }
472     }
473   }
474
475   aWorkshop->viewer()->enableDrawMode(myPreviousDrawModeEnabled);
476   myIsDragging = false;
477 }
478
479 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
480 {
481   if (myModule->sketchReentranceMgr()->processMouseMoved(theWnd, theEvent))
482     return;
483
484   if (isNestedCreateOperation(getCurrentOperation()) && !myIsMouseOverViewProcessed) {
485     myIsMouseOverViewProcessed = true;
486     // 1. perform the widget mouse move functionality and display the presentation
487     // the mouse move should be processed in the widget, if it can in order to visualize correct
488     // presentation. These widgets correct the feature attribute according to the mouse position
489     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
490     PartSet_WidgetPoint2D* aPoint2DWdg = dynamic_cast<PartSet_WidgetPoint2D*>(anActiveWidget);
491     if (aPoint2DWdg) {
492       aPoint2DWdg->onMouseMove(theWnd, theEvent);
493     }
494     PartSet_WidgetPoint2dDistance* aDistanceWdg = dynamic_cast<PartSet_WidgetPoint2dDistance*>
495                                                                 (anActiveWidget);
496     if (aDistanceWdg) {
497       aDistanceWdg->onMouseMove(theWnd, theEvent);
498     }
499     // the feature is to be erased here, but it is correct to call canDisplayObject because
500     // there can be additional check (e.g. editor widget in distance constraint)
501     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
502                                                                              (getCurrentOperation());
503     if (aFOperation) {
504       FeaturePtr aFeature = aFOperation->feature();
505       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
506     }
507   }
508
509   //myClickedPoint.clear();
510
511   if (myIsDragging) {
512     // 1. the current selection is saved in the mouse press method in order to restore it after moving
513     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
514     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
515     // deselected). This flag should be restored in the slot, processed the mouse release signal.
516
517     ModuleBase_Operation* aCurrentOperation = getCurrentOperation();
518     if (!aCurrentOperation)
519       return;
520     if (isSketchOperation(aCurrentOperation))
521       return; // No edit operation activated
522
523     Handle(V3d_View) aView = theWnd->v3dView();
524     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
525     double aX, aY;
526     PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, aY);
527     double dX =  aX - myCurrentPoint.myCurX;
528     double dY =  aY - myCurrentPoint.myCurY;
529
530     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
531     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
532     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
533     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
534     // viewer happens by deselect/select the modified objects. The flag should be restored after
535     // the selection processing. The update viewer should be also called.
536     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
537
538     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
539     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
540     FeatureToSelectionMap::const_iterator anIt = myCurrentSelection.begin(),
541                                           aLast = myCurrentSelection.end();
542     // 4. the features and attributes modification(move)
543     bool isModified = false;
544     for (; anIt != aLast; anIt++) {
545       FeaturePtr aFeature = anIt.key();
546
547       std::set<AttributePtr> anAttributes = anIt.value().first;
548       // Process selection by attribute: the priority to the attribute
549       if (!anAttributes.empty()) {
550         std::set<AttributePtr>::const_iterator anAttIt = anAttributes.begin(),
551                                                anAttLast = anAttributes.end();
552         for (; anAttIt != anAttLast; anAttIt++) {
553           AttributePtr anAttr = *anAttIt;
554           if (anAttr.get() == NULL)
555             continue;
556           std::string aAttrId = anAttr->id();
557           DataPtr aData = aFeature->data();
558           if (aData->isValid()) {
559             std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
560               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
561             if (aPoint.get() != NULL) {
562               bool isImmutable = aPoint->setImmutable(true);
563               aPoint->move(dX, dY);
564               isModified = true;
565               ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
566               aPoint->setImmutable(isImmutable);
567             }
568           }
569         }
570       } else {
571         // Process selection by feature
572         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
573           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
574         if (aSketchFeature) {
575           aSketchFeature->move(dX, dY);
576           isModified = true;
577           ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
578         }
579       }
580     }
581     // the modified state of the current operation should be updated if there are features, which
582     // were changed here
583     if (isModified) {
584       aCurrentOperation->onValuesChanged();
585     }
586     Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
587     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
588
589     // 5. it is necessary to save current selection in order to restore it after the features moving
590     restoreSelection();
591     // 6. restore the update viewer flag and call this update
592     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
593     aDisplayer->updateViewer();
594
595     myDragDone = true;
596     myCurrentPoint.setValue(aX, aY);
597   }
598 }
599
600 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
601 {
602   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
603                                                                (getCurrentOperation());
604   if (aFOperation && aFOperation->isEditOperation()) {
605     std::string aId = aFOperation->id().toStdString();
606     if (isDistanceOperation(aFOperation))
607     {
608       // Activate dimension value editing on double click
609       ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
610       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
611       // Find corresponded widget to activate value editing
612       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
613         if (aWgt->attributeID() == SketchPlugin_Constraint::VALUE() ||
614             aWgt->attributeID() == SketchPlugin_ConstraintAngle::ANGLE_VALUE_ID()) {
615           PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
616           if (anEditor)
617             anEditor->showPopupEditor();
618           return;
619         }
620       }
621     }
622   }
623 }
624
625 void PartSet_SketcherMgr::onApplicationStarted()
626 {
627   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
628   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
629   XGUI_Workshop* aWorkshop = aConnector->workshop();
630   PartSet_SketcherReetntrantMgr* aReentranceMgr = myModule->sketchReentranceMgr();
631
632   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
633   if (aPropertyPanel) {
634     //connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
635     //        this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
636
637     connect(aPropertyPanel, SIGNAL(noMoreWidgets(const std::string&)),
638             aReentranceMgr, SLOT(onNoMoreWidgets(const std::string&)));
639     connect(aPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
640             aReentranceMgr, SLOT(onWidgetActivated()));
641   }
642
643   XGUI_ViewerProxy* aViewerProxy = aWorkshop->viewer();
644   connect(aViewerProxy, SIGNAL(enterViewPort()), this, SLOT(onEnterViewPort()));
645   connect(aViewerProxy, SIGNAL(leaveViewPort()), this, SLOT(onLeaveViewPort()));
646
647   XGUI_ContextMenuMgr* aContextMenuMgr = aWorkshop->contextMenuMgr();
648   connect(aContextMenuMgr, SIGNAL(beforeContextMenu()), this, SLOT(onBeforeContextMenu()));
649   connect(aContextMenuMgr, SIGNAL(afterContextMenu()), this, SLOT(onAfterContextMenu()));
650 }
651
652 //void PartSet_SketcherMgr::onBeforeWidgetActivated(ModuleBase_ModelWidget* theWidget)
653 //{
654   //if (!myClickedPoint.myIsInitialized)
655   //  return;
656
657   //ModuleBase_Operation* aOperation = getCurrentOperation();
658   // the distance constraint feature should not use the clickedd point
659   // this is workaround in order to don't throw down the flyout point value,
660   // set by execute() method of these type of features
661   //if (isDistanceOperation(aOperation))
662   //  return;
663
664   //PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(theWidget);
665   //if (aPnt2dWgt) {
666   //  aPnt2dWgt->setPoint(myClickedPoint.myCurX, myClickedPoint.myCurY);
667   //}
668 //}
669
670 void PartSet_SketcherMgr::onBeforeContextMenu()
671 {
672   myIsPopupMenuActive = true;
673 }
674
675 void PartSet_SketcherMgr::onAfterContextMenu()
676 {
677   myIsPopupMenuActive = false;
678 }
679
680 void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent, 
681                                      Point& thePoint)
682 {
683   Handle(V3d_View) aView = theWnd->v3dView();
684   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
685   double aX, anY;
686   PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, anY);
687   thePoint.setValue(aX, anY);
688 }
689
690 void PartSet_SketcherMgr::launchEditing()
691 {
692   if (!myCurrentSelection.empty()) {
693     FeaturePtr aFeature = myCurrentSelection.begin().key();
694     std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
695               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
696     if (aSPFeature && (!aSPFeature->isExternal())) {
697       myModule->editFeature(aSPFeature);
698     }
699   }
700 }
701
702 bool PartSet_SketcherMgr::sketchSolverError()
703 {
704   bool anError = false;
705   CompositeFeaturePtr aSketch = activeSketch();
706   if (aSketch.get()) {
707     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
708     anError = !aAttributeString->value().empty();
709   }
710   return anError;
711 }
712
713 QString PartSet_SketcherMgr::getFeatureError(const FeaturePtr& theFeature)
714 {
715   std::string anError = "";
716   if (!theFeature.get() || !theFeature->data()->isValid())
717     return anError.c_str();
718
719   CompositeFeaturePtr aSketch = activeSketch();
720   if (aSketch.get() && aSketch == theFeature) {
721     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
722     anError = aAttributeString->value();
723     ModuleBase_Tools::translate(aSketch->getKind(), anError);
724   }
725   return anError.c_str();
726 }
727
728 void PartSet_SketcherMgr::clearClickedFlags()
729 {
730   //myClickedPoint.clear();
731   myCurrentPoint.clear();
732 }
733
734 const QStringList& PartSet_SketcherMgr::sketchOperationIdList()
735 {
736   static QStringList aIds;
737   if (aIds.size() == 0) {
738     aIds << SketchPlugin_Line::ID().c_str();
739     aIds << SketchPlugin_Point::ID().c_str();
740     aIds << SketchPlugin_Arc::ID().c_str();
741     aIds << SketchPlugin_Circle::ID().c_str();
742     aIds << SketchPlugin_ConstraintFillet::ID().c_str();
743     aIds << SketchPlugin_IntersectionPoint::ID().c_str();
744     // TODO
745     // SketchRectangle is a python feature, so its ID is passed just as a string
746     aIds << "SketchRectangle";
747     aIds.append(replicationsIdList());
748     aIds.append(constraintsIdList());
749   }
750   return aIds;
751 }
752
753 const QStringList& PartSet_SketcherMgr::replicationsIdList()
754 {
755   static QStringList aReplicationIds;
756   if (aReplicationIds.size() == 0) {
757     aReplicationIds << SketchPlugin_ConstraintMirror::ID().c_str();
758     aReplicationIds << SketchPlugin_MultiRotation::ID().c_str();
759     aReplicationIds << SketchPlugin_MultiTranslation::ID().c_str();
760   }
761   return aReplicationIds;
762 }
763
764 const QStringList& PartSet_SketcherMgr::constraintsIdList()
765 {
766   static QStringList aConstraintIds;
767   if (aConstraintIds.size() == 0) {
768     aConstraintIds << SketchPlugin_ConstraintLength::ID().c_str();
769     aConstraintIds << SketchPlugin_ConstraintDistance::ID().c_str();
770     aConstraintIds << SketchPlugin_ConstraintRigid::ID().c_str();
771     aConstraintIds << SketchPlugin_ConstraintRadius::ID().c_str();
772     aConstraintIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
773     aConstraintIds << SketchPlugin_ConstraintParallel::ID().c_str();
774     aConstraintIds << SketchPlugin_ConstraintHorizontal::ID().c_str();
775     aConstraintIds << SketchPlugin_ConstraintVertical::ID().c_str();
776     aConstraintIds << SketchPlugin_ConstraintEqual::ID().c_str();
777     aConstraintIds << SketchPlugin_ConstraintTangent::ID().c_str();
778     aConstraintIds << SketchPlugin_ConstraintCoincidence::ID().c_str();
779     aConstraintIds << SketchPlugin_ConstraintAngle::ID().c_str();
780     aConstraintIds << SketchPlugin_ConstraintCollinear::ID().c_str();
781     aConstraintIds << SketchPlugin_ConstraintMiddle::ID().c_str();
782   }
783   return aConstraintIds;
784 }
785
786 void PartSet_SketcherMgr::sketchSelectionModes(QIntList& theModes)
787 {
788   theModes.clear();
789
790   theModes.append(SketcherPrs_Tools::Sel_Dimension_Text);
791   theModes.append(SketcherPrs_Tools::Sel_Dimension_Line);
792   theModes.append(SketcherPrs_Tools::Sel_Constraint);
793   theModes.append(TopAbs_VERTEX);
794   theModes.append(TopAbs_EDGE);
795 }
796
797 Handle(AIS_InteractiveObject) PartSet_SketcherMgr::createPresentation(const ResultPtr& theResult)
798 {
799   Handle(AIS_InteractiveObject) aPrs;
800
801   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
802   if (aFeature.get() && aFeature->getKind() == SketchPlugin_Sketch::ID()) {
803     aPrs = new PartSet_ResultSketchPrs(theResult);
804   }
805   return aPrs;
806 }
807
808 bool PartSet_SketcherMgr::isSketchOperation(ModuleBase_Operation* theOperation)
809 {
810   return theOperation && theOperation->id().toStdString() == SketchPlugin_Sketch::ID();
811 }
812
813 bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation)
814 {
815   return theOperation &&
816          PartSet_SketcherMgr::sketchOperationIdList().contains(theOperation->id());
817 }
818
819 bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation)
820 {
821   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
822                                                                (theOperation);
823   return aFOperation && !aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
824 }
825
826 bool PartSet_SketcherMgr::isNestedEditOperation(ModuleBase_Operation* theOperation)
827 {
828   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
829                                                                (theOperation);
830   return aFOperation && aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
831 }
832
833 bool PartSet_SketcherMgr::isEntity(const std::string& theId)
834 {
835   return (theId == SketchPlugin_Line::ID()) ||
836          (theId == SketchPlugin_Point::ID()) ||
837          (theId == SketchPlugin_Arc::ID()) ||
838          (theId == SketchPlugin_Circle::ID());
839 }
840
841 bool PartSet_SketcherMgr::isDistanceOperation(ModuleBase_Operation* theOperation)
842 {
843   std::string anId = theOperation ? theOperation->id().toStdString() : "";
844
845   return isDistanceKind(anId);
846 }
847
848 bool PartSet_SketcherMgr::isDistanceKind(std::string& theKind)
849 {
850   return (theKind == SketchPlugin_ConstraintLength::ID()) ||
851          (theKind == SketchPlugin_ConstraintDistance::ID()) ||
852          (theKind == SketchPlugin_ConstraintRadius::ID()) ||
853          (theKind == SketchPlugin_ConstraintAngle::ID());
854 }
855
856 void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
857 {
858   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
859                                                                (getCurrentOperation());
860   if (!aFOperation)
861     return;
862
863   myModule->onViewTransformed();
864
865   // Display all sketcher sub-Objects
866   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFOperation->feature());
867   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
868
869   // Hide sketcher result
870   std::list<ResultPtr> aResults = myCurrentSketch->results();
871   std::list<ResultPtr>::const_iterator aIt;
872   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
873     (*aIt)->setDisplayed(false);
874   }
875   myCurrentSketch->setDisplayed(false);
876
877   // Remove invalid sketch entities
878   /*
879   std::set<FeaturePtr> anInvalidFeatures;
880   ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
881   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
882     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
883     if (aFeature.get()) {
884       if (!aFactory->validate(aFeature))
885         anInvalidFeatures.insert(aFeature);
886     }
887   }
888   std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
889   ModelAPI_Tools::findAllReferences(anInvalidFeatures, aReferences, false);
890   std::set<FeaturePtr> aFeatureRefsToDelete;
891   if (ModuleBase_Tools::askToDelete(anInvalidFeatures, aReferences, aConnector->desktop(), aFeatureRefsToDelete)) {
892     if (!aFeatureRefsToDelete.empty())
893       anInvalidFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
894     bool aDone = ModelAPI_Tools::removeFeatures(anInvalidFeatures, false);
895   }
896   else
897     return;
898   */
899   // Display sketcher objects
900   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
901     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
902     std::list<ResultPtr> aResults = aFeature->results();
903     std::list<ResultPtr>::const_iterator aIt;
904     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
905       (*aIt)->setDisplayed(true);
906     }
907     aFeature->setDisplayed(true);
908   }
909
910   if(myCirclePointFilter.IsNull()) {
911     myCirclePointFilter = new PartSet_CirclePointFilter(myModule->workshop());
912   }
913
914   myModule->workshop()->viewer()->addSelectionFilter(myCirclePointFilter);
915
916   if (myPlaneFilter.IsNull()) 
917     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
918
919   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
920   bool aHasPlane = false;
921   std::shared_ptr<GeomAPI_Pln> aPln;
922   aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
923   myPlaneFilter->setPlane(aPln);
924
925   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
926   // all displayed objects should be activated in current selection modes according to switched
927   // plane filter
928   if (aPln.get())
929     aConnector->activateModuleSelectionModes();
930 }
931
932 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
933 {
934   myIsMouseOverWindow = false;
935   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
936   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
937   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
938
939   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
940
941   DataPtr aData = myCurrentSketch->data();
942   if (!aData->isValid()) {
943     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
944     // The sketch was aborted
945     myCurrentSketch = CompositeFeaturePtr();
946     // TODO: move this outside of if-else
947     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
948     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
949
950     // Erase all sketcher objects
951     QStringList aSketchIds = sketchOperationIdList();
952     QObjectPtrList aObjects = aDisplayer->displayedObjects();
953     foreach (ObjectPtr aObj, aObjects) {
954       DataPtr aObjData = aObj->data();
955       if (!aObjData->isValid())
956         aObj->setDisplayed(false);
957     }
958   }
959   else {
960     // Hide all sketcher sub-Objects
961     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
962       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
963       std::list<ResultPtr> aResults = aFeature->results();
964       std::list<ResultPtr>::const_iterator aIt;
965       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
966         (*aIt)->setDisplayed(false);
967       }
968       aFeature->setDisplayed(false);
969     }
970     // Display sketcher result
971     std::list<ResultPtr> aResults = myCurrentSketch->results();
972     std::list<ResultPtr>::const_iterator aIt;
973     Events_Loop* aLoop = Events_Loop::loop();
974     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
975
976     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
977                                                                            (theOperation);
978     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
979       if (!aFOperation->isDisplayedOnStart(*aIt)) {
980         (*aIt)->setDisplayed(true);
981         // this display event is needed because sketch already may have "displayed" state,
982         // but not displayed while it is still active (issue 613, abort of existing sketch)
983         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
984       }
985     }
986     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
987       myCurrentSketch->setDisplayed(true);
988     
989     myCurrentSketch = CompositeFeaturePtr();
990
991     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
992     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
993
994     Events_Loop::loop()->flush(aDispEvent);
995   }
996   // restore the module selection modes, which were changed on startSketch
997   aConnector->activateModuleSelectionModes();
998 }
999
1000 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
1001 {
1002   if (canChangeCursor(theOperation) && myIsMouseOverWindow) {
1003     QCursor* aCurrentCursor = QApplication::overrideCursor();
1004     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
1005       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
1006 #ifdef DEBUG_CURSOR
1007       qDebug("startNestedSketch() : Qt::CrossCursor");
1008 #endif
1009     }
1010   }
1011 }
1012
1013 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
1014 {
1015   myIsMouseOverViewProcessed = true;
1016   operationMgr()->onValidateOperation();
1017   if (canChangeCursor(theOperation)) {
1018     QApplication::restoreOverrideCursor();
1019 #ifdef DEBUG_CURSOR
1020     qDebug("stopNestedSketch() : None");
1021 #endif
1022   }
1023   /// improvement to deselect automatically all eventual selected objects, when
1024   // returning to the neutral point of the Sketcher
1025   // if the operation is restarted, the previous selection is used to initialize started operation
1026   if (!myModule->sketchReentranceMgr()->isInternalEditStarted())
1027     workshop()->selector()->clearSelection();
1028 }
1029
1030 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
1031 {
1032   if (isNestedCreateOperation(theOperation)) {
1033     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1034                                                                              (theOperation);
1035     if (aFOperation) {
1036       FeaturePtr aFeature = aFOperation->feature();
1037       // it is necessary to check the the feature data validity because
1038       // some kind of features are removed by an operation commit(the macro state of a feature)
1039       if (aFeature.get() && aFeature->data()->isValid()) {
1040         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
1041       }
1042     }
1043   }
1044 }
1045
1046 void PartSet_SketcherMgr::activatePlaneFilter(const bool& toActivate)
1047 {
1048   if (toActivate)
1049     myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
1050   else
1051     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
1052 }
1053
1054 bool PartSet_SketcherMgr::operationActivatedByPreselection()
1055 {
1056   bool isOperationStopped = false;
1057   ModuleBase_Operation* anOperation = getCurrentOperation();
1058   if(anOperation && PartSet_SketcherMgr::isNestedSketchOperation(anOperation)) {
1059     // Set final definitions if they are necessary
1060     //propertyPanelDefined(aOperation);
1061     /// Commit sketcher operations automatically
1062     /// distance operation are able to show popup editor to modify the distance value
1063     /// after entering the value, the operation should be committed/aborted(by Esc key)
1064     bool aCanCommitOperation = true;
1065     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1066                                                                             (anOperation);
1067     if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation)) {
1068       bool aValueAccepted = setDistanceValueByPreselection(anOperation, myModule->workshop(),
1069                                                            aCanCommitOperation);
1070       if (!aValueAccepted)
1071         return isOperationStopped;
1072     }
1073
1074     if (aCanCommitOperation)
1075       isOperationStopped = anOperation->commit();
1076     else {
1077       anOperation->abort();
1078       isOperationStopped = true;
1079     }
1080   }
1081   return isOperationStopped;
1082 }
1083
1084 bool PartSet_SketcherMgr::canUndo() const
1085 {
1086   return isNestedCreateOperation(getCurrentOperation());
1087 }
1088
1089 bool PartSet_SketcherMgr::canRedo() const
1090 {
1091   return isNestedCreateOperation(getCurrentOperation());
1092 }
1093
1094 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1095 {
1096   bool aCanErase = true;
1097   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1098   if (myCurrentSketch.get()) {
1099     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1100     if (aResult.get()) {
1101       // Display sketcher objects
1102       for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1103
1104         FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1105         std::list<ResultPtr> aResults = aFeature->results();
1106         std::list<ResultPtr>::const_iterator anIt;
1107         for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1108           aCanErase = *anIt != aResult;
1109         }
1110       }
1111     }
1112   }
1113   return aCanErase;
1114 }
1115
1116 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1117 {
1118   bool aCanDisplay = true;
1119
1120   bool aHasActiveSketch = activeSketch().get() != NULL;
1121   if (aHasActiveSketch) {
1122     // 1. the sketch feature should not be displayed during the sketch active operation
1123     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch 
1124     // nested features can be visualized
1125     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1126     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1127       aCanDisplay = false;
1128     }
1129     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1130                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1131     /// some sketch entities should be never shown, e.g. projection feature
1132     if (aSketchFeature.get())
1133       aCanDisplay = aSketchFeature->canBeDisplayed();
1134   }
1135   else { // there are no an active sketch
1136     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1137     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1138     if (aFeature.get() != NULL) {
1139       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1140                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1141       if (aSketchFeature.get()) {
1142         aCanDisplay = false;
1143       }
1144     }
1145   }
1146
1147   // 3. the method should not filter the objects, which are not related to the current operation.
1148   // The object is filtered just if it is a current operation feature or this feature result
1149   if (aCanDisplay) {
1150     bool isObjectFound = false;
1151     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1152                                                                  (getCurrentOperation());
1153     if (aFOperation) {
1154       FeaturePtr aFeature = aFOperation->feature();
1155       if (aFeature.get()) {
1156         std::list<ResultPtr> aResults = aFeature->results();
1157         if (theObject == aFeature)
1158           isObjectFound = true;
1159         else {
1160           std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1161           for (; anIt != aLast && !isObjectFound; anIt++) {
1162             isObjectFound = *anIt == theObject;
1163           }
1164         }
1165       }
1166     }
1167     if (isObjectFound) {
1168       // 4. For created nested feature operation do not display the created feature if
1169       // the mouse curstor leaves the OCC window.
1170       // The correction cases, which ignores this condition:
1171       // a. the property panel values modification
1172       // b. the popup menu activated
1173       // c. widget editor control
1174       #ifndef DEBUG_DO_NOT_BY_ENTER
1175       if (isNestedCreateOperation(getCurrentOperation())) {
1176         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1177         ModuleBase_WidgetEditor* anEditorWdg = anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1178         // the active widget editor should not influence here. The presentation should be visible always
1179         // when this widget is active.
1180         if (!anEditorWdg && !myIsPopupMenuActive) {
1181           // during a nested create operation, the feature is redisplayed only if the mouse over view
1182           // of there was a value modified in the property panel after the mouse left the view
1183           aCanDisplay = canDisplayCurrentCreatedFeature();
1184         }
1185       }
1186       #endif
1187     }
1188   }
1189
1190   // checks the sketcher constraints visibility according to active sketch check box states
1191   if (aCanDisplay) {
1192     bool aProcessed = false;
1193     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1194     if (aFeature.get()) {
1195       bool aConstraintDisplayed = canDisplayConstraint(aFeature, PartSet_Tools::Any, aProcessed);
1196       if (aProcessed)
1197         aCanDisplay = aConstraintDisplayed;
1198     }
1199   }
1200
1201   return aCanDisplay;
1202 }
1203
1204 bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
1205                                              const PartSet_Tools::ConstraintVisibleState& theState,
1206                                              bool& isProcessed) const
1207 {
1208   bool aSwitchedOn = true;
1209
1210   const QStringList& aConstrIds = constraintsIdList();
1211
1212   std::string aKind = theFeature->getKind();
1213   if (aConstrIds.contains(QString(aKind.c_str()))) {
1214     bool isTypedConstraint = false;
1215
1216     switch (theState) {
1217       case PartSet_Tools::Dimensional: {
1218         bool isDistance = isDistanceKind(aKind);
1219         if (isDistance) {
1220           isProcessed = true;
1221           aSwitchedOn = myIsConstraintsShown[theState];
1222         }
1223       }
1224       break;
1225       case PartSet_Tools::Geometrical: {
1226         bool isGeometrical = !isDistanceKind(aKind);
1227         if (isGeometrical) {
1228           isProcessed = true;
1229           aSwitchedOn = myIsConstraintsShown[theState];
1230         }
1231       }
1232       break;
1233       case PartSet_Tools::Any: {
1234         isProcessed = true;
1235         bool isDistance = isDistanceKind(aKind);
1236         if (isDistance)
1237           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Dimensional];
1238         else
1239           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Geometrical];
1240       }
1241       break;
1242     default:
1243       break;
1244     }
1245   }
1246   return aSwitchedOn;
1247 }
1248
1249 /*void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
1250 {
1251   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1252                                                                            (getCurrentOperation());
1253   if (aFOperation && myCurrentSketch.get()) {
1254     // find results of the current operation
1255     // these results should not be proposed to be deleted
1256     FeaturePtr anOperationFeature = aFOperation->feature();
1257     std::list<ResultPtr> anOperationResultList = anOperationFeature->results();
1258     std::set<ResultPtr> anOperationResults;
1259     std::list<ResultPtr>::const_iterator aRIt = anOperationResultList.begin(),
1260                                         aRLast = anOperationResultList.end();
1261     for (; aRIt != aRLast; aRIt++)
1262       anOperationResults.insert(*aRIt);
1263
1264     std::set<FeaturePtr> anObjectsToBeDeleted;
1265     QStringList anObjectsToBeDeletedNames;
1266     std::list<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1267     for (; anIt != aLast; anIt++) {
1268       ObjectPtr anObject = *anIt;
1269       bool aCanErase = true;
1270       // when the sketch operation is active, results of sketch sub-feature can not be hidden
1271       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1272       // the result is found between current feature results
1273       if (anOperationResults.find(aResult) != anOperationResults.end())
1274         continue;
1275
1276       if (aResult.get()) {
1277         // Display sketcher objects
1278         for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1279           FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1280           std::list<ResultPtr> aResults = aFeature->results();
1281           std::list<ResultPtr>::const_iterator anIt;
1282           for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1283             aCanErase = *anIt != aResult;
1284           }
1285         }
1286       }
1287       if (!aCanErase) {
1288         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
1289         if (aFeature.get() && anObjectsToBeDeleted.find(aFeature) == anObjectsToBeDeleted.end()) {
1290           anObjectsToBeDeleted.insert(aFeature);
1291           anObjectsToBeDeletedNames.append(aFeature->name().c_str());
1292         }
1293       }
1294     }
1295     if (!anObjectsToBeDeleted.empty()) {
1296       QString aFeatureNames = anObjectsToBeDeletedNames.join(", ");
1297       QString aMessage = tr("The following features have incorrect presentation and \
1298 will be hidden: %1. Would you like to delete them?")
1299                          .arg(aFeatureNames);
1300       int anAnswer = QMessageBox::question(qApp->activeWindow(), tr("Features hide"),
1301                                            aMessage, QMessageBox::Ok | QMessageBox::Cancel,
1302                                            QMessageBox::Cancel);
1303       if (anAnswer == QMessageBox::Ok) {
1304         QObjectPtrList anObjects;
1305         std::set<FeaturePtr>::const_iterator anIt = anObjectsToBeDeleted.begin(),
1306                                              aLast = anObjectsToBeDeleted.end();
1307         for (; anIt != aLast; anIt++)
1308           anObjects.append(*anIt);
1309         SessionPtr aMgr = ModelAPI_Session::get();
1310         DocumentPtr aDoc = aMgr->activeDocument();
1311         bool aIsOp = aMgr->isOperation();
1312         if (!aIsOp)
1313           aMgr->startOperation();
1314         workshop()->deleteFeatures(anObjects);
1315         //static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
1316         //static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
1317         //Events_Loop::loop()->flush(aDeletedEvent);
1318         //Events_Loop::loop()->flush(aRedispEvent);
1319
1320         if (!aIsOp)
1321           aMgr->finishOperation();
1322       }
1323     }
1324   }
1325 }*/
1326
1327 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1328 {
1329   bool aCanDisplay = myIsMouseOverWindow;
1330   if (!aCanDisplay) {
1331     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1332     if (anActiveWidget)
1333       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1334   }
1335   return aCanDisplay;
1336 }
1337
1338 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1339 {
1340   return isNestedCreateOperation(theOperation) ||
1341          myModule->sketchReentranceMgr()->isInternalEditActive();
1342 }
1343
1344 const QMap<PartSet_Tools::ConstraintVisibleState, bool>& PartSet_SketcherMgr::showConstraintStates()
1345 {
1346   return myIsConstraintsShown;
1347 }
1348
1349 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1350 {
1351   bool isFoundObject = false;
1352
1353   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1354   if (anObjectFeature.get()) {
1355     int aSize = myCurrentSketch->numberOfSubs();
1356     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1357       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1358       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1359     }
1360   }
1361   return isFoundObject;
1362 }
1363
1364 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
1365 {
1366   if (myPlaneFilter.IsNull()) 
1367    myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
1368
1369   myPlaneFilter->setPlane(thePln);
1370 }
1371
1372 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
1373                                                          ModuleBase_IWorkshop* theWorkshop,
1374                                                          bool& theCanCommitOperation)
1375 {
1376   bool isValueAccepted = false;
1377   theCanCommitOperation = false;
1378
1379   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1380                                                                               (theOperation);
1381   FeaturePtr aFeature = aFOperation->feature();
1382   // editor is shown only if all attribute references are filled by preseletion
1383   bool anAllRefAttrInitialized = true;
1384
1385   std::list<AttributePtr> aRefAttrs = aFeature->data()->attributes(
1386                                               ModelAPI_AttributeRefAttr::typeId());
1387   std::list<AttributePtr>::const_iterator anIt = aRefAttrs.begin(), aLast = aRefAttrs.end();
1388   for (; anIt != aLast && anAllRefAttrInitialized; anIt++) {
1389     anAllRefAttrInitialized = (*anIt)->isInitialized();
1390   }
1391   if (anAllRefAttrInitialized) {
1392     // Activate dimension value editing on double click
1393     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
1394     QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
1395     // Find corresponded widget to activate value editing
1396     foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
1397       if (aWgt->attributeID() == "ConstraintValue") {
1398         // the featue should be displayed in order to find the AIS text position,
1399         // the place where the editor will be shown
1400         aFeature->setDisplayed(true);
1401         /// the execute is necessary to perform in the feature compute for flyout position
1402         aFeature->execute();
1403
1404         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1405         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1406
1407         PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
1408         if (anEditor) {
1409           int aX = 0, anY = 0;
1410
1411           XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(theWorkshop);
1412           XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1413           AISObjectPtr anAIS = aDisplayer->getAISObject(aFeature);
1414           Handle(AIS_InteractiveObject) anAISIO;
1415           if (anAIS.get() != NULL) {
1416             anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1417           }
1418           if (anAIS.get() != NULL) {
1419             Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1420
1421             if (!anAISIO.IsNull()) {
1422               Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAISIO);
1423               if (!aDim.IsNull()) {
1424                 gp_Pnt aPosition = aDim->GetTextPosition();
1425
1426                 ModuleBase_IViewer* aViewer = aWorkshop->viewer();
1427                 Handle(V3d_View) aView = aViewer->activeView();
1428                 int aCX, aCY;
1429                 aView->Convert(aPosition.X(), aPosition.Y(), aPosition.Z(), aCX, aCY);
1430
1431                 QWidget* aViewPort = aViewer->activeViewPort();
1432                 QPoint aGlPoint = aViewPort->mapToGlobal(QPoint(aCX, aCY));
1433                 aX = aGlPoint.x();
1434                 anY = aGlPoint.y();
1435               }
1436             }
1437             anEditor->setCursorPosition(aX, anY);
1438             isValueAccepted = anEditor->showPopupEditor(false);
1439             theCanCommitOperation = true;
1440           }
1441         }
1442       }
1443     }
1444   }
1445   return isValueAccepted;
1446 }
1447
1448 void PartSet_SketcherMgr::getCurrentSelection(const FeaturePtr& theFeature,
1449                                               const FeaturePtr& theSketch,
1450                                               ModuleBase_IWorkshop* theWorkshop,
1451                                               FeatureToSelectionMap& theSelection)
1452 {
1453   if (theFeature.get() == NULL)
1454     return;
1455
1456   std::set<AttributePtr> aSelectedAttributes;
1457   std::set<ResultPtr> aSelectedResults;
1458
1459   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1460   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
1461   if (!aContext.IsNull()) {
1462     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1463     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1464
1465     std::list<ResultPtr> aResults = theFeature->results();
1466     std::list<ResultPtr>::const_iterator aIt;
1467     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1468     {
1469       ResultPtr aResult = *aIt;
1470       AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1471       if (aAISObj.get() == NULL)
1472         continue;
1473       Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1474       for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
1475       {
1476         Handle(SelectMgr_EntityOwner) anOwner = aContext->SelectedOwner();
1477         if (anOwner->Selectable() != anAISIO)
1478           continue;
1479         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1480                                aSelectedAttributes, aSelectedResults);
1481       }
1482       for (aContext->InitDetected(); aContext->MoreDetected(); aContext->NextDetected()) {
1483         Handle(SelectMgr_EntityOwner) anOwner = aContext->DetectedOwner();
1484         if (anOwner.IsNull())
1485           continue;
1486         if (anOwner->Selectable() != anAISIO)
1487           continue;
1488         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1489                                aSelectedAttributes, aSelectedResults);
1490       }
1491     }
1492   }
1493   theSelection[theFeature] = std::make_pair(aSelectedAttributes, aSelectedResults);
1494 }
1495
1496 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1497                                              const FeaturePtr& theSketch,
1498                                              ModuleBase_IWorkshop* theWorkshop,
1499                                              const FeatureToSelectionMap& theSelection,
1500                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1501 {
1502   if (theFeature.get() == NULL)
1503     return;
1504
1505   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1506   std::set<AttributePtr> aSelectedAttributes = anIt.value().first;
1507   std::set<ResultPtr> aSelectedResults = anIt.value().second;
1508
1509   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1510
1511   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1512   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1513
1514   // 1. found the feature's owners. Check the AIS objects of the constructions
1515   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1516   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1517     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1518
1519     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1520     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1521     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1522       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1523       if (!anOwner.IsNull())
1524         theOwnersToSelect.Add(anOwner);
1525     }
1526   }
1527
1528   // 2. found the feature results's owners
1529   std::list<ResultPtr> aResults = theFeature->results();
1530   std::list<ResultPtr>::const_iterator aIt;
1531   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1532   {
1533     ResultPtr aResult = *aIt;
1534     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1535     if (aAISObj.get() == NULL)
1536       continue; 
1537     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1538
1539     SelectMgr_IndexedMapOfOwner aSelectedOwners;  
1540     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1541     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1542       Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1543       if ( anOwner.IsNull() || !anOwner->HasShape() )
1544         continue;
1545       const TopoDS_Shape& aShape = anOwner->Shape();
1546       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1547       if (aShapeType == TopAbs_VERTEX) {
1548         AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1549         if (aPntAttr.get() != NULL &&
1550             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end()) {
1551           theOwnersToSelect.Add(anOwner);
1552         }
1553       }
1554       else if (aShapeType == TopAbs_EDGE) {
1555         bool aFound = aSelectedResults.find(aResult) != aSelectedResults.end();
1556         if (aSelectedResults.find(aResult) != aSelectedResults.end() &&
1557             theOwnersToSelect.FindIndex(anOwner) <= 0)
1558           theOwnersToSelect.Add(anOwner);
1559       }
1560     }
1561   }
1562 }
1563
1564 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget, const bool isToConnect)
1565 {
1566   if (isToConnect) {
1567     connect(theWidget, SIGNAL(beforeValuesChanged()),
1568             this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1569     connect(theWidget, SIGNAL(afterValuesChanged()),
1570             this, SLOT(onAfterValuesChangedInPropertyPanel()));
1571   }
1572   else {
1573     disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1574                 this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1575     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1576                 this, SLOT(onAfterValuesChangedInPropertyPanel()));
1577   }
1578 }
1579
1580 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1581 {
1582   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1583                                                                            (getCurrentOperation());
1584   if (aFOperation) {
1585     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1586         PartSet_SketcherMgr::isNestedSketchOperation(aFOperation) &&
1587         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1588       FeaturePtr aFeature = aFOperation->feature();
1589       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1590     }
1591   }
1592 }
1593
1594 void PartSet_SketcherMgr::customizePresentation(const ObjectPtr& theObject)
1595 {
1596   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1597                                                                            (getCurrentOperation());
1598   if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1599                       PartSet_SketcherMgr::isNestedSketchOperation(aFOperation)))
1600     SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
1601
1602   // update entities selection priorities
1603   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1604   if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1605     // update priority for feature
1606     updateSelectionPriority(aFeature, aFeature);
1607     // update priority for results of the feature
1608     std::list<ResultPtr> aResults = aFeature->results();
1609     std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLastIt = aResults.end();
1610     for (; anIt != aLastIt; anIt++)
1611       updateSelectionPriority(*anIt, aFeature);
1612   }
1613 }
1614
1615 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1616 {
1617   return myModule->workshop()->currentOperation();
1618 }
1619
1620 //**************************************************************
1621 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1622 {
1623   ModuleBase_ModelWidget* aWidget = 0;
1624   ModuleBase_Operation* anOperation = getCurrentOperation();
1625   if (anOperation) {
1626     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1627     if (aPanel)
1628       aWidget = aPanel->activeWidget();
1629   }
1630   return aWidget;
1631 }
1632
1633 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1634                                            const bool isEditOperation,
1635                                            const bool isToDisplay,
1636                                            const bool isFlushRedisplay)
1637 {
1638   #ifdef DEBUG_DO_NOT_BY_ENTER
1639   return;
1640   #endif
1641
1642   if (isEditOperation || !theFeature.get())
1643     return;
1644
1645   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1646   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1647
1648   // 1. change visibility of the object itself, here the presentable object is processed,
1649   // e.g. constraints features
1650   //FeaturePtr aFeature = aFOperation->feature();
1651   std::list<ResultPtr> aResults = theFeature->results();
1652   if (isToDisplay)
1653     theFeature->setDisplayed(true);
1654   else
1655     theFeature->setDisplayed(false);
1656
1657   // change visibility of the object results, e.g. non-constraint features
1658   std::list<ResultPtr>::const_iterator aIt;
1659   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1660     if (isToDisplay) {
1661       (*aIt)->setDisplayed(true);
1662     }
1663     else {
1664       (*aIt)->setDisplayed(false);
1665     }
1666   }
1667   if (isFlushRedisplay)
1668     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1669 }
1670
1671 void PartSet_SketcherMgr::storeSelection(const bool theHighlightedOnly)
1672 {
1673   if (!myCurrentSketch.get())
1674     return;
1675
1676   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1677   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1678   QList<ModuleBase_ViewerPrsPtr> aHighlighted = aSelect->getHighlighted();
1679
1680   QList<FeaturePtr> aFeatureList;
1681   if (theHighlightedOnly) {
1682     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1683   }
1684   else {
1685     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1686
1687     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(ModuleBase_ISelection::AllControls);
1688     fillFeatureList(aSelected, myCurrentSketch, aFeatureList);
1689   }
1690
1691   // 1. it is necessary to save current selection in order to restore it after the features moving
1692   myCurrentSelection.clear();
1693   QList<FeaturePtr>::const_iterator anIt = aFeatureList.begin(), aLast = aFeatureList.end();
1694   for (; anIt != aLast; anIt++) {
1695     getCurrentSelection(*anIt, myCurrentSketch, aWorkshop, myCurrentSelection);
1696   }
1697   //qDebug(QString("  storeSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1698 }
1699
1700 void PartSet_SketcherMgr::restoreSelection()
1701 {
1702   if (!myCurrentSketch.get())
1703     return;
1704
1705   //qDebug(QString("restoreSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1706   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1707   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1708   FeatureToSelectionMap::const_iterator aSIt = myCurrentSelection.begin(),
1709                                         aSLast = myCurrentSelection.end();
1710   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1711   for (; aSIt != aSLast; aSIt++) {
1712     anOwnersToSelect.Clear();
1713     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, myCurrentSelection,
1714                         anOwnersToSelect);
1715     aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1716   }
1717 }
1718
1719 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
1720 {
1721   PartSet_Tools::ConstraintVisibleState aType = (PartSet_Tools::ConstraintVisibleState)theType;
1722
1723   updateBySketchParameters(aType, theState);
1724 }
1725
1726 void PartSet_SketcherMgr::updateBySketchParameters(
1727                                    const PartSet_Tools::ConstraintVisibleState& theType,
1728                                    bool theState)
1729 {
1730   if (myCurrentSketch.get() == NULL)
1731     return;
1732
1733   bool aPrevState = myIsConstraintsShown[theType];
1734   myIsConstraintsShown[theType] = theState;
1735
1736   switch (theType) {
1737     case PartSet_Tools::Geometrical:
1738     case PartSet_Tools::Dimensional: {
1739       if (aPrevState != theState) {
1740         ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1741         XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1742         for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1743           FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1744           bool aProcessed = false;
1745           bool aConstraintDisplayed = canDisplayConstraint(aSubFeature, theType, aProcessed);
1746           if (aProcessed)
1747             aSubFeature->setDisplayed(aConstraintDisplayed);
1748         }
1749         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1750       }
1751     }
1752     break;
1753     case PartSet_Tools::Expressions: {
1754       if (aPrevState != theState) {
1755         /// call all sketch features redisplay, the expression state will be corrected in customize
1756         /// of distance presentation
1757         Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1758         PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
1759       }
1760     }
1761     break;
1762   }
1763 }
1764
1765 void PartSet_SketcherMgr::updateSelectionPriority(ObjectPtr theObject,
1766                                                   FeaturePtr theFeature)
1767 {
1768   if (!theObject.get() || !theFeature.get())
1769     return;
1770
1771   AISObjectPtr anAIS = workshop()->displayer()->getAISObject(theObject);
1772   Handle(AIS_InteractiveObject) anAISIO;
1773   if (anAIS.get() != NULL) {
1774     anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1775   }
1776
1777   if (!anAISIO.IsNull()) { // the presentation for the object is visualized
1778     int anAdditionalPriority = 0;
1779     // current feature
1780     std::shared_ptr<SketchPlugin_Feature> aSPFeature =
1781             std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
1782     if (aSPFeature.get() != NULL) {
1783       // 1. Vertices
1784       // 2. Simple segments
1785       // 3. External objects (violet color)
1786       // 4. Auxiliary segments (dotted)
1787       // StdSelect_BRepSelectionTool::Load uses priority calculating:
1788       // Standard_Integer aPriority = (thePriority == -1) ? GetStandardPriority (theShape, theType) : thePriority;
1789       // Priority of Vertex is 8, edge(segment) is 7.
1790       // It might be not corrected as provides the condition above.
1791       bool isExternal = aSPFeature->isExternal();
1792       bool isAuxiliary = PartSet_Tools::isAuxiliarySketchEntity(aSPFeature);
1793       // current feature
1794       if (!isExternal && !isAuxiliary)
1795         anAdditionalPriority = 30;
1796       // external feature
1797       if (isExternal)
1798         anAdditionalPriority = 20;
1799       // auxiliary feature
1800       if (isAuxiliary) {
1801         anAdditionalPriority = 10; /// auxiliary objects should have less priority that
1802         // edges/vertices of local selection on not-sketch objects
1803       }
1804       Handle(ModuleBase_ResultPrs) aResult = Handle(ModuleBase_ResultPrs)::DownCast(anAISIO);
1805       if (!aResult.IsNull()) {
1806         aResult->setAdditionalSelectionPriority(anAdditionalPriority);
1807       }
1808     }
1809   }
1810 }
1811
1812 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
1813 {
1814   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1815   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1816   return aConnector->workshop();
1817 }
1818
1819 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1820 {
1821   return workshop()->operationMgr();
1822 }
1823