Salome HOME
Reset value state is provided in ModelWidget to remove 'myIsResetCurrentValue' in...
[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_Module.h"
9 #include "PartSet_WidgetPoint2d.h"
10 #include "PartSet_WidgetPoint2dDistance.h"
11 #include "PartSet_Tools.h"
12 #include "PartSet_WidgetSketchLabel.h"
13
14 #include <XGUI_ModuleConnector.h>
15 #include <XGUI_Displayer.h>
16 #include <XGUI_Workshop.h>
17 #include <XGUI_ContextMenuMgr.h>
18 #include <XGUI_Selection.h>
19 #include <XGUI_SelectionMgr.h>
20 #include <XGUI_ModuleConnector.h>
21 #include <XGUI_PropertyPanel.h>
22 #include <XGUI_ViewerProxy.h>
23 #include <XGUI_OperationMgr.h>
24
25 #include <ModuleBase_IPropertyPanel.h>
26 #include <ModuleBase_ISelection.h>
27 #include <ModuleBase_IViewer.h>
28 #include <ModuleBase_IWorkshop.h>
29 #include <ModuleBase_IViewWindow.h>
30 #include <ModuleBase_ModelWidget.h>
31 #include <ModuleBase_Operation.h>
32 #include <ModuleBase_OperationFeature.h>
33 #include <ModuleBase_Operation.h>
34 #include <ModuleBase_WidgetEditor.h>
35
36 #include <GeomDataAPI_Point2D.h>
37
38 #include <Events_Loop.h>
39
40 #include <SketchPlugin_Line.h>
41 #include <SketchPlugin_Sketch.h>
42 #include <SketchPlugin_Point.h>
43 #include <SketchPlugin_Arc.h>
44 #include <SketchPlugin_Circle.h>
45 #include <SketchPlugin_ConstraintLength.h>
46 #include <SketchPlugin_ConstraintDistance.h>
47 #include <SketchPlugin_ConstraintParallel.h>
48 #include <SketchPlugin_ConstraintPerpendicular.h>
49 #include <SketchPlugin_ConstraintRadius.h>
50 #include <SketchPlugin_ConstraintRigid.h>
51 #include <SketchPlugin_ConstraintHorizontal.h>
52 #include <SketchPlugin_ConstraintVertical.h>
53 #include <SketchPlugin_ConstraintEqual.h>
54 #include <SketchPlugin_ConstraintTangent.h>
55 #include <SketchPlugin_ConstraintCoincidence.h>
56 #include <SketchPlugin_ConstraintFillet.h>
57 #include <SketchPlugin_ConstraintMirror.h>
58 #include <SketchPlugin_ConstraintAngle.h>
59 #include <SketchPlugin_MultiRotation.h>
60 #include <SketchPlugin_MultiTranslation.h>
61
62 #include <SketcherPrs_Tools.h>
63
64 #include <SelectMgr_IndexedMapOfOwner.hxx>
65 #include <StdSelect_BRepOwner.hxx>
66
67 //#include <AIS_DimensionSelectionMode.hxx>
68 #include <AIS_Shape.hxx>
69
70 #include <ModelAPI_Events.h>
71 #include <ModelAPI_Session.h>
72 #include <ModelAPI_AttributeString.h>
73
74 #include <QMouseEvent>
75 #include <QApplication>
76
77 //#define DEBUG_DO_NOT_BY_ENTER
78 //#define DEBUG_MOUSE_OVER_WINDOW_FLAGS
79
80 /// Returns list of unique objects by sum of objects from List1 and List2
81 /*QList<ModuleBase_ViewerPrs> getSumList(const QList<ModuleBase_ViewerPrs>& theList1,
82                                        const QList<ModuleBase_ViewerPrs>& theList2)
83 {
84   QList<ModuleBase_ViewerPrs> aRes;
85   foreach (ModuleBase_ViewerPrs aPrs, theList1) {
86     if (!aRes.contains(aPrs))
87       aRes.append(aPrs);
88   }
89   foreach (ModuleBase_ViewerPrs aPrs, theList2) {
90     if (!aRes.contains(aPrs))
91       aRes.append(aPrs);
92   }
93   return aRes;
94 }*/
95
96 // Fills the list of features the list of selected presentations.
97 // \param theList a list of selected presentations
98 // \param theSketch a sketch to project a vertex shape of a presentation to the plane
99 // and find the corresponded attribute
100 // \param theFeatureList  an output list of features
101 void fillFeatureList(const QList<ModuleBase_ViewerPrs>& theList,
102                      const FeaturePtr theSketch,
103                      QList<FeaturePtr>& theFeatureList)
104 {
105   QList<ModuleBase_ViewerPrs> aRes;
106
107   QList<ModuleBase_ViewerPrs>::const_iterator anIt = theList.begin(),
108                                               aLast = theList.end();
109   for (; anIt != aLast; anIt++)
110   {
111     ModuleBase_ViewerPrs aPrs = *anIt;
112     FeaturePtr aFeature = ModelAPI_Feature::feature(aPrs.object());
113     if (aFeature.get()  && !theFeatureList.contains(aFeature))
114       theFeatureList.append(aFeature);
115   }
116 }
117
118 /// Fills attribute and result lists by the selected owner. In case if the attribute is found,
119 /// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge, put the function
120 /// result as is to the list of results.
121 /// \param theOwner a viewer selected owner
122 /// \param theFeature a feature, where the attribute is searched
123 /// \param theSketch a current sketch
124 /// \param theSelectedAttribute an output list of attributes
125 /// \param theSelectedResults an output list of edge results
126 void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
127                             const FeaturePtr& theFeature, const FeaturePtr& theSketch,
128                             const ResultPtr& theResult,
129                             std::set<AttributePtr>& aSelectedAttributes,
130                             std::set<ResultPtr>& aSelectedResults)
131 {
132   Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(theOwner);
133   if (aBRepOwner.IsNull())
134     return;
135   Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(
136                                                                     aBRepOwner->Selectable());
137   if (aBRepOwner->HasShape()) {
138     const TopoDS_Shape& aShape = aBRepOwner->Shape();
139     TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
140     if (aShapeType == TopAbs_VERTEX) {
141       AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature,
142                                                                     aShape, theSketch);
143       if (aPntAttr.get() != NULL)
144         aSelectedAttributes.insert(aPntAttr);
145     }
146     else if (aShapeType == TopAbs_EDGE &&
147              aSelectedResults.find(theResult) == aSelectedResults.end()) {
148       aSelectedResults.insert(theResult);
149     }
150   }
151 }
152
153 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
154   : QObject(theModule), myModule(theModule), myIsDragging(false), myDragDone(false),
155     /*myIsResetCurrentValue(false), */myIsMouseOverWindow(false),
156     myIsMouseOverViewProcessed(true), myPreviousUpdateViewerEnabled(true),
157     myIsPopupMenuActive(false), myIsConstraintsShown(true)
158 {
159   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
160   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
161
162   myPreviousDrawModeEnabled = true;//aViewer->isSelectionEnabled();
163
164   connect(aViewer, SIGNAL(mousePress(ModuleBase_IViewWindow*, QMouseEvent*)),
165           this, SLOT(onMousePressed(ModuleBase_IViewWindow*, QMouseEvent*)));
166
167   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)),
168           this, SLOT(onMouseReleased(ModuleBase_IViewWindow*, QMouseEvent*)));
169
170   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
171           this, SLOT(onMouseMoved(ModuleBase_IViewWindow*, QMouseEvent*)));
172
173   connect(aViewer, SIGNAL(mouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)),
174           this, SLOT(onMouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)));
175
176   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
177   XGUI_Workshop* aWorkshop = aConnector->workshop();
178   connect(aWorkshop, SIGNAL(applicationStarted()), this, SLOT(onApplicationStarted()));
179 }
180
181 PartSet_SketcherMgr::~PartSet_SketcherMgr()
182 {
183   if (!myPlaneFilter.IsNull())
184     myPlaneFilter.Nullify();
185 }
186
187 void PartSet_SketcherMgr::onEnterViewPort()
188 {
189   // 1. if the mouse over window, update the next flag. Do not perform update visibility of
190   // created feature because it should be done in onMouseMove(). Some widgets watch
191   // the mouse move and use the cursor position to update own values. If the presentaion is
192   // redisplayed before this update, the feature presentation jumps from reset value to current.
193   myIsMouseOverWindow = true;
194   //myIsResetCurrentValue = false;
195   //myIsCurrentValueUnderModification = false;
196   // it is important to validate operation here only if sketch entity create operation is active
197   // because at this operation we reacts to the mouse leave/enter view port
198   //operationMgr()->onValidateOperation();
199 #ifdef DEBUG_MOUSE_OVER_WINDOW_FLAGS
200   qDebug(QString("onEnterViewPort: %1").arg(mouseOverWindowFlagsInfo()).toStdString().c_str());
201 #endif
202
203   #ifdef DEBUG_DO_NOT_BY_ENTER
204   return;
205   #endif
206
207   if (!isNestedCreateOperation(getCurrentOperation()))
208     return;
209
210   QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));//QIcon(":pictures/button_plus.png").pixmap(20,20)));
211
212   operationMgr()->onValidateOperation();
213
214   // we need change displayed state of the current operation feature
215   // if the feature is presentable, e.g. distance construction. It has no results, so workshop does
216   // not accept a signal about the result created. Nothing is shown until mouse is moved out/in view
217   // port. If the isDisplayed flag is true, the presentable feature is displayed as soon as the
218   // presentation becomes valid and redisplay happens
219   //ModuleBase_Operation* aOperation = getCurrentOperation();
220   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
221                                                                            (getCurrentOperation());
222   if (aFOperation) {
223     FeaturePtr aFeature = aFOperation->feature();
224     if (aFeature.get() && aFeature->data()->isValid()) {
225       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature), false);
226     }
227   }
228 }
229
230 void PartSet_SketcherMgr::onLeaveViewPort()
231 {
232   myIsMouseOverViewProcessed = false;
233   myIsMouseOverWindow = false;
234   // it is important to validate operation here only if sketch entity create operation is active
235   // because at this operation we reacts to the mouse leave/enter view port
236   //operationMgr()->onValidateOperation();
237 #ifdef DEBUG_MOUSE_OVER_WINDOW_FLAGS
238   qDebug(QString("onLeaveViewPort: %1").arg(mouseOverWindowFlagsInfo()).toStdString().c_str());
239 #endif
240
241   #ifdef DEBUG_DO_NOT_BY_ENTER
242   return;
243   #endif
244
245   if (!isNestedCreateOperation(getCurrentOperation()))
246     return;
247
248   QApplication::restoreOverrideCursor();
249
250   // the method should be performed if the popup menu is called,
251   // the reset of the current widget should not happen
252   if (myIsPopupMenuActive)
253     return;
254
255   operationMgr()->onValidateOperation();
256
257   // 2. if the mouse IS NOT over window, reset the active widget value and hide the presentation
258   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
259   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
260   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
261   // disable the viewer update in order to avoid visualization of redisplayed feature in viewer
262   // obtained after reset value
263   bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
264   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
265   if (anActiveWidget && anActiveWidget->reset()) {
266     //myIsResetCurrentValue = true;
267   }
268   aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
269
270   // hides the presentation of the current operation feature
271   // the feature is to be erased here, but it is correct to call canDisplayObject because
272   // there can be additional check (e.g. editor widget in distance constraint)
273   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
274                                                                            (getCurrentOperation());
275   if (aFOperation) {
276     FeaturePtr aFeature = aFOperation->feature();
277     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
278   }
279 }
280
281 void PartSet_SketcherMgr::onValueStateChanged()
282 {
283   ///myIsCurrentValueUnderModification = true;
284   // update Apply enable state
285   //myIsResetCurrentValue = false;
286   //if (!isNestedCreateOperation(getCurrentOperation()))
287   //  return;
288
289   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
290   if (anActiveWidget && anActiveWidget->getValueState() != ModuleBase_ModelWidget::Stored)
291     operationMgr()->onValidateOperation();
292 }
293
294 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
295 {
296   //myIsResetCurrentValue = false;
297   //myIsCurrentValueUnderModification = false;
298
299   if (isNestedCreateOperation(getCurrentOperation()))
300     return;
301   // it is necessary to save current selection in order to restore it after the values are modifed
302   storeSelection();
303
304   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
305   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
306   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
307   myPreviousUpdateViewerEnabled = aDisplayer->enableUpdateViewer(false);
308 }
309
310 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
311 {
312   if (isNestedCreateOperation(getCurrentOperation()))
313     return;
314   // it is necessary to restore current selection in order to restore it after the values are modified
315   restoreSelection();
316   myCurrentSelection.clear();
317
318   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
319   // viewer happens by deselect/select the modified objects. The flag should be restored after
320   // the selection processing. The update viewer should be also called.
321   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
322   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
323   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
324   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
325   aDisplayer->updateViewer();
326 }
327
328 void PartSet_SketcherMgr::onValuesChangedInPropertyPanel()
329 {
330   if (!isNestedCreateOperation(getCurrentOperation()))
331     return;
332
333   // visualize the current operation feature
334   //myIsResetCurrentValue = false;
335   operationMgr()->onValidateOperation();
336   // the feature is to be erased here, but it is correct to call canDisplayObject because
337   // there can be additional check (e.g. editor widget in distance constraint)
338   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
339                                                                            (getCurrentOperation());
340   if (aFOperation) {
341     FeaturePtr aFeature = aFOperation->feature();
342     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
343   }
344 }
345
346 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
347 {
348   get2dPoint(theWnd, theEvent, myClickedPoint);
349
350   if (!(theEvent->buttons() & Qt::LeftButton))
351     return;
352
353   // Clear dragging mode
354   myIsDragging = false;
355
356   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
357   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
358   if (!aViewer->canDragByMouse())
359     return;
360
361   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
362                                                                (getCurrentOperation());
363   if (!aFOperation)
364     return;
365
366   if (aFOperation->isEditOperation()) {
367     // If the current widget is a selector, do nothing, it processes the mouse press
368     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
369     if(anActiveWidget && anActiveWidget->isViewerSelector()) {
370       return;
371     }
372   }
373
374   // Use only for sketch operations
375   if (myCurrentSketch) {
376     if (!PartSet_Tools::sketchPlane(myCurrentSketch))
377       return;
378
379     bool isSketcher = isSketchOperation(aFOperation);
380     bool isSketchOpe = isNestedSketchOperation(aFOperation);
381
382     // Avoid non-sketch operations
383     if ((!isSketchOpe) && (!isSketcher))
384       return;
385
386     bool isEditing = aFOperation->isEditOperation();
387
388     // Ignore creation sketch operation
389     if ((!isSketcher) && (!isEditing))
390       return;
391
392     Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
393     if (!aContext.IsNull()) {
394       // MoveTo in order to highlight current object
395       aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
396     }
397     // Remember highlighted objects for editing
398     ModuleBase_ISelection* aSelect = aWorkshop->selection();
399
400     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
401     storeSelection(!aHasShift);
402
403     if (myCurrentSelection.empty()) {
404       if (isSketchOpe && (!isSketcher))
405         // commit previous operation
406         if (!aFOperation->commit())
407           aFOperation->abort();
408       return;
409     }
410     // Init flyout point for radius rotation
411     FeaturePtr aFeature = myCurrentSelection.begin().key();
412
413     if (isSketcher) {
414       myIsDragging = true;
415       get2dPoint(theWnd, theEvent, myCurrentPoint);
416       myDragDone = false;
417       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
418       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
419       launchEditing();
420       if (aFeature.get() != NULL) {
421         std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
422                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
423       if (aSPFeature.get() && aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID()) {
424           DataPtr aData = aSPFeature->data();
425           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
426           std::shared_ptr<GeomDataAPI_Point2D> aFPAttr = 
427             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
428           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
429         }
430       }
431     } else if (isSketchOpe && isEditing) {
432       // If selected another object commit current result
433       aFOperation->commit();
434
435       myIsDragging = true;
436       get2dPoint(theWnd, theEvent, myCurrentPoint);
437       myDragDone = false;
438       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
439       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
440
441       // This is necessary in order to finalize previous operation
442       QApplication::processEvents();
443       launchEditing();
444     }
445   }
446 }
447
448 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
449 {
450   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
451   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
452   if (!aViewer->canDragByMouse())
453     return;
454   ModuleBase_Operation* aOp = getCurrentOperation();
455   if (aOp) {
456     if (isNestedSketchOperation(aOp)) {
457       get2dPoint(theWnd, theEvent, myClickedPoint);
458
459       // Only for sketcher operations
460       if (myIsDragging) {
461         if (myDragDone) {
462           //aOp->commit();
463           myCurrentSelection.clear();
464           /*Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
465           if (!aContext.IsNull()) {
466           // Reselect edited object
467           aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
468           if (theEvent->modifiers() & Qt::ShiftModifier)
469             aContext->ShiftSelect();
470           else
471             aContext->Select();
472           */
473         }
474       }
475     }
476   }
477       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
478   aWorkshop->viewer()->enableDrawMode(myPreviousDrawModeEnabled);
479   //aWorkshop->viewer()->enableSelection(myPreviousDrawModeEnabled);
480   myIsDragging = false;
481 }
482
483 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
484 {
485   if (isNestedCreateOperation(getCurrentOperation()) && !myIsMouseOverViewProcessed) {
486     myIsMouseOverViewProcessed = true;
487     // 1. perform the widget mouse move functionality and display the presentation
488     // the mouse move should be processed in the widget, if it can in order to visualize correct
489     // presentation. These widgets correct the feature attribute according to the mouse position
490     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
491     PartSet_WidgetPoint2D* aPoint2DWdg = dynamic_cast<PartSet_WidgetPoint2D*>(anActiveWidget);
492     if (aPoint2DWdg) {
493       aPoint2DWdg->onMouseMove(theWnd, theEvent);
494     }
495     PartSet_WidgetPoint2dDistance* aDistanceWdg = dynamic_cast<PartSet_WidgetPoint2dDistance*>
496                                                                 (anActiveWidget);
497     if (aDistanceWdg) {
498       aDistanceWdg->onMouseMove(theWnd, theEvent);
499     }
500     // the feature is to be erased here, but it is correct to call canDisplayObject because
501     // there can be additional check (e.g. editor widget in distance constraint)
502     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
503                                                                              (getCurrentOperation());
504     if (aFOperation) {
505       FeaturePtr aFeature = aFOperation->feature();
506       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
507     }
508   }
509
510   myClickedPoint.clear();
511
512   if (myIsDragging) {
513     // 1. the current selection is saved in the mouse press method in order to restore it after moving
514     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
515     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
516     // deselected). This flag should be restored in the slot, processed the mouse release signal.
517
518     // TODO: Has to be commented out when SALOME patch on draw mode become avialable
519     //ModuleBase_IViewer* aViewer = myModule->workshop()->viewer();
520     //aViewer->enableSelection(false);
521
522     ModuleBase_Operation* aCurrentOperation = getCurrentOperation();
523     if (!aCurrentOperation)
524       return;
525     if (isSketchOperation(aCurrentOperation))
526       return; // No edit operation activated
527
528     Handle(V3d_View) aView = theWnd->v3dView();
529     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
530     double aX, aY;
531     PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, aY);
532     double dX =  aX - myCurrentPoint.myCurX;
533     double dY =  aY - myCurrentPoint.myCurY;
534
535     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
536     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
537     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
538     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
539     // viewer happens by deselect/select the modified objects. The flag should be restored after
540     // the selection processing. The update viewer should be also called.
541     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
542
543     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
544     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
545     FeatureToSelectionMap::const_iterator anIt = myCurrentSelection.begin(),
546                                           aLast = myCurrentSelection.end();
547     // 4. the features and attributes modification(move)
548     bool isModified = false;
549     for (; anIt != aLast; anIt++) {
550       FeaturePtr aFeature = anIt.key();
551
552       std::set<AttributePtr> anAttributes = anIt.value().first;
553       // Process selection by attribute: the priority to the attribute
554       if (!anAttributes.empty()) {
555         std::set<AttributePtr>::const_iterator anAttIt = anAttributes.begin(),
556                                                anAttLast = anAttributes.end();
557         for (; anAttIt != anAttLast; anAttIt++) {
558           AttributePtr anAttr = *anAttIt;
559           if (anAttr.get() == NULL)
560             continue;
561           std::string aAttrId = anAttr->id();
562           DataPtr aData = aFeature->data();
563           if (aData->isValid()) {
564             std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
565               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
566             if (aPoint.get() != NULL) {
567               bool isImmutable = aPoint->setImmutable(true);
568               aPoint->move(dX, dY);
569               isModified = true;
570               ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
571               aPoint->setImmutable(isImmutable);
572             }
573           }
574         }
575       } else {
576         // Process selection by feature
577         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
578           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
579         if (aSketchFeature) {
580           aSketchFeature->move(dX, dY);
581           isModified = true;
582           ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
583         }
584       }
585     }
586     // the modified state of the current operation should be updated if there are features, which
587     // were changed here
588     if (isModified) {
589       aCurrentOperation->onValuesChanged();
590     }
591     Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
592     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
593
594     // 5. it is necessary to save current selection in order to restore it after the features moving
595     restoreSelection();
596     // 6. restore the update viewer flag and call this update
597     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
598     aDisplayer->updateViewer();
599
600     myDragDone = true;
601     myCurrentPoint.setValue(aX, aY);
602   }
603 }
604
605 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
606 {
607   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
608                                                                (getCurrentOperation());
609   if (aFOperation && aFOperation->isEditOperation()) {
610     std::string aId = aFOperation->id().toStdString();
611     if (isDistanceOperation(aFOperation))
612     {
613       // Activate dimension value editing on double click
614       ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
615       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
616       // Find corresponded widget to activate value editing
617       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
618         if (aWgt->attributeID() == "ConstraintValue") {
619           aWgt->focusTo();
620           return;
621         }
622       }
623     }
624   }
625 }
626
627 void PartSet_SketcherMgr::onApplicationStarted()
628 {
629   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
630   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
631   XGUI_Workshop* aWorkshop = aConnector->workshop();
632   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
633   if (aPropertyPanel) {
634     connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
635             this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
636   }
637
638   XGUI_ViewerProxy* aViewerProxy = aWorkshop->viewer();
639   connect(aViewerProxy, SIGNAL(enterViewPort()), this, SLOT(onEnterViewPort()));
640   connect(aViewerProxy, SIGNAL(leaveViewPort()), this, SLOT(onLeaveViewPort()));
641
642   XGUI_ContextMenuMgr* aContextMenuMgr = aWorkshop->contextMenuMgr();
643   connect(aContextMenuMgr, SIGNAL(beforeContextMenu()), this, SLOT(onBeforeContextMenu()));
644   connect(aContextMenuMgr, SIGNAL(afterContextMenu()), this, SLOT(onAfterContextMenu()));
645 }
646
647 void PartSet_SketcherMgr::onBeforeWidgetActivated(ModuleBase_ModelWidget* theWidget)
648 {
649   if (!myClickedPoint.myIsInitialized)
650     return;
651
652   ModuleBase_Operation* aOperation = getCurrentOperation();
653   // the distance constraint feature should not use the clickedd point
654   // this is workaround in order to don't throw down the flyout point value,
655   // set by execute() method of these type of features
656   if (isDistanceOperation(aOperation))
657     return;
658
659   PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(theWidget);
660   if (aPnt2dWgt) {
661     aPnt2dWgt->setPoint(myClickedPoint.myCurX, myClickedPoint.myCurY);
662   }
663 }
664
665 void PartSet_SketcherMgr::onBeforeContextMenu()
666 {
667   myIsPopupMenuActive = true;
668 }
669
670 void PartSet_SketcherMgr::onAfterContextMenu()
671 {
672   myIsPopupMenuActive = false;
673 }
674
675 void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent, 
676                                      Point& thePoint)
677 {
678   Handle(V3d_View) aView = theWnd->v3dView();
679   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
680   double aX, anY;
681   PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, anY);
682   thePoint.setValue(aX, anY);
683 }
684
685 void PartSet_SketcherMgr::launchEditing()
686 {
687   if (!myCurrentSelection.empty()) {
688     FeaturePtr aFeature = myCurrentSelection.begin().key();
689     std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
690               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
691     if (aSPFeature) {
692       myModule->editFeature(aSPFeature);
693     }
694   }
695 }
696
697 bool PartSet_SketcherMgr::sketchSolverError()
698 {
699   bool anError = false;
700   CompositeFeaturePtr aSketch = activeSketch();
701   if (aSketch.get()) {
702     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
703     anError = !aAttributeString->value().empty();
704   }
705   return anError;
706 }
707
708 QString PartSet_SketcherMgr::getFeatureError(const FeaturePtr& theFeature)
709 {
710   QString anError = "";
711   if (!theFeature.get() || !theFeature->data()->isValid())
712     return anError;
713
714   CompositeFeaturePtr aSketch = activeSketch();
715   if (aSketch.get() && aSketch == theFeature) {
716     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
717     anError = aAttributeString->value().c_str();
718   }
719   /*else if (myIsResetCurrentValue /*|| myIsCurrentValueUnderModification*+/) {
720     // this flags do not allow commit of the current operation
721     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
722                                                                         (getCurrentOperation());
723     if (aFOperation) {
724       FeaturePtr aFeature = aFOperation->feature();
725       if (aFeature.get() && aFeature == theFeature && isNestedCreateOperation(aFOperation)) {
726         QString anAttributeName = "";
727         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
728         if (anActiveWidget) {
729           AttributePtr anAttr = aFeature->attribute(anActiveWidget->attributeID());
730           if (anAttr.get())
731             anAttributeName = anAttr->id().c_str();
732         }
733         if (myIsResetCurrentValue)
734           anError = "Attribute \"" + anAttributeName + "\" is not initialized.";
735         //else if (myIsCurrentValueUnderModification) {
736         //  anError = "Attribute \"" + anAttributeName + "\" modification is not applyed. Please click \"Enter\" or \"Tab\".";
737         //}
738       }
739     }
740   }*/
741   else {
742     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
743     if (anActiveWidget) {
744       ModuleBase_ModelWidget::ValueState aState = anActiveWidget->getValueState();
745       if (aState != ModuleBase_ModelWidget::Stored) {
746         AttributePtr anAttr = anActiveWidget->feature()->attribute(anActiveWidget->attributeID());
747         if (anAttr.get()) {
748           QString anAttributeName = anAttr->id().c_str();
749           switch (aState) {
750             case ModuleBase_ModelWidget::Modified:
751               anError = "Attribute \"" + anAttributeName +
752                         "\" modification is not applyed. Please click \"Enter\" or \"Tab\".";
753               break;
754             case ModuleBase_ModelWidget::Reset:
755               anError = "Attribute \"" + anAttributeName + "\" is not initialized.";
756               break;
757           }
758         }
759       }
760     }
761   }
762   return anError;
763 }
764
765 const QStringList& PartSet_SketcherMgr::sketchOperationIdList()
766 {
767   static QStringList aIds;
768   if (aIds.size() == 0) {
769     aIds << SketchPlugin_Line::ID().c_str();
770     aIds << SketchPlugin_Point::ID().c_str();
771     aIds << SketchPlugin_Arc::ID().c_str();
772     aIds << SketchPlugin_Circle::ID().c_str();
773     aIds << SketchPlugin_ConstraintFillet::ID().c_str();
774     aIds.append(constraintsIdList());
775   }
776   return aIds;
777 }
778
779 const QStringList& PartSet_SketcherMgr::constraintsIdList()
780 {
781   static QStringList aIds;
782   if (aIds.size() == 0) {
783     aIds << SketchPlugin_ConstraintLength::ID().c_str();
784     aIds << SketchPlugin_ConstraintDistance::ID().c_str();
785     aIds << SketchPlugin_ConstraintRigid::ID().c_str();
786     aIds << SketchPlugin_ConstraintRadius::ID().c_str();
787     aIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
788     aIds << SketchPlugin_ConstraintParallel::ID().c_str();
789     aIds << SketchPlugin_ConstraintHorizontal::ID().c_str();
790     aIds << SketchPlugin_ConstraintVertical::ID().c_str();
791     aIds << SketchPlugin_ConstraintEqual::ID().c_str();
792     aIds << SketchPlugin_ConstraintTangent::ID().c_str();
793     aIds << SketchPlugin_ConstraintCoincidence::ID().c_str();
794     aIds << SketchPlugin_ConstraintMirror::ID().c_str();
795     aIds << SketchPlugin_ConstraintAngle::ID().c_str();
796     aIds << SketchPlugin_MultiRotation::ID().c_str();
797     aIds << SketchPlugin_MultiTranslation::ID().c_str();
798   }
799   return aIds;
800 }
801
802 void PartSet_SketcherMgr::sketchSelectionModes(QIntList& theModes)
803 {
804   theModes.clear();
805
806   theModes.append(SketcherPrs_Tools::Sel_Dimension_Text);
807   theModes.append(SketcherPrs_Tools::Sel_Dimension_Line);
808   theModes.append(SketcherPrs_Tools::Sel_Constraint);
809   theModes.append(TopAbs_VERTEX);
810   theModes.append(TopAbs_EDGE);
811 }
812
813 bool PartSet_SketcherMgr::isSketchOperation(ModuleBase_Operation* theOperation)
814 {
815   return theOperation && theOperation->id().toStdString() == SketchPlugin_Sketch::ID();
816 }
817
818 bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation)
819 {
820   return theOperation &&
821          PartSet_SketcherMgr::sketchOperationIdList().contains(theOperation->id());
822 }
823
824 bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation)
825 {
826   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
827                                                                (theOperation);
828   return aFOperation && !aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
829 }
830
831 bool PartSet_SketcherMgr::isEntity(const std::string& theId)
832 {
833   return (theId == SketchPlugin_Line::ID()) ||
834          (theId == SketchPlugin_Point::ID()) ||
835          (theId == SketchPlugin_Arc::ID()) ||
836          (theId == SketchPlugin_Circle::ID());
837 }
838
839 bool PartSet_SketcherMgr::isDistanceOperation(ModuleBase_Operation* theOperation)
840 {
841   std::string aId = theOperation ? theOperation->id().toStdString() : "";
842
843   return (aId == SketchPlugin_ConstraintLength::ID()) ||
844          (aId == SketchPlugin_ConstraintDistance::ID()) ||
845          (aId == SketchPlugin_ConstraintRadius::ID()) ||
846          (aId == SketchPlugin_ConstraintAngle::ID());
847 }
848
849 void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
850 {
851   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
852                                                                (getCurrentOperation());
853   if (!aFOperation)
854     return;
855
856   myModule->onViewTransformed();
857
858   // Display all sketcher sub-Objects
859   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFOperation->feature());
860   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
861
862   // Hide sketcher result
863   std::list<ResultPtr> aResults = myCurrentSketch->results();
864   std::list<ResultPtr>::const_iterator aIt;
865   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
866     (*aIt)->setDisplayed(false);
867   }
868   myCurrentSketch->setDisplayed(false);
869
870   // Display sketcher objects
871   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
872     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
873     std::list<ResultPtr> aResults = aFeature->results();
874     std::list<ResultPtr>::const_iterator aIt;
875     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
876       (*aIt)->setDisplayed(true);
877     }
878     aFeature->setDisplayed(true);
879   }
880
881   if (myPlaneFilter.IsNull()) 
882     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
883
884   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
885
886   bool aHasPlane = false;
887   std::shared_ptr<GeomAPI_Pln> aPln;
888   if (aFOperation->isEditOperation()) {
889     // If it is editing of sketch then it means that plane is already defined
890     aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
891     if (aPln.get())
892       aHasPlane = true;
893   }
894   myPlaneFilter->setPlane(aPln);
895
896   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
897   // all sketch objects should be activated in the sketch selection modes by edit operation start
898   // in case of creation operation, there is an active widget, which activates own selection mode
899   if (aFOperation->isEditOperation() && aHasPlane)
900     aConnector->activateModuleSelectionModes();
901 }
902
903 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
904 {
905   myIsMouseOverWindow = false;
906   myIsConstraintsShown = true;
907 #ifdef DEBUG_MOUSE_OVER_WINDOW_FLAGS
908   qDebug(QString("stopSketch: %1").arg(mouseOverWindowFlagsInfo()).toStdString().c_str());
909 #endif
910   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
911
912   DataPtr aData = myCurrentSketch->data();
913   if (!aData->isValid()) {
914     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
915     // The sketch was aborted
916     myCurrentSketch = CompositeFeaturePtr();
917     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
918
919     // Erase all sketcher objects
920     QStringList aSketchIds = sketchOperationIdList();
921     QObjectPtrList aObjects = aDisplayer->displayedObjects();
922     foreach (ObjectPtr aObj, aObjects) {
923       DataPtr aObjData = aObj->data();
924       if (!aObjData->isValid())
925         aObj->setDisplayed(false);
926     }
927   }
928   else {
929     // Hide all sketcher sub-Objects
930     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
931       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
932       std::list<ResultPtr> aResults = aFeature->results();
933       std::list<ResultPtr>::const_iterator aIt;
934       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
935         (*aIt)->setDisplayed(false);
936       }
937       aFeature->setDisplayed(false);
938     }
939     // Display sketcher result
940     std::list<ResultPtr> aResults = myCurrentSketch->results();
941     std::list<ResultPtr>::const_iterator aIt;
942     Events_Loop* aLoop = Events_Loop::loop();
943     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
944
945     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
946                                                                            (theOperation);
947     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
948       if (!aFOperation->isDisplayedOnStart(*aIt)) {
949         (*aIt)->setDisplayed(true);
950         // this display event is needed because sketch already may have "displayed" state,
951         // but not displayed while it is still active (issue 613, abort of existing sketch)
952         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
953       }
954     }
955     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
956       myCurrentSketch->setDisplayed(true);
957     
958     myCurrentSketch = CompositeFeaturePtr();
959     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
960
961     Events_Loop::loop()->flush(aDispEvent);
962   }
963   // restore the module selection modes, which were changed on startSketch
964   aConnector->activateModuleSelectionModes();
965 }
966
967 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
968 {
969   connectToPropertyPanel(true);
970   if (isNestedCreateOperation(theOperation) && myIsMouseOverWindow)
971     QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));//QIcon(":pictures/button_plus.png").pixmap(20,20)));
972 }
973
974 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOp)
975 {
976   connectToPropertyPanel(false);
977   //myIsResetCurrentValue = false;
978   //myIsCurrentValueUnderModification = false;
979   myIsMouseOverViewProcessed = true;
980   operationMgr()->onValidateOperation();
981   if (isNestedCreateOperation(theOp))
982     QApplication::restoreOverrideCursor();
983 }
984
985 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
986 {
987   if (isNestedCreateOperation(theOperation)) {
988     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
989                                                                              (theOperation);
990     if (aFOperation) {
991       FeaturePtr aFeature = aFOperation->feature();
992       // it is necessary to check the the feature data validity because
993       // some kind of features are removed by an operation commit(the macro state of a feature)
994       if (aFeature.get() && aFeature->data()->isValid()) {
995         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
996       }
997     }
998   }
999 }
1000
1001 bool PartSet_SketcherMgr::canUndo() const
1002 {
1003   return isNestedCreateOperation(getCurrentOperation());
1004 }
1005
1006 bool PartSet_SketcherMgr::canRedo() const
1007 {
1008   return isNestedCreateOperation(getCurrentOperation());
1009 }
1010
1011 /*bool PartSet_SketcherMgr::canCommitOperation() const
1012 {
1013   bool aCanCommit = true;
1014
1015   if (isNestedCreateOperation(getCurrentOperation()) &&
1016       (myIsResetCurrentValue || myIsCurrentValueUnderModification))
1017     aCanCommit = false;
1018
1019   return aCanCommit;
1020 }*/
1021
1022 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1023 {
1024   bool aCanErase = true;
1025   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1026   if (myCurrentSketch.get()) {
1027     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1028     if (aResult.get()) {
1029       // Display sketcher objects
1030       for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1031
1032         FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1033         std::list<ResultPtr> aResults = aFeature->results();
1034         std::list<ResultPtr>::const_iterator anIt;
1035         for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1036           aCanErase = *anIt != aResult;
1037         }
1038       }
1039     }
1040   }
1041   return aCanErase;
1042 }
1043
1044 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1045 {
1046   bool aCanDisplay = true;
1047
1048   bool aHasActiveSketch = activeSketch().get() != NULL;
1049   if (aHasActiveSketch) {
1050     // 1. the sketch feature should not be displayed during the sketch active operation
1051     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch 
1052     // nested features can be visualized
1053     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1054     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1055       aCanDisplay = false;
1056     }
1057   }
1058   else { // there are no an active sketch
1059     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1060     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1061     if (aFeature.get() != NULL) {
1062       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1063                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1064       if (aSketchFeature.get()) {
1065         aCanDisplay = false;
1066       }
1067     }
1068   }
1069
1070   // 3. the method should not filter the objects, which are not related to the current operation.
1071   // The object is filtered just if it is a current operation feature or this feature result
1072   bool isObjectFound = false;
1073   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1074                                                                (getCurrentOperation());
1075   if (aFOperation) {
1076     FeaturePtr aFeature = aFOperation->feature();
1077     if (aFeature.get()) {
1078       std::list<ResultPtr> aResults = aFeature->results();
1079       if (theObject == aFeature)
1080         isObjectFound = true;
1081       else {
1082         std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1083         for (; anIt != aLast && !isObjectFound; anIt++) {
1084           isObjectFound = *anIt == theObject;
1085         }
1086       }
1087     }
1088   }
1089   if (!isObjectFound) 
1090     return aCanDisplay;
1091   
1092   // 4. For created nested feature operation do not display the created feature if
1093   // the mouse curstor leaves the OCC window.
1094   // The correction cases, which ignores this condition:
1095   // a. the property panel values modification
1096   // b. the popup menu activated
1097   // c. widget editor control
1098   #ifndef DEBUG_DO_NOT_BY_ENTER
1099   if (aCanDisplay && isNestedCreateOperation(getCurrentOperation())) {
1100     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1101     ModuleBase_WidgetEditor* anEditorWdg = anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1102     // the active widget editor should not influence here. The presentation should be visible always
1103     // when this widget is active.
1104     if (!anEditorWdg && !myIsPopupMenuActive) {
1105       // during a nested create operation, the feature is redisplayed only if the mouse over view
1106       // of there was a value modified in the property panel after the mouse left the view
1107       aCanDisplay = canDisplayCurrentCreatedFeature();
1108     }
1109   }
1110   #endif
1111   return aCanDisplay;
1112 }
1113
1114 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1115 {
1116   bool aCanDisplay = myIsMouseOverWindow;
1117   if (!aCanDisplay) {
1118     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1119     bool isValueStored = anActiveWidget && anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1120     aCanDisplay = /*!myIsResetCurrentValue &&*/isValueStored;
1121   }
1122   return aCanDisplay;
1123   //return myIsMouseOverWindow || (!myIsResetCurrentValue && !myIsCurrentValueUnderModification);
1124 #ifdef DEBUG_MOUSE_OVER_WINDOW_FLAGS
1125   qDebug(QString("canDisplayCurrentCreatedFeature: %1").arg(mouseOverWindowFlagsInfo()).toStdString().c_str());
1126 #endif
1127 }
1128
1129 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1130 {
1131   bool isFoundObject = false;
1132
1133   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1134   if (anObjectFeature.get()) {
1135     int aSize = myCurrentSketch->numberOfSubs();
1136     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1137       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1138       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1139     }
1140   }
1141   return isFoundObject;
1142 }
1143
1144 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
1145 {
1146   if (myPlaneFilter.IsNull()) 
1147    myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
1148
1149   myPlaneFilter->setPlane(thePln);
1150 }
1151
1152 void PartSet_SketcherMgr::getCurrentSelection(const FeaturePtr& theFeature,
1153                                               const FeaturePtr& theSketch,
1154                                               ModuleBase_IWorkshop* theWorkshop,
1155                                               FeatureToSelectionMap& theSelection)
1156 {
1157   if (theFeature.get() == NULL)
1158     return;
1159
1160   std::set<AttributePtr> aSelectedAttributes;
1161   std::set<ResultPtr> aSelectedResults;
1162
1163   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1164   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
1165   if (!aContext.IsNull()) {
1166     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1167     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1168
1169     std::list<ResultPtr> aResults = theFeature->results();
1170     std::list<ResultPtr>::const_iterator aIt;
1171     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1172     {
1173       ResultPtr aResult = *aIt;
1174       AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1175       if (aAISObj.get() == NULL)
1176         continue;
1177       Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1178       for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
1179       {
1180         Handle(SelectMgr_EntityOwner) anOwner = aContext->SelectedOwner();
1181         if (anOwner->Selectable() != anAISIO)
1182           continue;
1183         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1184                                aSelectedAttributes, aSelectedResults);
1185       }
1186       for (aContext->InitDetected(); aContext->MoreDetected(); aContext->NextDetected()) {
1187         Handle(SelectMgr_EntityOwner) anOwner = aContext->DetectedOwner();
1188         if (anOwner.IsNull())
1189           continue;
1190         if (anOwner->Selectable() != anAISIO)
1191           continue;
1192         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1193                                aSelectedAttributes, aSelectedResults);
1194       }
1195     }
1196   }
1197   theSelection[theFeature] = std::make_pair(aSelectedAttributes, aSelectedResults);
1198 }
1199
1200 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1201                                              const FeaturePtr& theSketch,
1202                                              ModuleBase_IWorkshop* theWorkshop,
1203                                              const FeatureToSelectionMap& theSelection,
1204                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1205 {
1206   if (theFeature.get() == NULL)
1207     return;
1208
1209   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1210   std::set<AttributePtr> aSelectedAttributes = anIt.value().first;
1211   std::set<ResultPtr> aSelectedResults = anIt.value().second;
1212
1213   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1214
1215   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1216   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1217
1218   // 1. found the feature's owners. Check the AIS objects of the constructions
1219   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1220   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1221     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1222
1223     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1224     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1225     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1226       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1227       if (!anOwner.IsNull())
1228         theOwnersToSelect.Add(anOwner);
1229     }
1230   }
1231
1232   // 2. found the feature results's owners
1233   std::list<ResultPtr> aResults = theFeature->results();
1234   std::list<ResultPtr>::const_iterator aIt;
1235   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1236   {
1237     ResultPtr aResult = *aIt;
1238     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1239     if (aAISObj.get() == NULL)
1240       continue; 
1241     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1242
1243     SelectMgr_IndexedMapOfOwner aSelectedOwners;  
1244     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1245     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1246       Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1247       if ( anOwner.IsNull() || !anOwner->HasShape() )
1248         continue;
1249       const TopoDS_Shape& aShape = anOwner->Shape();
1250       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1251       if (aShapeType == TopAbs_VERTEX) {
1252         AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1253         if (aPntAttr.get() != NULL &&
1254             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end()) {
1255           theOwnersToSelect.Add(anOwner);
1256         }
1257       }
1258       else if (aShapeType == TopAbs_EDGE) {
1259         bool aFound = aSelectedResults.find(aResult) != aSelectedResults.end();
1260         if (aSelectedResults.find(aResult) != aSelectedResults.end() &&
1261             theOwnersToSelect.FindIndex(anOwner) <= 0)
1262           theOwnersToSelect.Add(anOwner);
1263       }
1264     }
1265   }
1266 }
1267
1268 void PartSet_SketcherMgr::connectToPropertyPanel(const bool isToConnect)
1269 {
1270   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1271   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1272   XGUI_Workshop* aWorkshop = aConnector->workshop();
1273   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
1274   if (aPropertyPanel) {
1275     const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
1276     foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
1277       if (isToConnect) {
1278         connect(aWidget, SIGNAL(beforeValuesChanged()),
1279                 this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1280         connect(aWidget, SIGNAL(valueStateChanged()),
1281                 this, SLOT(onValueStateChanged()));
1282         connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChangedInPropertyPanel()));
1283         connect(aWidget, SIGNAL(afterValuesChanged()),
1284                 this, SLOT(onAfterValuesChangedInPropertyPanel()));
1285       }
1286       else {
1287         disconnect(aWidget, SIGNAL(beforeValuesChanged()),
1288                    this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1289         disconnect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChangedInPropertyPanel()));
1290         disconnect(aWidget, SIGNAL(afterValuesChanged()),
1291                    this, SLOT(onAfterValuesChangedInPropertyPanel()));
1292       }
1293     }
1294   }
1295 }
1296
1297 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1298 {
1299   return myModule->workshop()->currentOperation();
1300 }
1301
1302 //**************************************************************
1303 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1304 {
1305   ModuleBase_ModelWidget* aWidget = 0;
1306   ModuleBase_Operation* anOperation = getCurrentOperation();
1307   if (anOperation) {
1308     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1309     if (aPanel)
1310       aWidget = aPanel->activeWidget();
1311   }
1312   return aWidget;
1313 }
1314
1315 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1316                                            const bool isEditOperation,
1317                                            const bool isToDisplay,
1318                                            const bool isFlushRedisplay)
1319 {
1320   #ifdef DEBUG_DO_NOT_BY_ENTER
1321   return;
1322   #endif
1323
1324   if (isEditOperation || !theFeature.get())
1325     return;
1326
1327   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1328   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1329
1330   // 1. change visibility of the object itself, here the presentable object is processed,
1331   // e.g. constraints features
1332   //FeaturePtr aFeature = aFOperation->feature();
1333   std::list<ResultPtr> aResults = theFeature->results();
1334   if (isToDisplay)
1335     theFeature->setDisplayed(true);
1336   else
1337     theFeature->setDisplayed(false);
1338
1339   // change visibility of the object results, e.g. non-constraint features
1340   std::list<ResultPtr>::const_iterator aIt;
1341   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1342     if (isToDisplay) {
1343       (*aIt)->setDisplayed(true);
1344     }
1345     else {
1346       (*aIt)->setDisplayed(false);
1347     }
1348   }
1349   if (isFlushRedisplay)
1350     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1351 }
1352
1353 void PartSet_SketcherMgr::storeSelection(const bool theHighlightedOnly)
1354 {
1355   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1356   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1357   QList<ModuleBase_ViewerPrs> aHighlighted = aSelect->getHighlighted();
1358
1359   QList<FeaturePtr> aFeatureList;
1360   if (theHighlightedOnly) {
1361     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1362   }
1363   else {
1364     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1365
1366     QList<ModuleBase_ViewerPrs> aSelected = aSelect->getSelected(ModuleBase_ISelection::AllControls);
1367     fillFeatureList(aSelected, myCurrentSketch, aFeatureList);
1368   }
1369
1370   // 1. it is necessary to save current selection in order to restore it after the features moving
1371   myCurrentSelection.clear();
1372   QList<FeaturePtr>::const_iterator anIt = aFeatureList.begin(), aLast = aFeatureList.end();
1373   for (; anIt != aLast; anIt++) {
1374     getCurrentSelection(*anIt, myCurrentSketch, aWorkshop, myCurrentSelection);
1375   }
1376   //qDebug(QString("  storeSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1377 }
1378
1379 void PartSet_SketcherMgr::restoreSelection()
1380 {
1381   //qDebug(QString("restoreSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1382   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1383   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1384   FeatureToSelectionMap::const_iterator aSIt = myCurrentSelection.begin(),
1385                                         aSLast = myCurrentSelection.end();
1386   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1387   for (; aSIt != aSLast; aSIt++) {
1388     anOwnersToSelect.Clear();
1389     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, myCurrentSelection,
1390                         anOwnersToSelect);
1391     aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1392   }
1393 }
1394
1395 void PartSet_SketcherMgr::onShowConstraintsToggle(bool theOn)
1396 {
1397   if (myIsConstraintsShown == theOn)
1398     return;
1399   if (myCurrentSketch.get() == NULL)
1400     return;
1401
1402   myIsConstraintsShown = theOn;
1403
1404   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1405   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1406
1407   const QStringList& aConstrIds = constraintsIdList();
1408   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1409     FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1410     if (aConstrIds.contains(QString(aSubFeature->getKind().c_str()))) {
1411       if (myIsConstraintsShown) 
1412         aSubFeature->setDisplayed(true);
1413       else
1414         aSubFeature->setDisplayed(false);
1415     }
1416   }
1417   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1418 }
1419
1420 QString PartSet_SketcherMgr::mouseOverWindowFlagsInfo() const
1421 {
1422   return "";//QString("myIsResetCurrentValue = %1,    myIsMouseOverWindow = %2")
1423      //.arg(myIsResetCurrentValue).arg(myIsMouseOverWindow);
1424 }
1425
1426 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1427 {
1428   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1429   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1430   XGUI_Workshop* aWorkshop = aConnector->workshop();
1431
1432   return aWorkshop->operationMgr();
1433 }