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