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