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