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