]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_SketcherMgr.cpp
Salome HOME
Issue #1535 crash when mirror: debug information
[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 #include "PartSet_ResultSketchPrs.h"
16
17 #include <XGUI_ModuleConnector.h>
18 #include <XGUI_Displayer.h>
19 #include <XGUI_Workshop.h>
20 #include <XGUI_ContextMenuMgr.h>
21 #include <XGUI_Selection.h>
22 #include <XGUI_SelectionMgr.h>
23 #include <XGUI_ModuleConnector.h>
24 #include <XGUI_PropertyPanel.h>
25 #include <XGUI_ViewerProxy.h>
26 #include <XGUI_OperationMgr.h>
27 #include <XGUI_Tools.h>
28
29 #include <ModuleBase_IPropertyPanel.h>
30 #include <ModuleBase_ISelection.h>
31 #include <ModuleBase_IViewer.h>
32 #include <ModuleBase_IWorkshop.h>
33 #include <ModuleBase_IViewWindow.h>
34 #include <ModuleBase_ModelWidget.h>
35 #include <ModuleBase_Operation.h>
36 #include <ModuleBase_OperationFeature.h>
37 #include <ModuleBase_Operation.h>
38 #include <ModuleBase_WidgetEditor.h>
39 #include <ModuleBase_ViewerPrs.h>
40 #include <ModuleBase_Tools.h>
41
42 #include <GeomDataAPI_Point2D.h>
43
44 #include <Events_Loop.h>
45
46 #include <SketchPlugin_Line.h>
47 #include <SketchPlugin_Sketch.h>
48 #include <SketchPlugin_Point.h>
49 #include <SketchPlugin_Arc.h>
50 #include <SketchPlugin_Circle.h>
51 #include <SketchPlugin_ConstraintLength.h>
52 #include <SketchPlugin_ConstraintDistance.h>
53 #include <SketchPlugin_ConstraintParallel.h>
54 #include <SketchPlugin_ConstraintPerpendicular.h>
55 #include <SketchPlugin_ConstraintRadius.h>
56 #include <SketchPlugin_ConstraintRigid.h>
57 #include <SketchPlugin_ConstraintHorizontal.h>
58 #include <SketchPlugin_ConstraintVertical.h>
59 #include <SketchPlugin_ConstraintEqual.h>
60 #include <SketchPlugin_ConstraintTangent.h>
61 #include <SketchPlugin_ConstraintCoincidence.h>
62 #include <SketchPlugin_ConstraintFillet.h>
63 #include <SketchPlugin_ConstraintMirror.h>
64 #include <SketchPlugin_ConstraintAngle.h>
65 #include <SketchPlugin_ConstraintCollinear.h>
66 #include <SketchPlugin_ConstraintMiddle.h>
67 #include <SketchPlugin_MultiRotation.h>
68 #include <SketchPlugin_MultiTranslation.h>
69 #include <SketchPlugin_IntersectionPoint.h>
70
71 #include <SketcherPrs_Tools.h>
72
73 #include <SelectMgr_IndexedMapOfOwner.hxx>
74 #include <StdSelect_BRepOwner.hxx>
75
76 //#include <AIS_DimensionSelectionMode.hxx>
77 #include <AIS_Shape.hxx>
78 #include <AIS_Dimension.hxx>
79
80 #include <ModelAPI_Events.h>
81 #include <ModelAPI_Session.h>
82 #include <ModelAPI_AttributeString.h>
83
84 #include <QMouseEvent>
85 #include <QApplication>
86 #include <QCursor>
87 #include <QMessageBox>
88
89 //#define DEBUG_DO_NOT_BY_ENTER
90
91 //#define DEBUG_CURSOR
92
93 /// Returns list of unique objects by sum of objects from List1 and List2
94 /*QList<ModuleBase_ViewerPrsPtr> getSumList(const QList<ModuleBase_ViewerPrsPtr>& theList1,
95                                        const QList<ModuleBase_ViewerPrsPtr>& theList2)
96 {
97   QList<ModuleBase_ViewerPrsPtr> aRes;
98   foreach (ModuleBase_ViewerPrsPtr aPrs, theList1) {
99     if (!aRes.contains(aPrs))
100       aRes.append(aPrs);
101   }
102   foreach (ModuleBase_ViewerPrsPtr aPrs, theList2) {
103     if (!aRes.contains(aPrs))
104       aRes.append(aPrs);
105   }
106   return aRes;
107 }*/
108
109 // Fills the list of features the list of selected presentations.
110 // \param theList a list of selected presentations
111 // \param theSketch a sketch to project a vertex shape of a presentation to the plane
112 // and find the corresponded attribute
113 // \param theFeatureList  an output list of features
114 void fillFeatureList(const QList<ModuleBase_ViewerPrsPtr>& theList,
115                      const FeaturePtr theSketch,
116                      QList<FeaturePtr>& theFeatureList)
117 {
118   QList<ModuleBase_ViewerPrsPtr> aRes;
119
120   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theList.begin(),
121                                               aLast = theList.end();
122   for (; anIt != aLast; anIt++)
123   {
124     ModuleBase_ViewerPrsPtr aPrs = *anIt;
125     FeaturePtr aFeature = ModelAPI_Feature::feature(aPrs->object());
126     if (aFeature.get()  && !theFeatureList.contains(aFeature))
127       theFeatureList.append(aFeature);
128   }
129 }
130
131 /// Fills attribute and result lists by the selected owner. In case if the attribute is found,
132 /// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge, put the function
133 /// result as is to the list of results.
134 /// \param theOwner a viewer selected owner
135 /// \param theFeature a feature, where the attribute is searched
136 /// \param theSketch a current sketch
137 /// \param theSelectedAttribute an output list of attributes
138 /// \param theSelectedResults an output list of edge results
139 void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
140                             const FeaturePtr& theFeature, const FeaturePtr& theSketch,
141                             const ResultPtr& theResult,
142                             std::set<AttributePtr>& aSelectedAttributes,
143                             std::set<ResultPtr>& aSelectedResults)
144 {
145   Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(theOwner);
146   if (aBRepOwner.IsNull())
147     return;
148   Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(
149                                                                     aBRepOwner->Selectable());
150   if (aBRepOwner->HasShape()) {
151     const TopoDS_Shape& aShape = aBRepOwner->Shape();
152     TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
153     if (aShapeType == TopAbs_VERTEX) {
154       AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature,
155                                                                     aShape, theSketch);
156       if (aPntAttr.get() != NULL)
157         aSelectedAttributes.insert(aPntAttr);
158     }
159     else if (aShapeType == TopAbs_EDGE &&
160              aSelectedResults.find(theResult) == aSelectedResults.end()) {
161       aSelectedResults.insert(theResult);
162     }
163   }
164 }
165
166 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
167   : QObject(theModule), myModule(theModule), myIsDragging(false), myDragDone(false),
168     myIsMouseOverWindow(false),
169     myIsMouseOverViewProcessed(true), myPreviousUpdateViewerEnabled(true),
170     myIsPopupMenuActive(false)
171 {
172   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
173   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
174
175   myPreviousDrawModeEnabled = true;//aViewer->isSelectionEnabled();
176
177   connect(aViewer, SIGNAL(mousePress(ModuleBase_IViewWindow*, QMouseEvent*)),
178           this, SLOT(onMousePressed(ModuleBase_IViewWindow*, QMouseEvent*)));
179
180   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)),
181           this, SLOT(onMouseReleased(ModuleBase_IViewWindow*, QMouseEvent*)));
182
183   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
184           this, SLOT(onMouseMoved(ModuleBase_IViewWindow*, QMouseEvent*)));
185
186   connect(aViewer, SIGNAL(mouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)),
187           this, SLOT(onMouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)));
188
189   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
190   XGUI_Workshop* aWorkshop = aConnector->workshop();
191   connect(aWorkshop, SIGNAL(applicationStarted()), this, SLOT(onApplicationStarted()));
192
193   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
194   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
195   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
196 }
197
198 PartSet_SketcherMgr::~PartSet_SketcherMgr()
199 {
200   if (!myPlaneFilter.IsNull())
201     myPlaneFilter.Nullify();
202 }
203
204 void PartSet_SketcherMgr::onEnterViewPort()
205 {
206   // 1. if the mouse over window, update the next flag. Do not perform update visibility of
207   // created feature because it should be done in onMouseMove(). Some widgets watch
208   // the mouse move and use the cursor position to update own values. If the presentaion is
209   // redisplayed before this update, the feature presentation jumps from reset value to current.
210   myIsMouseOverWindow = true;
211
212   #ifdef DEBUG_DO_NOT_BY_ENTER
213   return;
214   #endif
215
216   if (canChangeCursor(getCurrentOperation())) {
217     QCursor* aCurrentCursor = QApplication::overrideCursor();
218     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
219       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
220 #ifdef DEBUG_CURSOR
221       qDebug("onEnterViewPort() : Qt::CrossCursor");
222 #endif
223     }
224   }
225
226   if (!isNestedCreateOperation(getCurrentOperation()))
227     return;
228
229   operationMgr()->onValidateOperation();
230
231   // we need change displayed state of the current operation feature
232   // if the feature is presentable, e.g. distance construction. It has no results, so workshop does
233   // not accept a signal about the result created. Nothing is shown until mouse is moved out/in view
234   // port. If the isDisplayed flag is true, the presentable feature is displayed as soon as the
235   // presentation becomes valid and redisplay happens
236   //ModuleBase_Operation* aOperation = getCurrentOperation();
237   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
238                                                                            (getCurrentOperation());
239   if (aFOperation) {
240     FeaturePtr aFeature = aFOperation->feature();
241     if (aFeature.get() && aFeature->data()->isValid()) {
242       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature), false);
243     }
244   }
245 }
246
247 void PartSet_SketcherMgr::onLeaveViewPort()
248 {
249   myIsMouseOverViewProcessed = false;
250   myIsMouseOverWindow = false;
251
252   #ifdef DEBUG_DO_NOT_BY_ENTER
253   return;
254   #endif
255
256   if (canChangeCursor(getCurrentOperation())) {
257     QApplication::restoreOverrideCursor();
258 #ifdef DEBUG_CURSOR
259     qDebug("onLeaveViewPort() : None");
260 #endif
261   }
262
263   if (!isNestedCreateOperation(getCurrentOperation()))
264     return;
265
266   // the method should be performed if the popup menu is called,
267   // the reset of the current widget should not happen
268   if (myIsPopupMenuActive)
269     return;
270
271   // it is important to validate operation here only if sketch entity create operation is active
272   // because at this operation we reacts to the mouse leave/enter view port
273   operationMgr()->onValidateOperation();
274
275   // 2. if the mouse IS NOT over window, reset the active widget value and hide the presentation
276   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
277   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
278   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
279   // disable the viewer update in order to avoid visualization of redisplayed feature in viewer
280   // obtained after reset value
281   bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
282   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
283   if (anActiveWidget)
284     anActiveWidget->reset();
285
286   // hides the presentation of the current operation feature
287   // the feature is to be erased here, but it is correct to call canDisplayObject because
288   // there can be additional check (e.g. editor widget in distance constraint)
289   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
290                                                                            (getCurrentOperation());
291   if (aFOperation) {
292     FeaturePtr aFeature = aFOperation->feature();
293     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
294   }
295   // we should update viewer after the presentation are hidden in the viewer
296   // otherwise the reset presentation(line) appears in the viewer(by quick move from viewer to PP)
297   aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
298 }
299
300 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
301 {
302   if (!isNestedEditOperation(getCurrentOperation()) ||
303       myModule->sketchReentranceMgr()->isInternalEditActive())
304     return;
305   // it is necessary to save current selection in order to restore it after the values are modifed
306   storeSelection();
307
308   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
309   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
310   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
311   myPreviousUpdateViewerEnabled = aDisplayer->enableUpdateViewer(false);
312 }
313
314 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
315 {
316   if (!isNestedEditOperation(getCurrentOperation()) ||
317       myModule->sketchReentranceMgr()->isInternalEditActive()) {
318     myModule->sketchReentranceMgr()->updateInternalEditActiveState();
319     return;
320   }
321   // it is necessary to restore current selection in order to restore it after the values are modified
322   restoreSelection();
323   myCurrentSelection.clear();
324
325   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
326   // viewer happens by deselect/select the modified objects. The flag should be restored after
327   // the selection processing. The update viewer should be also called.
328   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
329   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
330   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
331   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
332   aDisplayer->updateViewer();
333
334
335 }
336
337 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
338 {
339   if (myModule->sketchReentranceMgr()->processMousePressed(theWnd, theEvent))
340     return;
341
342   //get2dPoint(theWnd, theEvent, myClickedPoint);
343
344   if (!(theEvent->buttons() & Qt::LeftButton))
345     return;
346
347   // Clear dragging mode
348   myIsDragging = false;
349
350   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
351   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
352   if (!aViewer->canDragByMouse())
353     return;
354
355   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
356                                                                (getCurrentOperation());
357   if (!aFOperation)
358     return;
359
360   if (aFOperation->isEditOperation()) {
361     // If the current widget is a selector, do nothing, it processes the mouse press
362     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
363     if(anActiveWidget && anActiveWidget->isViewerSelector()) {
364       return;
365     }
366   }
367
368   // Use only for sketch operations
369   if (myCurrentSketch) {
370     if (!PartSet_Tools::sketchPlane(myCurrentSketch))
371       return;
372
373     bool isSketcher = isSketchOperation(aFOperation);
374     bool isSketchOpe = isNestedSketchOperation(aFOperation);
375
376     // Avoid non-sketch operations
377     if ((!isSketchOpe) && (!isSketcher))
378       return;
379
380     bool isEditing = aFOperation->isEditOperation();
381
382     // Ignore creation sketch operation
383     if ((!isSketcher) && (!isEditing))
384       return;
385
386     Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
387     if (!aContext.IsNull()) {
388       // MoveTo in order to highlight current object
389       aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
390       ModuleBase_Tools::selectionInfo(aContext, "PartSet_SketcherMgr::onMousePressed -- MoveTo");
391     }
392     // Remember highlighted objects for editing
393     ModuleBase_ISelection* aSelect = aWorkshop->selection();
394
395     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
396     storeSelection(!aHasShift);
397
398     if (myCurrentSelection.empty()) {
399       if (isSketchOpe && (!isSketcher))
400         // commit previous operation
401         if (!aFOperation->commit())
402           aFOperation->abort();
403       return;
404     }
405     // Init flyout point for radius rotation
406     FeaturePtr aFeature = myCurrentSelection.begin().key();
407
408     if (isSketcher) {
409       myIsDragging = true;
410       get2dPoint(theWnd, theEvent, myCurrentPoint);
411       myDragDone = false;
412
413       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
414       launchEditing();
415       if (aFeature.get() != NULL) {
416         std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
417                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
418       if (aSPFeature.get() && aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID()) {
419           DataPtr aData = aSPFeature->data();
420           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
421           std::shared_ptr<GeomDataAPI_Point2D> aFPAttr = 
422             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
423           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
424         }
425       }
426     } else if (isSketchOpe && isEditing) {
427       // If selected another object commit current result
428       aFOperation->commit();
429
430       myIsDragging = true;
431       get2dPoint(theWnd, theEvent, myCurrentPoint);
432       myDragDone = false;
433
434       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
435
436       // this is temporary commented in order to avoid the following wrong case:
437       // Distance constraint is under edition, double click on the digit -> nothing happens
438       // because QApplication::processEvents() calls onMouseDoubleClick, which try to show editor
439       // but as the prev edit is commited an new one is not started, editor is not shown.
440       // This is necessary in order to finalize previous operation
441       //QApplication::processEvents();
442       launchEditing();
443     }
444   }
445 }
446
447 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
448 {
449   if (myModule->sketchReentranceMgr()->processMouseReleased(theWnd, theEvent))
450     return;
451
452   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
453   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
454   if (!aViewer->canDragByMouse())
455     return;
456   ModuleBase_Operation* aOp = getCurrentOperation();
457   if (aOp) {
458     if (isNestedSketchOperation(aOp)) {
459       //get2dPoint(theWnd, theEvent, myClickedPoint);
460
461       // Only for sketcher operations
462       if (myIsDragging) {
463         if (myDragDone) {
464           //aOp->commit();
465           myCurrentSelection.clear();
466           /*Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
467           if (!aContext.IsNull()) {
468           // Reselect edited object
469           aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
470           if (theEvent->modifiers() & Qt::ShiftModifier)
471             aContext->ShiftSelect();
472           else
473             aContext->Select();
474           */
475         }
476       }
477     }
478   }
479
480   aWorkshop->viewer()->enableDrawMode(myPreviousDrawModeEnabled);
481   myIsDragging = false;
482 }
483
484 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
485 {
486   if (myModule->sketchReentranceMgr()->processMouseMoved(theWnd, theEvent))
487     return;
488
489   if (isNestedCreateOperation(getCurrentOperation()) && !myIsMouseOverViewProcessed) {
490     myIsMouseOverViewProcessed = true;
491     // 1. perform the widget mouse move functionality and display the presentation
492     // the mouse move should be processed in the widget, if it can in order to visualize correct
493     // presentation. These widgets correct the feature attribute according to the mouse position
494     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
495     PartSet_WidgetPoint2D* aPoint2DWdg = dynamic_cast<PartSet_WidgetPoint2D*>(anActiveWidget);
496     if (aPoint2DWdg) {
497       aPoint2DWdg->onMouseMove(theWnd, theEvent);
498     }
499     PartSet_WidgetPoint2dDistance* aDistanceWdg = dynamic_cast<PartSet_WidgetPoint2dDistance*>
500                                                                 (anActiveWidget);
501     if (aDistanceWdg) {
502       aDistanceWdg->onMouseMove(theWnd, theEvent);
503     }
504     // the feature is to be erased here, but it is correct to call canDisplayObject because
505     // there can be additional check (e.g. editor widget in distance constraint)
506     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
507                                                                              (getCurrentOperation());
508     if (aFOperation) {
509       FeaturePtr aFeature = aFOperation->feature();
510       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
511     }
512   }
513
514   //myClickedPoint.clear();
515
516   if (myIsDragging) {
517     // 1. the current selection is saved in the mouse press method in order to restore it after moving
518     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
519     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
520     // deselected). This flag should be restored in the slot, processed the mouse release signal.
521
522     ModuleBase_Operation* aCurrentOperation = getCurrentOperation();
523     if (!aCurrentOperation)
524       return;
525     if (isSketchOperation(aCurrentOperation))
526       return; // No edit operation activated
527
528     Handle(V3d_View) aView = theWnd->v3dView();
529     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
530     double aX, aY;
531     PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, aY);
532     double dX =  aX - myCurrentPoint.myCurX;
533     double dY =  aY - myCurrentPoint.myCurY;
534
535     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
536     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
537     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
538     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
539     // viewer happens by deselect/select the modified objects. The flag should be restored after
540     // the selection processing. The update viewer should be also called.
541     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
542
543     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
544     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
545     FeatureToSelectionMap::const_iterator anIt = myCurrentSelection.begin(),
546                                           aLast = myCurrentSelection.end();
547     // 4. the features and attributes modification(move)
548     bool isModified = false;
549     for (; anIt != aLast; anIt++) {
550       FeaturePtr aFeature = anIt.key();
551
552       std::set<AttributePtr> anAttributes = anIt.value().first;
553       // Process selection by attribute: the priority to the attribute
554       if (!anAttributes.empty()) {
555         std::set<AttributePtr>::const_iterator anAttIt = anAttributes.begin(),
556                                                anAttLast = anAttributes.end();
557         for (; anAttIt != anAttLast; anAttIt++) {
558           AttributePtr anAttr = *anAttIt;
559           if (anAttr.get() == NULL)
560             continue;
561           std::string aAttrId = anAttr->id();
562           DataPtr aData = aFeature->data();
563           if (aData->isValid()) {
564             std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
565               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
566             if (aPoint.get() != NULL) {
567               bool isImmutable = aPoint->setImmutable(true);
568               aPoint->move(dX, dY);
569               isModified = true;
570               ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
571               aPoint->setImmutable(isImmutable);
572             }
573           }
574         }
575       } else {
576         // Process selection by feature
577         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
578           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
579         if (aSketchFeature) {
580           aSketchFeature->move(dX, dY);
581           isModified = true;
582           ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
583         }
584       }
585     }
586     // the modified state of the current operation should be updated if there are features, which
587     // were changed here
588     if (isModified) {
589       aCurrentOperation->onValuesChanged();
590     }
591     Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
592     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
593
594     // 5. it is necessary to save current selection in order to restore it after the features moving
595     restoreSelection();
596     // 6. restore the update viewer flag and call this update
597     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
598     aDisplayer->updateViewer();
599
600     myDragDone = true;
601     myCurrentPoint.setValue(aX, aY);
602   }
603 }
604
605 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
606 {
607   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
608                                                                (getCurrentOperation());
609   if (aFOperation && aFOperation->isEditOperation()) {
610     std::string aId = aFOperation->id().toStdString();
611     if (isDistanceOperation(aFOperation))
612     {
613       // Activate dimension value editing on double click
614       ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
615       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
616       // Find corresponded widget to activate value editing
617       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
618         if (aWgt->attributeID() == SketchPlugin_Constraint::VALUE() ||
619             aWgt->attributeID() == SketchPlugin_ConstraintAngle::ANGLE_VALUE_ID()) {
620           PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
621           if (anEditor)
622             anEditor->showPopupEditor();
623           return;
624         }
625       }
626     }
627   }
628 }
629
630 void PartSet_SketcherMgr::onApplicationStarted()
631 {
632   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
633   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
634   XGUI_Workshop* aWorkshop = aConnector->workshop();
635   PartSet_SketcherReetntrantMgr* aReentranceMgr = myModule->sketchReentranceMgr();
636
637   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
638   if (aPropertyPanel) {
639     //connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
640     //        this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
641
642     connect(aPropertyPanel, SIGNAL(noMoreWidgets(const std::string&)),
643             aReentranceMgr, SLOT(onNoMoreWidgets(const std::string&)));
644     connect(aPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
645             aReentranceMgr, SLOT(onWidgetActivated()));
646   }
647
648   XGUI_ViewerProxy* aViewerProxy = aWorkshop->viewer();
649   connect(aViewerProxy, SIGNAL(enterViewPort()), this, SLOT(onEnterViewPort()));
650   connect(aViewerProxy, SIGNAL(leaveViewPort()), this, SLOT(onLeaveViewPort()));
651
652   XGUI_ContextMenuMgr* aContextMenuMgr = aWorkshop->contextMenuMgr();
653   connect(aContextMenuMgr, SIGNAL(beforeContextMenu()), this, SLOT(onBeforeContextMenu()));
654   connect(aContextMenuMgr, SIGNAL(afterContextMenu()), this, SLOT(onAfterContextMenu()));
655 }
656
657 //void PartSet_SketcherMgr::onBeforeWidgetActivated(ModuleBase_ModelWidget* theWidget)
658 //{
659   //if (!myClickedPoint.myIsInitialized)
660   //  return;
661
662   //ModuleBase_Operation* aOperation = getCurrentOperation();
663   // the distance constraint feature should not use the clickedd point
664   // this is workaround in order to don't throw down the flyout point value,
665   // set by execute() method of these type of features
666   //if (isDistanceOperation(aOperation))
667   //  return;
668
669   //PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(theWidget);
670   //if (aPnt2dWgt) {
671   //  aPnt2dWgt->setPoint(myClickedPoint.myCurX, myClickedPoint.myCurY);
672   //}
673 //}
674
675 void PartSet_SketcherMgr::onBeforeContextMenu()
676 {
677   myIsPopupMenuActive = true;
678 }
679
680 void PartSet_SketcherMgr::onAfterContextMenu()
681 {
682   myIsPopupMenuActive = false;
683 }
684
685 void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent, 
686                                      Point& thePoint)
687 {
688   Handle(V3d_View) aView = theWnd->v3dView();
689   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
690   double aX, anY;
691   PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, anY);
692   thePoint.setValue(aX, anY);
693 }
694
695 void PartSet_SketcherMgr::launchEditing()
696 {
697   if (!myCurrentSelection.empty()) {
698     FeaturePtr aFeature = myCurrentSelection.begin().key();
699     std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
700               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
701     if (aSPFeature && (!aSPFeature->isExternal())) {
702       myModule->editFeature(aSPFeature);
703     }
704   }
705 }
706
707 bool PartSet_SketcherMgr::sketchSolverError()
708 {
709   bool anError = false;
710   CompositeFeaturePtr aSketch = activeSketch();
711   if (aSketch.get()) {
712     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
713     anError = !aAttributeString->value().empty();
714   }
715   return anError;
716 }
717
718 QString PartSet_SketcherMgr::getFeatureError(const FeaturePtr& theFeature)
719 {
720   QString anError = "";
721   if (!theFeature.get() || !theFeature->data()->isValid())
722     return anError;
723
724   CompositeFeaturePtr aSketch = activeSketch();
725   if (aSketch.get() && aSketch == theFeature) {
726     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
727     anError = aAttributeString->value().c_str();
728   }
729   return anError;
730 }
731
732 void PartSet_SketcherMgr::clearClickedFlags()
733 {
734   //myClickedPoint.clear();
735   myCurrentPoint.clear();
736 }
737
738 const QStringList& PartSet_SketcherMgr::sketchOperationIdList()
739 {
740   static QStringList aIds;
741   if (aIds.size() == 0) {
742     aIds << SketchPlugin_Line::ID().c_str();
743     aIds << SketchPlugin_Point::ID().c_str();
744     aIds << SketchPlugin_Arc::ID().c_str();
745     aIds << SketchPlugin_Circle::ID().c_str();
746     aIds << SketchPlugin_ConstraintFillet::ID().c_str();
747     aIds << SketchPlugin_IntersectionPoint::ID().c_str();
748     // TODO
749     // SketchRectangle is a python feature, so its ID is passed just as a string
750     aIds << "SketchRectangle";
751     aIds.append(constraintsIdList());
752   }
753   return aIds;
754 }
755
756 const QStringList& PartSet_SketcherMgr::constraintsIdList()
757 {
758   static QStringList aIds;
759   if (aIds.size() == 0) {
760     aIds << SketchPlugin_ConstraintLength::ID().c_str();
761     aIds << SketchPlugin_ConstraintDistance::ID().c_str();
762     aIds << SketchPlugin_ConstraintRigid::ID().c_str();
763     aIds << SketchPlugin_ConstraintRadius::ID().c_str();
764     aIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
765     aIds << SketchPlugin_ConstraintParallel::ID().c_str();
766     aIds << SketchPlugin_ConstraintHorizontal::ID().c_str();
767     aIds << SketchPlugin_ConstraintVertical::ID().c_str();
768     aIds << SketchPlugin_ConstraintEqual::ID().c_str();
769     aIds << SketchPlugin_ConstraintTangent::ID().c_str();
770     aIds << SketchPlugin_ConstraintCoincidence::ID().c_str();
771     aIds << SketchPlugin_ConstraintMirror::ID().c_str();
772     aIds << SketchPlugin_ConstraintAngle::ID().c_str();
773     aIds << SketchPlugin_MultiRotation::ID().c_str();
774     aIds << SketchPlugin_MultiTranslation::ID().c_str();
775     aIds << SketchPlugin_ConstraintCollinear::ID().c_str();
776     aIds << SketchPlugin_ConstraintMiddle::ID().c_str();
777   }
778   return aIds;
779 }
780
781 void PartSet_SketcherMgr::sketchSelectionModes(QIntList& theModes)
782 {
783   theModes.clear();
784
785   theModes.append(SketcherPrs_Tools::Sel_Dimension_Text);
786   theModes.append(SketcherPrs_Tools::Sel_Dimension_Line);
787   theModes.append(SketcherPrs_Tools::Sel_Constraint);
788   theModes.append(TopAbs_VERTEX);
789   theModes.append(TopAbs_EDGE);
790 }
791
792 Handle(AIS_InteractiveObject) PartSet_SketcherMgr::createPresentation(const ResultPtr& theResult)
793 {
794   Handle(AIS_InteractiveObject) aPrs;
795
796   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
797   if (aFeature.get() && aFeature->getKind() == SketchPlugin_Sketch::ID()) {
798     aPrs = new PartSet_ResultSketchPrs(theResult);
799   }
800   return aPrs;
801 }
802
803 bool PartSet_SketcherMgr::isSketchOperation(ModuleBase_Operation* theOperation)
804 {
805   return theOperation && theOperation->id().toStdString() == SketchPlugin_Sketch::ID();
806 }
807
808 bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation)
809 {
810   return theOperation &&
811          PartSet_SketcherMgr::sketchOperationIdList().contains(theOperation->id());
812 }
813
814 bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation)
815 {
816   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
817                                                                (theOperation);
818   return aFOperation && !aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
819 }
820
821 bool PartSet_SketcherMgr::isNestedEditOperation(ModuleBase_Operation* theOperation)
822 {
823   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
824                                                                (theOperation);
825   return aFOperation && aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
826 }
827
828 bool PartSet_SketcherMgr::isEntity(const std::string& theId)
829 {
830   return (theId == SketchPlugin_Line::ID()) ||
831          (theId == SketchPlugin_Point::ID()) ||
832          (theId == SketchPlugin_Arc::ID()) ||
833          (theId == SketchPlugin_Circle::ID());
834 }
835
836 bool PartSet_SketcherMgr::isDistanceOperation(ModuleBase_Operation* theOperation)
837 {
838   std::string anId = theOperation ? theOperation->id().toStdString() : "";
839
840   return isDistanceKind(anId);
841 }
842
843 bool PartSet_SketcherMgr::isDistanceKind(std::string& theKind)
844 {
845   return (theKind == SketchPlugin_ConstraintLength::ID()) ||
846          (theKind == SketchPlugin_ConstraintDistance::ID()) ||
847          (theKind == SketchPlugin_ConstraintRadius::ID()) ||
848          (theKind == SketchPlugin_ConstraintAngle::ID());
849 }
850
851 void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
852 {
853   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
854                                                                (getCurrentOperation());
855   if (!aFOperation)
856     return;
857
858   myModule->onViewTransformed();
859
860   // Display all sketcher sub-Objects
861   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFOperation->feature());
862   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
863
864   // Hide sketcher result
865   std::list<ResultPtr> aResults = myCurrentSketch->results();
866   std::list<ResultPtr>::const_iterator aIt;
867   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
868     (*aIt)->setDisplayed(false);
869   }
870   myCurrentSketch->setDisplayed(false);
871
872   // Display sketcher objects
873   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
874     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
875     std::list<ResultPtr> aResults = aFeature->results();
876     std::list<ResultPtr>::const_iterator aIt;
877     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
878       (*aIt)->setDisplayed(true);
879     }
880     aFeature->setDisplayed(true);
881   }
882
883   if(myCirclePointFilter.IsNull()) {
884     myCirclePointFilter = new PartSet_CirclePointFilter(myModule->workshop());
885   }
886
887   myModule->workshop()->viewer()->addSelectionFilter(myCirclePointFilter);
888
889   if (myPlaneFilter.IsNull()) 
890     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
891
892   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
893   bool aHasPlane = false;
894   std::shared_ptr<GeomAPI_Pln> aPln;
895   aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
896   myPlaneFilter->setPlane(aPln);
897
898   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
899   // all displayed objects should be activated in current selection modes according to switched
900   // plane filter
901   if (aPln.get())
902     aConnector->activateModuleSelectionModes();
903 }
904
905 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
906 {
907   myIsMouseOverWindow = false;
908   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
909   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
910   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
911
912   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
913
914   DataPtr aData = myCurrentSketch->data();
915   if (!aData->isValid()) {
916     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
917     // The sketch was aborted
918     myCurrentSketch = CompositeFeaturePtr();
919     // TODO: move this outside of if-else
920     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
921     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
922
923     // Erase all sketcher objects
924     QStringList aSketchIds = sketchOperationIdList();
925     QObjectPtrList aObjects = aDisplayer->displayedObjects();
926     foreach (ObjectPtr aObj, aObjects) {
927       DataPtr aObjData = aObj->data();
928       if (!aObjData->isValid())
929         aObj->setDisplayed(false);
930     }
931   }
932   else {
933     // Hide all sketcher sub-Objects
934     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
935       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
936       std::list<ResultPtr> aResults = aFeature->results();
937       std::list<ResultPtr>::const_iterator aIt;
938       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
939         (*aIt)->setDisplayed(false);
940       }
941       aFeature->setDisplayed(false);
942     }
943     // Display sketcher result
944     std::list<ResultPtr> aResults = myCurrentSketch->results();
945     std::list<ResultPtr>::const_iterator aIt;
946     Events_Loop* aLoop = Events_Loop::loop();
947     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
948
949     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
950                                                                            (theOperation);
951     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
952       if (!aFOperation->isDisplayedOnStart(*aIt)) {
953         (*aIt)->setDisplayed(true);
954         // this display event is needed because sketch already may have "displayed" state,
955         // but not displayed while it is still active (issue 613, abort of existing sketch)
956         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
957       }
958     }
959     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
960       myCurrentSketch->setDisplayed(true);
961     
962     myCurrentSketch = CompositeFeaturePtr();
963
964     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
965     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
966
967     Events_Loop::loop()->flush(aDispEvent);
968   }
969   // restore the module selection modes, which were changed on startSketch
970   aConnector->activateModuleSelectionModes();
971 }
972
973 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
974 {
975   if (canChangeCursor(theOperation) && myIsMouseOverWindow) {
976     QCursor* aCurrentCursor = QApplication::overrideCursor();
977     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
978       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
979 #ifdef DEBUG_CURSOR
980       qDebug("startNestedSketch() : Qt::CrossCursor");
981 #endif
982     }
983   }
984 }
985
986 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
987 {
988   myIsMouseOverViewProcessed = true;
989   operationMgr()->onValidateOperation();
990   if (canChangeCursor(theOperation)) {
991     QApplication::restoreOverrideCursor();
992 #ifdef DEBUG_CURSOR
993     qDebug("stopNestedSketch() : None");
994 #endif
995   }
996 }
997
998 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
999 {
1000   if (isNestedCreateOperation(theOperation)) {
1001     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1002                                                                              (theOperation);
1003     if (aFOperation) {
1004       FeaturePtr aFeature = aFOperation->feature();
1005       // it is necessary to check the the feature data validity because
1006       // some kind of features are removed by an operation commit(the macro state of a feature)
1007       if (aFeature.get() && aFeature->data()->isValid()) {
1008         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
1009       }
1010     }
1011   }
1012 }
1013
1014 void PartSet_SketcherMgr::activatePlaneFilter(const bool& toActivate)
1015 {
1016   if (toActivate)
1017     myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
1018   else
1019     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
1020 }
1021
1022 bool PartSet_SketcherMgr::operationActivatedByPreselection()
1023 {
1024   bool isOperationStopped = false;
1025   ModuleBase_Operation* anOperation = getCurrentOperation();
1026   if(anOperation && PartSet_SketcherMgr::isNestedSketchOperation(anOperation)) {
1027     // Set final definitions if they are necessary
1028     //propertyPanelDefined(aOperation);
1029     /// Commit sketcher operations automatically
1030     /// distance operation are able to show popup editor to modify the distance value
1031     /// after entering the value, the operation should be committed/aborted(by Esc key)
1032     bool aCanCommitOperation = true;
1033     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1034                                                                             (anOperation);
1035     if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation)) {
1036       bool aValueAccepted = setDistanceValueByPreselection(anOperation, myModule->workshop(),
1037                                                            aCanCommitOperation);
1038       if (!aValueAccepted)
1039         return isOperationStopped;
1040     }
1041
1042     if (aCanCommitOperation)
1043       isOperationStopped = anOperation->commit();
1044     else {
1045       anOperation->abort();
1046       isOperationStopped = true;
1047     }
1048   }
1049   return isOperationStopped;
1050 }
1051
1052 bool PartSet_SketcherMgr::canUndo() const
1053 {
1054   return isNestedCreateOperation(getCurrentOperation());
1055 }
1056
1057 bool PartSet_SketcherMgr::canRedo() const
1058 {
1059   return isNestedCreateOperation(getCurrentOperation());
1060 }
1061
1062 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1063 {
1064   bool aCanErase = true;
1065   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1066   if (myCurrentSketch.get()) {
1067     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1068     if (aResult.get()) {
1069       // Display sketcher objects
1070       for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1071
1072         FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1073         std::list<ResultPtr> aResults = aFeature->results();
1074         std::list<ResultPtr>::const_iterator anIt;
1075         for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1076           aCanErase = *anIt != aResult;
1077         }
1078       }
1079     }
1080   }
1081   return aCanErase;
1082 }
1083
1084 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1085 {
1086   bool aCanDisplay = true;
1087
1088   bool aHasActiveSketch = activeSketch().get() != NULL;
1089   if (aHasActiveSketch) {
1090     // 1. the sketch feature should not be displayed during the sketch active operation
1091     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch 
1092     // nested features can be visualized
1093     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1094     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1095       aCanDisplay = false;
1096     }
1097     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1098                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1099     /// some sketch entities should be never shown, e.g. projection feature
1100     if (aSketchFeature.get())
1101       aCanDisplay = aSketchFeature->canBeDisplayed();
1102   }
1103   else { // there are no an active sketch
1104     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1105     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1106     if (aFeature.get() != NULL) {
1107       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1108                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1109       if (aSketchFeature.get()) {
1110         aCanDisplay = false;
1111       }
1112     }
1113   }
1114
1115   // 3. the method should not filter the objects, which are not related to the current operation.
1116   // The object is filtered just if it is a current operation feature or this feature result
1117   if (aCanDisplay) {
1118     bool isObjectFound = false;
1119     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1120                                                                  (getCurrentOperation());
1121     if (aFOperation) {
1122       FeaturePtr aFeature = aFOperation->feature();
1123       if (aFeature.get()) {
1124         std::list<ResultPtr> aResults = aFeature->results();
1125         if (theObject == aFeature)
1126           isObjectFound = true;
1127         else {
1128           std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1129           for (; anIt != aLast && !isObjectFound; anIt++) {
1130             isObjectFound = *anIt == theObject;
1131           }
1132         }
1133       }
1134     }
1135     if (isObjectFound) {
1136       // 4. For created nested feature operation do not display the created feature if
1137       // the mouse curstor leaves the OCC window.
1138       // The correction cases, which ignores this condition:
1139       // a. the property panel values modification
1140       // b. the popup menu activated
1141       // c. widget editor control
1142       #ifndef DEBUG_DO_NOT_BY_ENTER
1143       if (isNestedCreateOperation(getCurrentOperation())) {
1144         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1145         ModuleBase_WidgetEditor* anEditorWdg = anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1146         // the active widget editor should not influence here. The presentation should be visible always
1147         // when this widget is active.
1148         if (!anEditorWdg && !myIsPopupMenuActive) {
1149           // during a nested create operation, the feature is redisplayed only if the mouse over view
1150           // of there was a value modified in the property panel after the mouse left the view
1151           aCanDisplay = canDisplayCurrentCreatedFeature();
1152         }
1153       }
1154       #endif
1155     }
1156   }
1157
1158   // checks the sketcher constraints visibility according to active sketch check box states
1159   if (aCanDisplay) {
1160     bool aProcessed = false;
1161     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1162     if (aFeature.get()) {
1163       bool aConstraintDisplayed = canDisplayConstraint(aFeature, PartSet_Tools::Any, aProcessed);
1164       if (aProcessed)
1165         aCanDisplay = aConstraintDisplayed;
1166     }
1167   }
1168
1169   return aCanDisplay;
1170 }
1171
1172 bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
1173                                              const PartSet_Tools::ConstraintVisibleState& theState,
1174                                              bool& isProcessed) const
1175 {
1176   bool aSwitchedOn = true;
1177
1178   const QStringList& aConstrIds = constraintsIdList();
1179
1180   std::string aKind = theFeature->getKind();
1181   if (aConstrIds.contains(QString(aKind.c_str()))) {
1182     bool isTypedConstraint = false;
1183
1184     switch (theState) {
1185       case PartSet_Tools::Dimensional: {
1186         bool isDistance = isDistanceKind(aKind);
1187         if (isDistance) {
1188           isProcessed = true;
1189           aSwitchedOn = myIsConstraintsShown[theState];
1190         }
1191       }
1192       break;
1193       case PartSet_Tools::Geometrical: {
1194         bool isGeometrical = !isDistanceKind(aKind);
1195         if (isGeometrical) {
1196           isProcessed = true;
1197           aSwitchedOn = myIsConstraintsShown[theState];
1198         }
1199       }
1200       break;
1201       case PartSet_Tools::Any: {
1202         isProcessed = true;
1203         bool isDistance = isDistanceKind(aKind);
1204         if (isDistance)
1205           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Dimensional];
1206         else
1207           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Geometrical];
1208       }
1209       break;
1210     default:
1211       break;
1212     }
1213   }
1214   return aSwitchedOn;
1215 }
1216
1217 /*void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
1218 {
1219   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1220                                                                            (getCurrentOperation());
1221   if (aFOperation && myCurrentSketch.get()) {
1222     // find results of the current operation
1223     // these results should not be proposed to be deleted
1224     FeaturePtr anOperationFeature = aFOperation->feature();
1225     std::list<ResultPtr> anOperationResultList = anOperationFeature->results();
1226     std::set<ResultPtr> anOperationResults;
1227     std::list<ResultPtr>::const_iterator aRIt = anOperationResultList.begin(),
1228                                         aRLast = anOperationResultList.end();
1229     for (; aRIt != aRLast; aRIt++)
1230       anOperationResults.insert(*aRIt);
1231
1232     std::set<FeaturePtr> anObjectsToBeDeleted;
1233     QStringList anObjectsToBeDeletedNames;
1234     std::list<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1235     for (; anIt != aLast; anIt++) {
1236       ObjectPtr anObject = *anIt;
1237       bool aCanErase = true;
1238       // when the sketch operation is active, results of sketch sub-feature can not be hidden
1239       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1240       // the result is found between current feature results
1241       if (anOperationResults.find(aResult) != anOperationResults.end())
1242         continue;
1243
1244       if (aResult.get()) {
1245         // Display sketcher objects
1246         for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1247           FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1248           std::list<ResultPtr> aResults = aFeature->results();
1249           std::list<ResultPtr>::const_iterator anIt;
1250           for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1251             aCanErase = *anIt != aResult;
1252           }
1253         }
1254       }
1255       if (!aCanErase) {
1256         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
1257         if (aFeature.get() && anObjectsToBeDeleted.find(aFeature) == anObjectsToBeDeleted.end()) {
1258           anObjectsToBeDeleted.insert(aFeature);
1259           anObjectsToBeDeletedNames.append(aFeature->name().c_str());
1260         }
1261       }
1262     }
1263     if (!anObjectsToBeDeleted.empty()) {
1264       QString aFeatureNames = anObjectsToBeDeletedNames.join(", ");
1265       QString aMessage = tr("The following features have incorrect presentation and \
1266 will be hidden: %1. Would you like to delete them?")
1267                          .arg(aFeatureNames);
1268       int anAnswer = QMessageBox::question(qApp->activeWindow(), tr("Features hide"),
1269                                            aMessage, QMessageBox::Ok | QMessageBox::Cancel,
1270                                            QMessageBox::Cancel);
1271       if (anAnswer == QMessageBox::Ok) {
1272         QObjectPtrList anObjects;
1273         std::set<FeaturePtr>::const_iterator anIt = anObjectsToBeDeleted.begin(),
1274                                              aLast = anObjectsToBeDeleted.end();
1275         for (; anIt != aLast; anIt++)
1276           anObjects.append(*anIt);
1277         SessionPtr aMgr = ModelAPI_Session::get();
1278         DocumentPtr aDoc = aMgr->activeDocument();
1279         bool aIsOp = aMgr->isOperation();
1280         if (!aIsOp)
1281           aMgr->startOperation();
1282         workshop()->deleteFeatures(anObjects);
1283         //static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
1284         //static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
1285         //Events_Loop::loop()->flush(aDeletedEvent);
1286         //Events_Loop::loop()->flush(aRedispEvent);
1287
1288         if (!aIsOp)
1289           aMgr->finishOperation();
1290       }
1291     }
1292   }
1293 }*/
1294
1295 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1296 {
1297   bool aCanDisplay = myIsMouseOverWindow;
1298   if (!aCanDisplay) {
1299     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1300     if (anActiveWidget)
1301       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1302   }
1303   return aCanDisplay;
1304 }
1305
1306 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1307 {
1308   return isNestedCreateOperation(theOperation) ||
1309          myModule->sketchReentranceMgr()->isInternalEditActive();
1310 }
1311
1312 const QMap<PartSet_Tools::ConstraintVisibleState, bool>& PartSet_SketcherMgr::showConstraintStates()
1313 {
1314   return myIsConstraintsShown;
1315 }
1316
1317 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1318 {
1319   bool isFoundObject = false;
1320
1321   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1322   if (anObjectFeature.get()) {
1323     int aSize = myCurrentSketch->numberOfSubs();
1324     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1325       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1326       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1327     }
1328   }
1329   return isFoundObject;
1330 }
1331
1332 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
1333 {
1334   if (myPlaneFilter.IsNull()) 
1335    myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
1336
1337   myPlaneFilter->setPlane(thePln);
1338 }
1339
1340 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
1341                                                          ModuleBase_IWorkshop* theWorkshop,
1342                                                          bool& theCanCommitOperation)
1343 {
1344   bool isValueAccepted = false;
1345   theCanCommitOperation = false;
1346
1347   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1348                                                                               (theOperation);
1349   FeaturePtr aFeature = aFOperation->feature();
1350   // editor is shown only if all attribute references are filled by preseletion
1351   bool anAllRefAttrInitialized = true;
1352
1353   std::list<AttributePtr> aRefAttrs = aFeature->data()->attributes(
1354                                               ModelAPI_AttributeRefAttr::typeId());
1355   std::list<AttributePtr>::const_iterator anIt = aRefAttrs.begin(), aLast = aRefAttrs.end();
1356   for (; anIt != aLast && anAllRefAttrInitialized; anIt++) {
1357     anAllRefAttrInitialized = (*anIt)->isInitialized();
1358   }
1359   if (anAllRefAttrInitialized) {
1360     // Activate dimension value editing on double click
1361     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
1362     QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
1363     // Find corresponded widget to activate value editing
1364     foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
1365       if (aWgt->attributeID() == "ConstraintValue") {
1366         // the featue should be displayed in order to find the AIS text position,
1367         // the place where the editor will be shown
1368         aFeature->setDisplayed(true);
1369         /// the execute is necessary to perform in the feature compute for flyout position
1370         aFeature->execute();
1371
1372         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1373         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1374
1375         PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
1376         if (anEditor) {
1377           int aX = 0, anY = 0;
1378
1379           XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(theWorkshop);
1380           XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1381           AISObjectPtr anAIS = aDisplayer->getAISObject(aFeature);
1382           Handle(AIS_InteractiveObject) anAISIO;
1383           if (anAIS.get() != NULL) {
1384             anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1385           }
1386           if (anAIS.get() != NULL) {
1387             Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1388
1389             if (!anAISIO.IsNull()) {
1390               Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAISIO);
1391               if (!aDim.IsNull()) {
1392                 gp_Pnt aPosition = aDim->GetTextPosition();
1393
1394                 ModuleBase_IViewer* aViewer = aWorkshop->viewer();
1395                 Handle(V3d_View) aView = aViewer->activeView();
1396                 int aCX, aCY;
1397                 aView->Convert(aPosition.X(), aPosition.Y(), aPosition.Z(), aCX, aCY);
1398
1399                 QWidget* aViewPort = aViewer->activeViewPort();
1400                 QPoint aGlPoint = aViewPort->mapToGlobal(QPoint(aCX, aCY));
1401                 aX = aGlPoint.x();
1402                 anY = aGlPoint.y();
1403               }
1404             }
1405             anEditor->setCursorPosition(aX, anY);
1406             isValueAccepted = anEditor->showPopupEditor(false);
1407             theCanCommitOperation = true;
1408           }
1409         }
1410       }
1411     }
1412   }
1413   return isValueAccepted;
1414 }
1415
1416 void PartSet_SketcherMgr::getCurrentSelection(const FeaturePtr& theFeature,
1417                                               const FeaturePtr& theSketch,
1418                                               ModuleBase_IWorkshop* theWorkshop,
1419                                               FeatureToSelectionMap& theSelection)
1420 {
1421   if (theFeature.get() == NULL)
1422     return;
1423
1424   std::set<AttributePtr> aSelectedAttributes;
1425   std::set<ResultPtr> aSelectedResults;
1426
1427   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1428   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
1429   if (!aContext.IsNull()) {
1430     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1431     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1432
1433     std::list<ResultPtr> aResults = theFeature->results();
1434     std::list<ResultPtr>::const_iterator aIt;
1435     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1436     {
1437       ResultPtr aResult = *aIt;
1438       AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1439       if (aAISObj.get() == NULL)
1440         continue;
1441       Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1442       for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
1443       {
1444         Handle(SelectMgr_EntityOwner) anOwner = aContext->SelectedOwner();
1445         if (anOwner->Selectable() != anAISIO)
1446           continue;
1447         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1448                                aSelectedAttributes, aSelectedResults);
1449       }
1450       for (aContext->InitDetected(); aContext->MoreDetected(); aContext->NextDetected()) {
1451         Handle(SelectMgr_EntityOwner) anOwner = aContext->DetectedOwner();
1452         if (anOwner.IsNull())
1453           continue;
1454         if (anOwner->Selectable() != anAISIO)
1455           continue;
1456         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1457                                aSelectedAttributes, aSelectedResults);
1458       }
1459     }
1460   }
1461   theSelection[theFeature] = std::make_pair(aSelectedAttributes, aSelectedResults);
1462 }
1463
1464 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1465                                              const FeaturePtr& theSketch,
1466                                              ModuleBase_IWorkshop* theWorkshop,
1467                                              const FeatureToSelectionMap& theSelection,
1468                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1469 {
1470   if (theFeature.get() == NULL)
1471     return;
1472
1473   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1474   std::set<AttributePtr> aSelectedAttributes = anIt.value().first;
1475   std::set<ResultPtr> aSelectedResults = anIt.value().second;
1476
1477   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1478
1479   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1480   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1481
1482   // 1. found the feature's owners. Check the AIS objects of the constructions
1483   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1484   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1485     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1486
1487     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1488     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1489     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1490       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1491       if (!anOwner.IsNull())
1492         theOwnersToSelect.Add(anOwner);
1493     }
1494   }
1495
1496   // 2. found the feature results's owners
1497   std::list<ResultPtr> aResults = theFeature->results();
1498   std::list<ResultPtr>::const_iterator aIt;
1499   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1500   {
1501     ResultPtr aResult = *aIt;
1502     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1503     if (aAISObj.get() == NULL)
1504       continue; 
1505     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1506
1507     SelectMgr_IndexedMapOfOwner aSelectedOwners;  
1508     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1509     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1510       Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1511       if ( anOwner.IsNull() || !anOwner->HasShape() )
1512         continue;
1513       const TopoDS_Shape& aShape = anOwner->Shape();
1514       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1515       if (aShapeType == TopAbs_VERTEX) {
1516         AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1517         if (aPntAttr.get() != NULL &&
1518             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end()) {
1519           theOwnersToSelect.Add(anOwner);
1520         }
1521       }
1522       else if (aShapeType == TopAbs_EDGE) {
1523         bool aFound = aSelectedResults.find(aResult) != aSelectedResults.end();
1524         if (aSelectedResults.find(aResult) != aSelectedResults.end() &&
1525             theOwnersToSelect.FindIndex(anOwner) <= 0)
1526           theOwnersToSelect.Add(anOwner);
1527       }
1528     }
1529   }
1530 }
1531
1532 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget, const bool isToConnect)
1533 {
1534   if (isToConnect) {
1535     connect(theWidget, SIGNAL(beforeValuesChanged()),
1536             this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1537     connect(theWidget, SIGNAL(afterValuesChanged()),
1538             this, SLOT(onAfterValuesChangedInPropertyPanel()));
1539   }
1540   else {
1541     disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1542                 this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1543     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1544                 this, SLOT(onAfterValuesChangedInPropertyPanel()));
1545   }
1546 }
1547
1548 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1549 {
1550   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1551                                                                            (getCurrentOperation());
1552   if (aFOperation) {
1553     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1554         PartSet_SketcherMgr::isNestedSketchOperation(aFOperation) &&
1555         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1556       FeaturePtr aFeature = aFOperation->feature();
1557       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1558     }
1559   }
1560 }
1561
1562 void PartSet_SketcherMgr::customizePresentation(const ObjectPtr& theObject)
1563 {
1564   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1565                                                                            (getCurrentOperation());
1566   if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1567                       PartSet_SketcherMgr::isNestedSketchOperation(aFOperation)))
1568     SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
1569 }
1570
1571 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1572 {
1573   return myModule->workshop()->currentOperation();
1574 }
1575
1576 //**************************************************************
1577 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1578 {
1579   ModuleBase_ModelWidget* aWidget = 0;
1580   ModuleBase_Operation* anOperation = getCurrentOperation();
1581   if (anOperation) {
1582     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1583     if (aPanel)
1584       aWidget = aPanel->activeWidget();
1585   }
1586   return aWidget;
1587 }
1588
1589 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1590                                            const bool isEditOperation,
1591                                            const bool isToDisplay,
1592                                            const bool isFlushRedisplay)
1593 {
1594   #ifdef DEBUG_DO_NOT_BY_ENTER
1595   return;
1596   #endif
1597
1598   if (isEditOperation || !theFeature.get())
1599     return;
1600
1601   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1602   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1603
1604   // 1. change visibility of the object itself, here the presentable object is processed,
1605   // e.g. constraints features
1606   //FeaturePtr aFeature = aFOperation->feature();
1607   std::list<ResultPtr> aResults = theFeature->results();
1608   if (isToDisplay)
1609     theFeature->setDisplayed(true);
1610   else
1611     theFeature->setDisplayed(false);
1612
1613   // change visibility of the object results, e.g. non-constraint features
1614   std::list<ResultPtr>::const_iterator aIt;
1615   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1616     if (isToDisplay) {
1617       (*aIt)->setDisplayed(true);
1618     }
1619     else {
1620       (*aIt)->setDisplayed(false);
1621     }
1622   }
1623   if (isFlushRedisplay)
1624     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1625 }
1626
1627 void PartSet_SketcherMgr::storeSelection(const bool theHighlightedOnly)
1628 {
1629   if (!myCurrentSketch.get())
1630     return;
1631
1632   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1633   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1634   QList<ModuleBase_ViewerPrsPtr> aHighlighted = aSelect->getHighlighted();
1635
1636   QList<FeaturePtr> aFeatureList;
1637   if (theHighlightedOnly) {
1638     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1639   }
1640   else {
1641     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1642
1643     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(ModuleBase_ISelection::AllControls);
1644     fillFeatureList(aSelected, myCurrentSketch, aFeatureList);
1645   }
1646
1647   // 1. it is necessary to save current selection in order to restore it after the features moving
1648   myCurrentSelection.clear();
1649   QList<FeaturePtr>::const_iterator anIt = aFeatureList.begin(), aLast = aFeatureList.end();
1650   for (; anIt != aLast; anIt++) {
1651     getCurrentSelection(*anIt, myCurrentSketch, aWorkshop, myCurrentSelection);
1652   }
1653   //qDebug(QString("  storeSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1654 }
1655
1656 void PartSet_SketcherMgr::restoreSelection()
1657 {
1658   if (!myCurrentSketch.get())
1659     return;
1660
1661   //qDebug(QString("restoreSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1662   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1663   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1664   FeatureToSelectionMap::const_iterator aSIt = myCurrentSelection.begin(),
1665                                         aSLast = myCurrentSelection.end();
1666   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1667   for (; aSIt != aSLast; aSIt++) {
1668     anOwnersToSelect.Clear();
1669     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, myCurrentSelection,
1670                         anOwnersToSelect);
1671     aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1672   }
1673 }
1674
1675 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
1676 {
1677   PartSet_Tools::ConstraintVisibleState aType = (PartSet_Tools::ConstraintVisibleState)theType;
1678
1679   updateBySketchParameters(aType, theState);
1680 }
1681
1682 void PartSet_SketcherMgr::updateBySketchParameters(
1683                                    const PartSet_Tools::ConstraintVisibleState& theType,
1684                                    bool theState)
1685 {
1686   if (myCurrentSketch.get() == NULL)
1687     return;
1688
1689   bool aPrevState = myIsConstraintsShown[theType];
1690   myIsConstraintsShown[theType] = theState;
1691
1692   switch (theType) {
1693     case PartSet_Tools::Geometrical:
1694     case PartSet_Tools::Dimensional: {
1695       if (aPrevState != theState) {
1696         ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1697         XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1698         for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1699           FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1700           bool aProcessed = false;
1701           bool aConstraintDisplayed = canDisplayConstraint(aSubFeature, theType, aProcessed);
1702           if (aProcessed)
1703             aSubFeature->setDisplayed(aConstraintDisplayed);
1704         }
1705         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1706       }
1707     }
1708     break;
1709     case PartSet_Tools::Expressions: {
1710       if (aPrevState != theState) {
1711         /// call all sketch features redisplay, the expression state will be corrected in customize
1712         /// of distance presentation
1713         Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1714         PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
1715       }
1716     }
1717     break;
1718   }
1719 }
1720
1721 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
1722 {
1723   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1724   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1725   return aConnector->workshop();
1726 }
1727
1728 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1729 {
1730   return workshop()->operationMgr();
1731 }
1732