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