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