Salome HOME
028ebd6509de5cbb38be1248c236855b338f9241
[modules/shaper.git] / src / PartSet / PartSet_SketcherMgr.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        PartSet_SketcherMgr.cpp
4 // Created:     19 Dec 2014
5 // Author:      Vitaly SMETANNIKOV
6
7 #include "PartSet_SketcherMgr.h"
8 #include "PartSet_SketcherReetntrantMgr.h"
9 #include "PartSet_Module.h"
10 #include "PartSet_WidgetPoint2d.h"
11 #include "PartSet_WidgetPoint2dDistance.h"
12 #include "PartSet_Tools.h"
13 #include "PartSet_WidgetSketchLabel.h"
14
15 #include <XGUI_ModuleConnector.h>
16 #include <XGUI_Displayer.h>
17 #include <XGUI_Workshop.h>
18 #include <XGUI_ContextMenuMgr.h>
19 #include <XGUI_Selection.h>
20 #include <XGUI_SelectionMgr.h>
21 #include <XGUI_ModuleConnector.h>
22 #include <XGUI_PropertyPanel.h>
23 #include <XGUI_ViewerProxy.h>
24 #include <XGUI_OperationMgr.h>
25
26 #include <ModuleBase_IPropertyPanel.h>
27 #include <ModuleBase_ISelection.h>
28 #include <ModuleBase_IViewer.h>
29 #include <ModuleBase_IWorkshop.h>
30 #include <ModuleBase_IViewWindow.h>
31 #include <ModuleBase_ModelWidget.h>
32 #include <ModuleBase_Operation.h>
33 #include <ModuleBase_OperationFeature.h>
34 #include <ModuleBase_Operation.h>
35 #include <ModuleBase_WidgetEditor.h>
36
37 #include <GeomDataAPI_Point2D.h>
38
39 #include <Events_Loop.h>
40
41 #include <SketchPlugin_Line.h>
42 #include <SketchPlugin_Sketch.h>
43 #include <SketchPlugin_Point.h>
44 #include <SketchPlugin_Arc.h>
45 #include <SketchPlugin_Circle.h>
46 #include <SketchPlugin_ConstraintLength.h>
47 #include <SketchPlugin_ConstraintDistance.h>
48 #include <SketchPlugin_ConstraintParallel.h>
49 #include <SketchPlugin_ConstraintPerpendicular.h>
50 #include <SketchPlugin_ConstraintRadius.h>
51 #include <SketchPlugin_ConstraintRigid.h>
52 #include <SketchPlugin_ConstraintHorizontal.h>
53 #include <SketchPlugin_ConstraintVertical.h>
54 #include <SketchPlugin_ConstraintEqual.h>
55 #include <SketchPlugin_ConstraintTangent.h>
56 #include <SketchPlugin_ConstraintCoincidence.h>
57 #include <SketchPlugin_ConstraintFillet.h>
58 #include <SketchPlugin_ConstraintMirror.h>
59 #include <SketchPlugin_ConstraintAngle.h>
60 #include <SketchPlugin_MultiRotation.h>
61 #include <SketchPlugin_MultiTranslation.h>
62
63 #include <SketcherPrs_Tools.h>
64
65 #include <SelectMgr_IndexedMapOfOwner.hxx>
66 #include <StdSelect_BRepOwner.hxx>
67
68 //#include <AIS_DimensionSelectionMode.hxx>
69 #include <AIS_Shape.hxx>
70
71 #include <ModelAPI_Events.h>
72 #include <ModelAPI_Session.h>
73 #include <ModelAPI_AttributeString.h>
74
75 #include <QMouseEvent>
76 #include <QApplication>
77
78 //#define DEBUG_DO_NOT_BY_ENTER
79 //#define DEBUG_MOUSE_OVER_WINDOW_FLAGS
80
81 /// Returns list of unique objects by sum of objects from List1 and List2
82 /*QList<ModuleBase_ViewerPrs> getSumList(const QList<ModuleBase_ViewerPrs>& theList1,
83                                        const QList<ModuleBase_ViewerPrs>& theList2)
84 {
85   QList<ModuleBase_ViewerPrs> aRes;
86   foreach (ModuleBase_ViewerPrs aPrs, theList1) {
87     if (!aRes.contains(aPrs))
88       aRes.append(aPrs);
89   }
90   foreach (ModuleBase_ViewerPrs aPrs, theList2) {
91     if (!aRes.contains(aPrs))
92       aRes.append(aPrs);
93   }
94   return aRes;
95 }*/
96
97 // Fills the list of features the list of selected presentations.
98 // \param theList a list of selected presentations
99 // \param theSketch a sketch to project a vertex shape of a presentation to the plane
100 // and find the corresponded attribute
101 // \param theFeatureList  an output list of features
102 void fillFeatureList(const QList<ModuleBase_ViewerPrs>& theList,
103                      const FeaturePtr theSketch,
104                      QList<FeaturePtr>& theFeatureList)
105 {
106   QList<ModuleBase_ViewerPrs> aRes;
107
108   QList<ModuleBase_ViewerPrs>::const_iterator anIt = theList.begin(),
109                                               aLast = theList.end();
110   for (; anIt != aLast; anIt++)
111   {
112     ModuleBase_ViewerPrs aPrs = *anIt;
113     FeaturePtr aFeature = ModelAPI_Feature::feature(aPrs.object());
114     if (aFeature.get()  && !theFeatureList.contains(aFeature))
115       theFeatureList.append(aFeature);
116   }
117 }
118
119 /// Fills attribute and result lists by the selected owner. In case if the attribute is found,
120 /// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge, put the function
121 /// result as is to the list of results.
122 /// \param theOwner a viewer selected owner
123 /// \param theFeature a feature, where the attribute is searched
124 /// \param theSketch a current sketch
125 /// \param theSelectedAttribute an output list of attributes
126 /// \param theSelectedResults an output list of edge results
127 void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
128                             const FeaturePtr& theFeature, const FeaturePtr& theSketch,
129                             const ResultPtr& theResult,
130                             std::set<AttributePtr>& aSelectedAttributes,
131                             std::set<ResultPtr>& aSelectedResults)
132 {
133   Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(theOwner);
134   if (aBRepOwner.IsNull())
135     return;
136   Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(
137                                                                     aBRepOwner->Selectable());
138   if (aBRepOwner->HasShape()) {
139     const TopoDS_Shape& aShape = aBRepOwner->Shape();
140     TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
141     if (aShapeType == TopAbs_VERTEX) {
142       AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature,
143                                                                     aShape, theSketch);
144       if (aPntAttr.get() != NULL)
145         aSelectedAttributes.insert(aPntAttr);
146     }
147     else if (aShapeType == TopAbs_EDGE &&
148              aSelectedResults.find(theResult) == aSelectedResults.end()) {
149       aSelectedResults.insert(theResult);
150     }
151   }
152 }
153
154 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
155   : QObject(theModule), myModule(theModule), myIsDragging(false), myDragDone(false),
156     myIsResetCurrentValue(false), myIsMouseOverWindow(false),
157     myIsMouseOverViewProcessed(true), myPreviousUpdateViewerEnabled(true),
158     myIsPopupMenuActive(false), myIsConstraintsShown(true)
159 {
160   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
161   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
162
163   myPreviousDrawModeEnabled = true;//aViewer->isSelectionEnabled();
164
165   connect(aViewer, SIGNAL(mousePress(ModuleBase_IViewWindow*, QMouseEvent*)),
166           this, SLOT(onMousePressed(ModuleBase_IViewWindow*, QMouseEvent*)));
167
168   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)),
169           this, SLOT(onMouseReleased(ModuleBase_IViewWindow*, QMouseEvent*)));
170
171   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
172           this, SLOT(onMouseMoved(ModuleBase_IViewWindow*, QMouseEvent*)));
173
174   connect(aViewer, SIGNAL(mouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)),
175           this, SLOT(onMouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)));
176
177   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
178   XGUI_Workshop* aWorkshop = aConnector->workshop();
179   connect(aWorkshop, SIGNAL(applicationStarted()), this, SLOT(onApplicationStarted()));
180 }
181
182 PartSet_SketcherMgr::~PartSet_SketcherMgr()
183 {
184   if (!myPlaneFilter.IsNull())
185     myPlaneFilter.Nullify();
186 }
187
188 void PartSet_SketcherMgr::onEnterViewPort()
189 {
190   // 1. if the mouse over window, update the next flag. Do not perform update visibility of
191   // created feature because it should be done in onMouseMove(). Some widgets watch
192   // the mouse move and use the cursor position to update own values. If the presentaion is
193   // redisplayed before this update, the feature presentation jumps from reset value to current.
194   myIsMouseOverWindow = true;
195   myIsResetCurrentValue = false;
196   // it is important to validate operation here only if sketch entity create operation is active
197   // because at this operation we reacts to the mouse leave/enter view port
198   //operationMgr()->onValidateOperation();
199 #ifdef DEBUG_MOUSE_OVER_WINDOW_FLAGS
200   qDebug(QString("onEnterViewPort: %1").arg(mouseOverWindowFlagsInfo()).toStdString().c_str());
201 #endif
202
203   #ifdef DEBUG_DO_NOT_BY_ENTER
204   return;
205   #endif
206
207   if (!isNestedCreateOperation(getCurrentOperation()))
208     return;
209
210   QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));//QIcon(":pictures/button_plus.png").pixmap(20,20)));
211   operationMgr()->onValidateOperation();
212
213   // we need change displayed state of the current operation feature
214   // if the feature is presentable, e.g. distance construction. It has no results, so workshop does
215   // not accept a signal about the result created. Nothing is shown until mouse is moved out/in view
216   // port. If the isDisplayed flag is true, the presentable feature is displayed as soon as the
217   // presentation becomes valid and redisplay happens
218   //ModuleBase_Operation* aOperation = getCurrentOperation();
219   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
220                                                                            (getCurrentOperation());
221   if (aFOperation) {
222     FeaturePtr aFeature = aFOperation->feature();
223     if (aFeature.get() && aFeature->data()->isValid()) {
224       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature), false);
225     }
226   }
227 }
228
229 void PartSet_SketcherMgr::onLeaveViewPort()
230 {
231   myIsMouseOverViewProcessed = false;
232   myIsMouseOverWindow = false;
233   // it is important to validate operation here only if sketch entity create operation is active
234   // because at this operation we reacts to the mouse leave/enter view port
235   //operationMgr()->onValidateOperation();
236 #ifdef DEBUG_MOUSE_OVER_WINDOW_FLAGS
237   qDebug(QString("onLeaveViewPort: %1").arg(mouseOverWindowFlagsInfo()).toStdString().c_str());
238 #endif
239
240   #ifdef DEBUG_DO_NOT_BY_ENTER
241   return;
242   #endif
243
244   if (!isNestedCreateOperation(getCurrentOperation()))
245     return;
246
247   QApplication::restoreOverrideCursor();
248
249   // the method should be performed if the popup menu is called,
250   // the reset of the current widget should not happen
251   if (myIsPopupMenuActive)
252     return;
253
254   operationMgr()->onValidateOperation();
255
256   // 2. if the mouse IS NOT over window, reset the active widget value and hide the presentation
257   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
258   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
259   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
260   // disable the viewer update in order to avoid visualization of redisplayed feature in viewer
261   // obtained after reset value
262   bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
263   ModuleBase_Operation* aOperation = getCurrentOperation();
264   ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
265   ModuleBase_ModelWidget* aActiveWgt = aPanel->activeWidget();
266   if (aActiveWgt && aActiveWgt->reset()) {
267     myIsResetCurrentValue = true;
268   }
269   aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
270
271   // hides the presentation of the current operation feature
272   // the feature is to be erased here, but it is correct to call canDisplayObject because
273   // there can be additional check (e.g. editor widget in distance constraint)
274   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
275                                                                            (getCurrentOperation());
276   if (aFOperation) {
277     FeaturePtr aFeature = aFOperation->feature();
278     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
279   }
280 }
281
282 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
283 {
284   myIsResetCurrentValue = false;
285
286   if (isNestedCreateOperation(getCurrentOperation()))
287     return;
288   // it is necessary to save current selection in order to restore it after the values are modifed
289   storeSelection();
290
291   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
292   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
293   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
294   myPreviousUpdateViewerEnabled = aDisplayer->enableUpdateViewer(false);
295 }
296
297 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
298 {
299   if (isNestedCreateOperation(getCurrentOperation()))
300     return;
301   // it is necessary to restore current selection in order to restore it after the values are modified
302   restoreSelection();
303   myCurrentSelection.clear();
304
305   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
306   // viewer happens by deselect/select the modified objects. The flag should be restored after
307   // the selection processing. The update viewer should be also called.
308   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
309   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
310   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
311   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
312   aDisplayer->updateViewer();
313 }
314
315 void PartSet_SketcherMgr::onValuesChangedInPropertyPanel()
316 {
317   if (!isNestedCreateOperation(getCurrentOperation()))
318     return;
319
320   // visualize the current operation feature
321   //myIsResetCurrentValue = false;
322   operationMgr()->onValidateOperation();
323   // the feature is to be erased here, but it is correct to call canDisplayObject because
324   // there can be additional check (e.g. editor widget in distance constraint)
325   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
326                                                                            (getCurrentOperation());
327   if (aFOperation) {
328     FeaturePtr aFeature = aFOperation->feature();
329     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
330   }
331 }
332
333 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
334 {
335   get2dPoint(theWnd, theEvent, myClickedPoint);
336
337   if (!(theEvent->buttons() & Qt::LeftButton))
338     return;
339
340   if (myModule->sketchReentranceMgr()->processMousePressed(theWnd, theEvent))
341     return;
342
343   // Clear dragging mode
344   myIsDragging = false;
345
346   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
347   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
348   if (!aViewer->canDragByMouse())
349     return;
350
351   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
352                                                                (getCurrentOperation());
353   if (!aFOperation)
354     return;
355
356   if (aFOperation->isEditOperation()) {
357     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
358     ModuleBase_ModelWidget* aActiveWgt = aPanel->activeWidget();
359     // If the current widget is a selector, do nothing, it processes the mouse press
360     if(aActiveWgt && aActiveWgt->isViewerSelector()) {
361       return;
362     }
363   }
364
365   // Use only for sketch operations
366   if (myCurrentSketch) {
367     if (!PartSet_Tools::sketchPlane(myCurrentSketch))
368       return;
369
370     bool isSketcher = isSketchOperation(aFOperation);
371     bool isSketchOpe = isNestedSketchOperation(aFOperation);
372
373     // Avoid non-sketch operations
374     if ((!isSketchOpe) && (!isSketcher))
375       return;
376
377     bool isEditing = aFOperation->isEditOperation();
378
379     // Ignore creation sketch operation
380     if ((!isSketcher) && (!isEditing))
381       return;
382
383     Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
384     if (!aContext.IsNull()) {
385       // MoveTo in order to highlight current object
386       aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
387     }
388     // Remember highlighted objects for editing
389     ModuleBase_ISelection* aSelect = aWorkshop->selection();
390
391     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
392     storeSelection(!aHasShift);
393
394     if (myCurrentSelection.empty()) {
395       if (isSketchOpe && (!isSketcher))
396         // commit previous operation
397         if (!aFOperation->commit())
398           aFOperation->abort();
399       return;
400     }
401     // Init flyout point for radius rotation
402     FeaturePtr aFeature = myCurrentSelection.begin().key();
403
404     if (isSketcher) {
405       myIsDragging = true;
406       get2dPoint(theWnd, theEvent, myCurrentPoint);
407       myDragDone = false;
408       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
409       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
410       launchEditing();
411       if (aFeature.get() != NULL) {
412         std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
413                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
414       if (aSPFeature.get() && aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID()) {
415           DataPtr aData = aSPFeature->data();
416           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
417           std::shared_ptr<GeomDataAPI_Point2D> aFPAttr = 
418             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
419           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
420         }
421       }
422     } else if (isSketchOpe && isEditing) {
423       // If selected another object commit current result
424       aFOperation->commit();
425
426       myIsDragging = true;
427       get2dPoint(theWnd, theEvent, myCurrentPoint);
428       myDragDone = false;
429       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
430       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
431
432       // This is necessary in order to finalize previous operation
433       QApplication::processEvents();
434       launchEditing();
435     }
436   }
437 }
438
439 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
440 {
441   if (myModule->sketchReentranceMgr()->processMouseReleased(theWnd, theEvent))
442     return;
443
444   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
445   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
446   if (!aViewer->canDragByMouse())
447     return;
448   ModuleBase_Operation* aOp = getCurrentOperation();
449   if (aOp) {
450     if (isNestedSketchOperation(aOp)) {
451       get2dPoint(theWnd, theEvent, myClickedPoint);
452
453       // Only for sketcher operations
454       if (myIsDragging) {
455         if (myDragDone) {
456           //aOp->commit();
457           myCurrentSelection.clear();
458           /*Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
459           if (!aContext.IsNull()) {
460           // Reselect edited object
461           aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
462           if (theEvent->modifiers() & Qt::ShiftModifier)
463             aContext->ShiftSelect();
464           else
465             aContext->Select();
466           */
467         }
468       }
469     }
470   }
471       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
472   aWorkshop->viewer()->enableDrawMode(myPreviousDrawModeEnabled);
473   //aWorkshop->viewer()->enableSelection(myPreviousDrawModeEnabled);
474   myIsDragging = false;
475 }
476
477 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
478 {
479   if (myModule->sketchReentranceMgr()->processMouseMoved(theWnd, theEvent))
480     return;
481
482   if (isNestedCreateOperation(getCurrentOperation()) && !myIsMouseOverViewProcessed) {
483     myIsMouseOverViewProcessed = true;
484     // 1. perform the widget mouse move functionality and display the presentation
485     ModuleBase_Operation* aOperation = getCurrentOperation();
486     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
487     ModuleBase_ModelWidget* anActiveWdg = aPanel->activeWidget();
488     // the mouse move should be processed in the widget, if it can in order to visualize correct
489     // presentation. These widgets correct the feature attribute according to the mouse position
490     PartSet_WidgetPoint2D* aPoint2DWdg = dynamic_cast<PartSet_WidgetPoint2D*>(anActiveWdg);
491     if (aPoint2DWdg) {
492       aPoint2DWdg->onMouseMove(theWnd, theEvent);
493     }
494     PartSet_WidgetPoint2dDistance* aDistanceWdg = dynamic_cast<PartSet_WidgetPoint2dDistance*>
495                                                                 (anActiveWdg);
496     if (aDistanceWdg) {
497       aDistanceWdg->onMouseMove(theWnd, theEvent);
498     }
499     // the feature is to be erased here, but it is correct to call canDisplayObject because
500     // there can be additional check (e.g. editor widget in distance constraint)
501     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
502                                                                              (getCurrentOperation());
503     if (aFOperation) {
504       FeaturePtr aFeature = aFOperation->feature();
505       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
506     }
507   }
508
509   myClickedPoint.clear();
510
511   if (myIsDragging) {
512     // 1. the current selection is saved in the mouse press method in order to restore it after moving
513     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
514     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
515     // deselected). This flag should be restored in the slot, processed the mouse release signal.
516
517     // TODO: Has to be commented out when SALOME patch on draw mode become avialable
518     //ModuleBase_IViewer* aViewer = myModule->workshop()->viewer();
519     //aViewer->enableSelection(false);
520
521     ModuleBase_Operation* aCurrentOperation = getCurrentOperation();
522     if (!aCurrentOperation)
523       return;
524     if (isSketchOperation(aCurrentOperation))
525       return; // No edit operation activated
526
527     Handle(V3d_View) aView = theWnd->v3dView();
528     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
529     double aX, aY;
530     PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, aY);
531     double dX =  aX - myCurrentPoint.myCurX;
532     double dY =  aY - myCurrentPoint.myCurY;
533
534     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
535     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
536     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
537     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
538     // viewer happens by deselect/select the modified objects. The flag should be restored after
539     // the selection processing. The update viewer should be also called.
540     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
541
542     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
543     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
544     FeatureToSelectionMap::const_iterator anIt = myCurrentSelection.begin(),
545                                           aLast = myCurrentSelection.end();
546     // 4. the features and attributes modification(move)
547     bool isModified = false;
548     for (; anIt != aLast; anIt++) {
549       FeaturePtr aFeature = anIt.key();
550
551       std::set<AttributePtr> anAttributes = anIt.value().first;
552       // Process selection by attribute: the priority to the attribute
553       if (!anAttributes.empty()) {
554         std::set<AttributePtr>::const_iterator anAttIt = anAttributes.begin(),
555                                                anAttLast = anAttributes.end();
556         for (; anAttIt != anAttLast; anAttIt++) {
557           AttributePtr anAttr = *anAttIt;
558           if (anAttr.get() == NULL)
559             continue;
560           std::string aAttrId = anAttr->id();
561           DataPtr aData = aFeature->data();
562           if (aData->isValid()) {
563             std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
564               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
565             if (aPoint.get() != NULL) {
566               bool isImmutable = aPoint->setImmutable(true);
567               aPoint->move(dX, dY);
568               isModified = true;
569               ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
570               aPoint->setImmutable(isImmutable);
571             }
572           }
573         }
574       } else {
575         // Process selection by feature
576         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
577           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
578         if (aSketchFeature) {
579           aSketchFeature->move(dX, dY);
580           isModified = true;
581           ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
582         }
583       }
584     }
585     // the modified state of the current operation should be updated if there are features, which
586     // were changed here
587     if (isModified) {
588       aCurrentOperation->onValuesChanged();
589     }
590     Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
591     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
592
593     // 5. it is necessary to save current selection in order to restore it after the features moving
594     restoreSelection();
595     // 6. restore the update viewer flag and call this update
596     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
597     aDisplayer->updateViewer();
598
599     myDragDone = true;
600     myCurrentPoint.setValue(aX, aY);
601   }
602 }
603
604 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
605 {
606   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
607                                                                (getCurrentOperation());
608   if (aFOperation && aFOperation->isEditOperation()) {
609     std::string aId = aFOperation->id().toStdString();
610     if (isDistanceOperation(aFOperation))
611     {
612       // Activate dimension value editing on double click
613       ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
614       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
615       // Find corresponded widget to activate value editing
616       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
617         if (aWgt->attributeID() == "ConstraintValue") {
618           aWgt->focusTo();
619           return;
620         }
621       }
622     }
623   }
624 }
625
626 void PartSet_SketcherMgr::onApplicationStarted()
627 {
628   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
629   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
630   XGUI_Workshop* aWorkshop = aConnector->workshop();
631   PartSet_SketcherReetntrantMgr* aReentranceMgr = myModule->sketchReentranceMgr();
632
633   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
634   if (aPropertyPanel) {
635     connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
636             this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
637
638     connect(aPropertyPanel, SIGNAL(noMoreWidgets(const std::string&)),
639             aReentranceMgr, SLOT(onNoMoreWidgets(const std::string&)));
640     connect(aPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
641             aReentranceMgr, SLOT(onWidgetActivated()));
642   }
643
644   XGUI_OperationMgr* anOpMgr = aWorkshop->operationMgr();
645   connect(anOpMgr, SIGNAL(keyEnterReleased()), aReentranceMgr, SLOT(onEnterReleased()));
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 }