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