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