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