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