Salome HOME
ModuleBase_ViewerPrs is wrapped into shared_ptr: remove include of this class from...
[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   // it is important to validate operation here only if sketch entity create operation is active
251   // because at this operation we reacts to the mouse leave/enter view port
252   //operationMgr()->onValidateOperation();
253
254   #ifdef DEBUG_DO_NOT_BY_ENTER
255   return;
256   #endif
257
258   if (canChangeCursor(getCurrentOperation())) {
259     QApplication::restoreOverrideCursor();
260 #ifdef DEBUG_CURSOR
261     qDebug("onLeaveViewPort() : None");
262 #endif
263   }
264
265   if (!isNestedCreateOperation(getCurrentOperation()))
266     return;
267
268   // the method should be performed if the popup menu is called,
269   // the reset of the current widget should not happen
270   if (myIsPopupMenuActive)
271     return;
272
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     }
391     // Remember highlighted objects for editing
392     ModuleBase_ISelection* aSelect = aWorkshop->selection();
393
394     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
395     storeSelection(!aHasShift);
396
397     if (myCurrentSelection.empty()) {
398       if (isSketchOpe && (!isSketcher))
399         // commit previous operation
400         if (!aFOperation->commit())
401           aFOperation->abort();
402       return;
403     }
404     // Init flyout point for radius rotation
405     FeaturePtr aFeature = myCurrentSelection.begin().key();
406
407     if (isSketcher) {
408       myIsDragging = true;
409       get2dPoint(theWnd, theEvent, myCurrentPoint);
410       myDragDone = false;
411
412       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
413       launchEditing();
414       if (aFeature.get() != NULL) {
415         std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
416                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
417       if (aSPFeature.get() && aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID()) {
418           DataPtr aData = aSPFeature->data();
419           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
420           std::shared_ptr<GeomDataAPI_Point2D> aFPAttr = 
421             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
422           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
423         }
424       }
425     } else if (isSketchOpe && isEditing) {
426       // If selected another object commit current result
427       aFOperation->commit();
428
429       myIsDragging = true;
430       get2dPoint(theWnd, theEvent, myCurrentPoint);
431       myDragDone = false;
432
433       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
434
435       // this is temporary commented in order to avoid the following wrong case:
436       // Distance constraint is under edition, double click on the digit -> nothing happens
437       // because QApplication::processEvents() calls onMouseDoubleClick, which try to show editor
438       // but as the prev edit is commited an new one is not started, editor is not shown.
439       // This is necessary in order to finalize previous operation
440       //QApplication::processEvents();
441       launchEditing();
442     }
443   }
444 }
445
446 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
447 {
448   if (myModule->sketchReentranceMgr()->processMouseReleased(theWnd, theEvent))
449     return;
450
451   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
452   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
453   if (!aViewer->canDragByMouse())
454     return;
455   ModuleBase_Operation* aOp = getCurrentOperation();
456   if (aOp) {
457     if (isNestedSketchOperation(aOp)) {
458       //get2dPoint(theWnd, theEvent, myClickedPoint);
459
460       // Only for sketcher operations
461       if (myIsDragging) {
462         if (myDragDone) {
463           //aOp->commit();
464           myCurrentSelection.clear();
465           /*Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
466           if (!aContext.IsNull()) {
467           // Reselect edited object
468           aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
469           if (theEvent->modifiers() & Qt::ShiftModifier)
470             aContext->ShiftSelect();
471           else
472             aContext->Select();
473           */
474         }
475       }
476     }
477   }
478
479   aWorkshop->viewer()->enableDrawMode(myPreviousDrawModeEnabled);
480   myIsDragging = false;
481 }
482
483 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
484 {
485   if (myModule->sketchReentranceMgr()->processMouseMoved(theWnd, theEvent))
486     return;
487
488   if (isNestedCreateOperation(getCurrentOperation()) && !myIsMouseOverViewProcessed) {
489     myIsMouseOverViewProcessed = true;
490     // 1. perform the widget mouse move functionality and display the presentation
491     // the mouse move should be processed in the widget, if it can in order to visualize correct
492     // presentation. These widgets correct the feature attribute according to the mouse position
493     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
494     PartSet_WidgetPoint2D* aPoint2DWdg = dynamic_cast<PartSet_WidgetPoint2D*>(anActiveWidget);
495     if (aPoint2DWdg) {
496       aPoint2DWdg->onMouseMove(theWnd, theEvent);
497     }
498     PartSet_WidgetPoint2dDistance* aDistanceWdg = dynamic_cast<PartSet_WidgetPoint2dDistance*>
499                                                                 (anActiveWidget);
500     if (aDistanceWdg) {
501       aDistanceWdg->onMouseMove(theWnd, theEvent);
502     }
503     // the feature is to be erased here, but it is correct to call canDisplayObject because
504     // there can be additional check (e.g. editor widget in distance constraint)
505     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
506                                                                              (getCurrentOperation());
507     if (aFOperation) {
508       FeaturePtr aFeature = aFOperation->feature();
509       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
510     }
511   }
512
513   //myClickedPoint.clear();
514
515   if (myIsDragging) {
516     // 1. the current selection is saved in the mouse press method in order to restore it after moving
517     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
518     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
519     // deselected). This flag should be restored in the slot, processed the mouse release signal.
520
521     ModuleBase_Operation* aCurrentOperation = getCurrentOperation();
522     if (!aCurrentOperation)
523       return;
524     if (isSketchOperation(aCurrentOperation))
525       return; // No edit operation activated
526
527     Handle(V3d_View) aView = theWnd->v3dView();
528     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
529     double aX, aY;
530     PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, aY);
531     double dX =  aX - myCurrentPoint.myCurX;
532     double dY =  aY - myCurrentPoint.myCurY;
533
534     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
535     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
536     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
537     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
538     // viewer happens by deselect/select the modified objects. The flag should be restored after
539     // the selection processing. The update viewer should be also called.
540     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
541
542     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
543     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
544     FeatureToSelectionMap::const_iterator anIt = myCurrentSelection.begin(),
545                                           aLast = myCurrentSelection.end();
546     // 4. the features and attributes modification(move)
547     bool isModified = false;
548     for (; anIt != aLast; anIt++) {
549       FeaturePtr aFeature = anIt.key();
550
551       std::set<AttributePtr> anAttributes = anIt.value().first;
552       // Process selection by attribute: the priority to the attribute
553       if (!anAttributes.empty()) {
554         std::set<AttributePtr>::const_iterator anAttIt = anAttributes.begin(),
555                                                anAttLast = anAttributes.end();
556         for (; anAttIt != anAttLast; anAttIt++) {
557           AttributePtr anAttr = *anAttIt;
558           if (anAttr.get() == NULL)
559             continue;
560           std::string aAttrId = anAttr->id();
561           DataPtr aData = aFeature->data();
562           if (aData->isValid()) {
563             std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
564               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
565             if (aPoint.get() != NULL) {
566               bool isImmutable = aPoint->setImmutable(true);
567               aPoint->move(dX, dY);
568               isModified = true;
569               ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
570               aPoint->setImmutable(isImmutable);
571             }
572           }
573         }
574       } else {
575         // Process selection by feature
576         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
577           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
578         if (aSketchFeature) {
579           aSketchFeature->move(dX, dY);
580           isModified = true;
581           ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
582         }
583       }
584     }
585     // the modified state of the current operation should be updated if there are features, which
586     // were changed here
587     if (isModified) {
588       aCurrentOperation->onValuesChanged();
589     }
590     Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
591     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
592
593     // 5. it is necessary to save current selection in order to restore it after the features moving
594     restoreSelection();
595     // 6. restore the update viewer flag and call this update
596     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
597     aDisplayer->updateViewer();
598
599     myDragDone = true;
600     myCurrentPoint.setValue(aX, aY);
601   }
602 }
603
604 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
605 {
606   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
607                                                                (getCurrentOperation());
608   if (aFOperation && aFOperation->isEditOperation()) {
609     std::string aId = aFOperation->id().toStdString();
610     if (isDistanceOperation(aFOperation))
611     {
612       // Activate dimension value editing on double click
613       ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
614       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
615       // Find corresponded widget to activate value editing
616       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
617         if (aWgt->attributeID() == "ConstraintValue") {
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) {
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   aConnector->workshop()->displayer()->activateTrihedron(true);
862
863   // Hide sketcher result
864   std::list<ResultPtr> aResults = myCurrentSketch->results();
865   std::list<ResultPtr>::const_iterator aIt;
866   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
867     (*aIt)->setDisplayed(false);
868   }
869   myCurrentSketch->setDisplayed(false);
870
871   // Display sketcher objects
872   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
873     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
874     std::list<ResultPtr> aResults = aFeature->results();
875     std::list<ResultPtr>::const_iterator aIt;
876     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
877       (*aIt)->setDisplayed(true);
878     }
879     aFeature->setDisplayed(true);
880   }
881
882   if(myCirclePointFilter.IsNull()) {
883     myCirclePointFilter = new PartSet_CirclePointFilter(myModule->workshop());
884   }
885
886   myModule->workshop()->viewer()->addSelectionFilter(myCirclePointFilter);
887
888   if (myPlaneFilter.IsNull()) 
889     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
890
891   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
892   bool aHasPlane = false;
893   std::shared_ptr<GeomAPI_Pln> aPln;
894   if (aFOperation->isEditOperation()) {
895     // If it is editing of sketch then it means that plane is already defined
896     aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
897     if (aPln.get())
898       aHasPlane = true;
899   }
900   myPlaneFilter->setPlane(aPln);
901
902   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
903   // all sketch objects should be activated in the sketch selection modes by edit operation start
904   // in case of creation operation, there is an active widget, which activates own selection mode
905   if (aFOperation->isEditOperation() && aHasPlane)
906     aConnector->activateModuleSelectionModes();
907 }
908
909 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
910 {
911   myIsMouseOverWindow = false;
912   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
913   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
914   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
915
916   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
917
918   DataPtr aData = myCurrentSketch->data();
919   if (!aData->isValid()) {
920     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
921     // The sketch was aborted
922     myCurrentSketch = CompositeFeaturePtr();
923     // TODO: move this outside of if-else
924     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
925     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
926
927     // Erase all sketcher objects
928     QStringList aSketchIds = sketchOperationIdList();
929     QObjectPtrList aObjects = aDisplayer->displayedObjects();
930     foreach (ObjectPtr aObj, aObjects) {
931       DataPtr aObjData = aObj->data();
932       if (!aObjData->isValid())
933         aObj->setDisplayed(false);
934     }
935   }
936   else {
937     // Hide all sketcher sub-Objects
938     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
939       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
940       std::list<ResultPtr> aResults = aFeature->results();
941       std::list<ResultPtr>::const_iterator aIt;
942       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
943         (*aIt)->setDisplayed(false);
944       }
945       aFeature->setDisplayed(false);
946     }
947     // Display sketcher result
948     std::list<ResultPtr> aResults = myCurrentSketch->results();
949     std::list<ResultPtr>::const_iterator aIt;
950     Events_Loop* aLoop = Events_Loop::loop();
951     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
952
953     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
954                                                                            (theOperation);
955     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
956       if (!aFOperation->isDisplayedOnStart(*aIt)) {
957         (*aIt)->setDisplayed(true);
958         // this display event is needed because sketch already may have "displayed" state,
959         // but not displayed while it is still active (issue 613, abort of existing sketch)
960         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
961       }
962     }
963     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
964       myCurrentSketch->setDisplayed(true);
965     
966     myCurrentSketch = CompositeFeaturePtr();
967
968     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
969     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
970
971     Events_Loop::loop()->flush(aDispEvent);
972   }
973   // restore the module selection modes, which were changed on startSketch
974   aConnector->activateModuleSelectionModes();
975   aConnector->workshop()->displayer()->activateTrihedron(false);
976 }
977
978 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
979 {
980   if (canChangeCursor(theOperation) && myIsMouseOverWindow) {
981     QCursor* aCurrentCursor = QApplication::overrideCursor();
982     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
983       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
984 #ifdef DEBUG_CURSOR
985       qDebug("startNestedSketch() : Qt::CrossCursor");
986 #endif
987     }
988   }
989 }
990
991 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
992 {
993   myIsMouseOverViewProcessed = true;
994   operationMgr()->onValidateOperation();
995   if (canChangeCursor(theOperation)) {
996     QApplication::restoreOverrideCursor();
997 #ifdef DEBUG_CURSOR
998     qDebug("stopNestedSketch() : None");
999 #endif
1000   }
1001 }
1002
1003 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
1004 {
1005   if (isNestedCreateOperation(theOperation)) {
1006     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1007                                                                              (theOperation);
1008     if (aFOperation) {
1009       FeaturePtr aFeature = aFOperation->feature();
1010       // it is necessary to check the the feature data validity because
1011       // some kind of features are removed by an operation commit(the macro state of a feature)
1012       if (aFeature.get() && aFeature->data()->isValid()) {
1013         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
1014       }
1015     }
1016   }
1017 }
1018
1019 void PartSet_SketcherMgr::activatePlaneFilter(const bool& toActivate)
1020 {
1021   if (toActivate)
1022     myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
1023   else
1024     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
1025 }
1026
1027 bool PartSet_SketcherMgr::operationActivatedByPreselection()
1028 {
1029   bool isOperationStopped = false;
1030   ModuleBase_Operation* anOperation = getCurrentOperation();
1031   if(anOperation && PartSet_SketcherMgr::isNestedSketchOperation(anOperation)) {
1032     // Set final definitions if they are necessary
1033     //propertyPanelDefined(aOperation);
1034     /// Commit sketcher operations automatically
1035     /// distance operation are able to show popup editor to modify the distance value
1036     /// after entering the value, the operation should be committed/aborted(by Esc key)
1037     bool aCanCommitOperation = true;
1038     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1039                                                                             (anOperation);
1040     if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation))
1041       aCanCommitOperation = setDistanceValueByPreselection(anOperation, myModule->workshop());
1042
1043     if (aCanCommitOperation)
1044       isOperationStopped = anOperation->commit();
1045     else {
1046       anOperation->abort();
1047       isOperationStopped = true;
1048     }
1049   }
1050   return isOperationStopped;
1051 }
1052
1053 bool PartSet_SketcherMgr::canUndo() const
1054 {
1055   return isNestedCreateOperation(getCurrentOperation());
1056 }
1057
1058 bool PartSet_SketcherMgr::canRedo() const
1059 {
1060   return isNestedCreateOperation(getCurrentOperation());
1061 }
1062
1063 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1064 {
1065   bool aCanErase = true;
1066   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1067   if (myCurrentSketch.get()) {
1068     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1069     if (aResult.get()) {
1070       // Display sketcher objects
1071       for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1072
1073         FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1074         std::list<ResultPtr> aResults = aFeature->results();
1075         std::list<ResultPtr>::const_iterator anIt;
1076         for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1077           aCanErase = *anIt != aResult;
1078         }
1079       }
1080     }
1081   }
1082   return aCanErase;
1083 }
1084
1085 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1086 {
1087   bool aCanDisplay = true;
1088
1089   bool aHasActiveSketch = activeSketch().get() != NULL;
1090   if (aHasActiveSketch) {
1091     // 1. the sketch feature should not be displayed during the sketch active operation
1092     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch 
1093     // nested features can be visualized
1094     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1095     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1096       aCanDisplay = false;
1097     }
1098   }
1099   else { // there are no an active sketch
1100     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1101     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1102     if (aFeature.get() != NULL) {
1103       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1104                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1105       if (aSketchFeature.get()) {
1106         aCanDisplay = false;
1107       }
1108     }
1109   }
1110
1111   // 3. the method should not filter the objects, which are not related to the current operation.
1112   // The object is filtered just if it is a current operation feature or this feature result
1113   bool isObjectFound = false;
1114   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1115                                                                (getCurrentOperation());
1116   if (aFOperation) {
1117     FeaturePtr aFeature = aFOperation->feature();
1118     if (aFeature.get()) {
1119       std::list<ResultPtr> aResults = aFeature->results();
1120       if (theObject == aFeature)
1121         isObjectFound = true;
1122       else {
1123         std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1124         for (; anIt != aLast && !isObjectFound; anIt++) {
1125           isObjectFound = *anIt == theObject;
1126         }
1127       }
1128     }
1129   }
1130   if (isObjectFound) {
1131     // 4. For created nested feature operation do not display the created feature if
1132     // the mouse curstor leaves the OCC window.
1133     // The correction cases, which ignores this condition:
1134     // a. the property panel values modification
1135     // b. the popup menu activated
1136     // c. widget editor control
1137     #ifndef DEBUG_DO_NOT_BY_ENTER
1138     if (aCanDisplay && isNestedCreateOperation(getCurrentOperation())) {
1139       ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1140       ModuleBase_WidgetEditor* anEditorWdg = anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1141       // the active widget editor should not influence here. The presentation should be visible always
1142       // when this widget is active.
1143       if (!anEditorWdg && !myIsPopupMenuActive) {
1144         // during a nested create operation, the feature is redisplayed only if the mouse over view
1145         // of there was a value modified in the property panel after the mouse left the view
1146         aCanDisplay = canDisplayCurrentCreatedFeature();
1147       }
1148     }
1149     #endif
1150   }
1151
1152   // checks the sketcher constraints visibility according to active sketch check box states
1153   if (aCanDisplay) {
1154     bool aProcessed = false;
1155     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1156     if (aFeature.get()) {
1157       bool aConstraintDisplayed = canDisplayConstraint(aFeature, PartSet_Tools::Any, aProcessed);
1158       if (aProcessed)
1159         aCanDisplay = aConstraintDisplayed;
1160     }
1161   }
1162
1163   return aCanDisplay;
1164 }
1165
1166 bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
1167                                              const PartSet_Tools::ConstraintVisibleState& theState,
1168                                              bool& isProcessed) const
1169 {
1170   bool aSwitchedOn = true;
1171
1172   const QStringList& aConstrIds = constraintsIdList();
1173
1174   std::string aKind = theFeature->getKind();
1175   if (aConstrIds.contains(QString(aKind.c_str()))) {
1176     bool isTypedConstraint = false;
1177
1178     switch (theState) {
1179       case PartSet_Tools::Dimensional: {
1180         bool isDistance = isDistanceKind(aKind);
1181         if (isDistance) {
1182           isProcessed = true;
1183           aSwitchedOn = myIsConstraintsShown[theState];
1184         }
1185       }
1186       break;
1187       case PartSet_Tools::Geometrical: {
1188         bool isGeometrical = !isDistanceKind(aKind);
1189         if (isGeometrical) {
1190           isProcessed = true;
1191           aSwitchedOn = myIsConstraintsShown[theState];
1192         }
1193       }
1194       break;
1195       case PartSet_Tools::Any: {
1196         isProcessed = true;
1197         bool isDistance = isDistanceKind(aKind);
1198         if (isDistance)
1199           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Dimensional];
1200         else
1201           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Geometrical];
1202       }
1203       break;
1204     default:
1205       break;
1206     }
1207   }
1208   return aSwitchedOn;
1209 }
1210
1211 void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
1212 {
1213   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1214                                                                            (getCurrentOperation());
1215   if (aFOperation && myCurrentSketch.get()) {
1216     // find results of the current operation
1217     // these results should not be proposed to be deleted
1218     FeaturePtr anOperationFeature = aFOperation->feature();
1219     std::list<ResultPtr> anOperationResultList = anOperationFeature->results();
1220     std::set<ResultPtr> anOperationResults;
1221     std::list<ResultPtr>::const_iterator aRIt = anOperationResultList.begin(),
1222                                         aRLast = anOperationResultList.end();
1223     for (; aRIt != aRLast; aRIt++)
1224       anOperationResults.insert(*aRIt);
1225
1226     std::set<FeaturePtr> anObjectsToBeDeleted;
1227     QStringList anObjectsToBeDeletedNames;
1228     std::list<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1229     for (; anIt != aLast; anIt++) {
1230       ObjectPtr anObject = *anIt;
1231       bool aCanErase = true;
1232       // when the sketch operation is active, results of sketch sub-feature can not be hidden
1233       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1234       // the result is found between current feature results
1235       if (anOperationResults.find(aResult) != anOperationResults.end())
1236         continue;
1237
1238       if (aResult.get()) {
1239         // Display sketcher objects
1240         for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1241           FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1242           std::list<ResultPtr> aResults = aFeature->results();
1243           std::list<ResultPtr>::const_iterator anIt;
1244           for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1245             aCanErase = *anIt != aResult;
1246           }
1247         }
1248       }
1249       if (!aCanErase) {
1250         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
1251         if (aFeature.get() && anObjectsToBeDeleted.find(aFeature) == anObjectsToBeDeleted.end()) {
1252           anObjectsToBeDeleted.insert(aFeature);
1253           anObjectsToBeDeletedNames.append(aFeature->name().c_str());
1254         }
1255       }
1256     }
1257     if (!anObjectsToBeDeleted.empty()) {
1258       QString aFeatureNames = anObjectsToBeDeletedNames.join(", ");
1259       QString aMessage = tr("The following features have incorrect presentation and \
1260 will be hidden: %1. Would you like to delete them?")
1261                          .arg(aFeatureNames);
1262       int anAnswer = QMessageBox::question(qApp->activeWindow(), tr("Features hide"),
1263                                            aMessage, QMessageBox::Ok | QMessageBox::Cancel,
1264                                            QMessageBox::Cancel);
1265       if (anAnswer == QMessageBox::Ok) {
1266         QObjectPtrList anObjects;
1267         std::set<FeaturePtr>::const_iterator anIt = anObjectsToBeDeleted.begin(),
1268                                              aLast = anObjectsToBeDeleted.end();
1269         for (; anIt != aLast; anIt++)
1270           anObjects.append(*anIt);
1271         SessionPtr aMgr = ModelAPI_Session::get();
1272         DocumentPtr aDoc = aMgr->activeDocument();
1273         bool aIsOp = aMgr->isOperation();
1274         if (!aIsOp)
1275           aMgr->startOperation();
1276         workshop()->deleteFeatures(anObjects);
1277         //static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
1278         //static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
1279         //Events_Loop::loop()->flush(aDeletedEvent);
1280         //Events_Loop::loop()->flush(aRedispEvent);
1281
1282         if (!aIsOp)
1283           aMgr->finishOperation();
1284       }
1285     }
1286   }
1287 }
1288
1289 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1290 {
1291   bool aCanDisplay = myIsMouseOverWindow;
1292   if (!aCanDisplay) {
1293     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1294     if (anActiveWidget)
1295       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1296   }
1297   return aCanDisplay;
1298 }
1299
1300 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1301 {
1302   return isNestedCreateOperation(theOperation) ||
1303          myModule->sketchReentranceMgr()->isInternalEditActive();
1304 }
1305
1306 const QMap<PartSet_Tools::ConstraintVisibleState, bool>& PartSet_SketcherMgr::showConstraintStates()
1307 {
1308   return myIsConstraintsShown;
1309 }
1310
1311 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1312 {
1313   bool isFoundObject = false;
1314
1315   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1316   if (anObjectFeature.get()) {
1317     int aSize = myCurrentSketch->numberOfSubs();
1318     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1319       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1320       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1321     }
1322   }
1323   return isFoundObject;
1324 }
1325
1326 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
1327 {
1328   if (myPlaneFilter.IsNull()) 
1329    myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
1330
1331   myPlaneFilter->setPlane(thePln);
1332 }
1333
1334 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
1335                                                          ModuleBase_IWorkshop* theWorkshop)
1336 {
1337   bool isValueAccepted = false;
1338
1339   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1340                                                                               (theOperation);
1341   FeaturePtr aFeature = aFOperation->feature();
1342   // editor is shown only if all attribute references are filled by preseletion
1343   bool anAllRefAttrInitialized = true;
1344
1345   std::list<AttributePtr> aRefAttrs = aFeature->data()->attributes(
1346                                               ModelAPI_AttributeRefAttr::typeId());
1347   std::list<AttributePtr>::const_iterator anIt = aRefAttrs.begin(), aLast = aRefAttrs.end();
1348   for (; anIt != aLast && anAllRefAttrInitialized; anIt++) {
1349     anAllRefAttrInitialized = (*anIt)->isInitialized();
1350   }
1351   if (anAllRefAttrInitialized) {
1352     // Activate dimension value editing on double click
1353     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
1354     QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
1355     // Find corresponded widget to activate value editing
1356     foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
1357       if (aWgt->attributeID() == "ConstraintValue") {
1358         // the featue should be displayed in order to find the AIS text position,
1359         // the place where the editor will be shown
1360         aFeature->setDisplayed(true);
1361         /// the execute is necessary to perform in the feature compute for flyout position
1362         aFeature->execute();
1363
1364         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1365         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1366
1367         PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
1368         if (anEditor) {
1369           int aX = 0, anY = 0;
1370
1371           XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(theWorkshop);
1372           XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1373           AISObjectPtr anAIS = aDisplayer->getAISObject(aFeature);
1374           Handle(AIS_InteractiveObject) anAISIO;
1375           if (anAIS.get() != NULL) {
1376             anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1377           }
1378           if (anAIS.get() != NULL) {
1379             Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1380
1381             if (!anAISIO.IsNull()) {
1382               Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAISIO);
1383               if (!aDim.IsNull()) {
1384                 gp_Pnt aPosition = aDim->GetTextPosition();
1385
1386                 ModuleBase_IViewer* aViewer = aWorkshop->viewer();
1387                 Handle(V3d_View) aView = aViewer->activeView();
1388                 int aCX, aCY;
1389                 aView->Convert(aPosition.X(), aPosition.Y(), aPosition.Z(), aCX, aCY);
1390
1391                 QWidget* aViewPort = aViewer->activeViewPort();
1392                 QPoint aGlPoint = aViewPort->mapToGlobal(QPoint(aCX, aCY));
1393                 aX = aGlPoint.x();
1394                 anY = aGlPoint.y();
1395               }
1396             }
1397             anEditor->setCursorPosition(aX, anY);
1398             isValueAccepted = anEditor->showPopupEditor(false);
1399           }
1400         }
1401       }
1402     }
1403   }
1404   return isValueAccepted;
1405 }
1406
1407 void PartSet_SketcherMgr::getCurrentSelection(const FeaturePtr& theFeature,
1408                                               const FeaturePtr& theSketch,
1409                                               ModuleBase_IWorkshop* theWorkshop,
1410                                               FeatureToSelectionMap& theSelection)
1411 {
1412   if (theFeature.get() == NULL)
1413     return;
1414
1415   std::set<AttributePtr> aSelectedAttributes;
1416   std::set<ResultPtr> aSelectedResults;
1417
1418   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1419   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
1420   if (!aContext.IsNull()) {
1421     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1422     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1423
1424     std::list<ResultPtr> aResults = theFeature->results();
1425     std::list<ResultPtr>::const_iterator aIt;
1426     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1427     {
1428       ResultPtr aResult = *aIt;
1429       AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1430       if (aAISObj.get() == NULL)
1431         continue;
1432       Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1433       for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
1434       {
1435         Handle(SelectMgr_EntityOwner) anOwner = aContext->SelectedOwner();
1436         if (anOwner->Selectable() != anAISIO)
1437           continue;
1438         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1439                                aSelectedAttributes, aSelectedResults);
1440       }
1441       for (aContext->InitDetected(); aContext->MoreDetected(); aContext->NextDetected()) {
1442         Handle(SelectMgr_EntityOwner) anOwner = aContext->DetectedOwner();
1443         if (anOwner.IsNull())
1444           continue;
1445         if (anOwner->Selectable() != anAISIO)
1446           continue;
1447         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1448                                aSelectedAttributes, aSelectedResults);
1449       }
1450     }
1451   }
1452   theSelection[theFeature] = std::make_pair(aSelectedAttributes, aSelectedResults);
1453 }
1454
1455 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1456                                              const FeaturePtr& theSketch,
1457                                              ModuleBase_IWorkshop* theWorkshop,
1458                                              const FeatureToSelectionMap& theSelection,
1459                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1460 {
1461   if (theFeature.get() == NULL)
1462     return;
1463
1464   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1465   std::set<AttributePtr> aSelectedAttributes = anIt.value().first;
1466   std::set<ResultPtr> aSelectedResults = anIt.value().second;
1467
1468   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1469
1470   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1471   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1472
1473   // 1. found the feature's owners. Check the AIS objects of the constructions
1474   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1475   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1476     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1477
1478     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1479     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1480     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1481       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1482       if (!anOwner.IsNull())
1483         theOwnersToSelect.Add(anOwner);
1484     }
1485   }
1486
1487   // 2. found the feature results's owners
1488   std::list<ResultPtr> aResults = theFeature->results();
1489   std::list<ResultPtr>::const_iterator aIt;
1490   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1491   {
1492     ResultPtr aResult = *aIt;
1493     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1494     if (aAISObj.get() == NULL)
1495       continue; 
1496     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1497
1498     SelectMgr_IndexedMapOfOwner aSelectedOwners;  
1499     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1500     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1501       Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1502       if ( anOwner.IsNull() || !anOwner->HasShape() )
1503         continue;
1504       const TopoDS_Shape& aShape = anOwner->Shape();
1505       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1506       if (aShapeType == TopAbs_VERTEX) {
1507         AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1508         if (aPntAttr.get() != NULL &&
1509             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end()) {
1510           theOwnersToSelect.Add(anOwner);
1511         }
1512       }
1513       else if (aShapeType == TopAbs_EDGE) {
1514         bool aFound = aSelectedResults.find(aResult) != aSelectedResults.end();
1515         if (aSelectedResults.find(aResult) != aSelectedResults.end() &&
1516             theOwnersToSelect.FindIndex(anOwner) <= 0)
1517           theOwnersToSelect.Add(anOwner);
1518       }
1519     }
1520   }
1521 }
1522
1523 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget, const bool isToConnect)
1524 {
1525   if (isToConnect) {
1526     connect(theWidget, SIGNAL(beforeValuesChanged()),
1527             this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1528     connect(theWidget, SIGNAL(afterValuesChanged()),
1529             this, SLOT(onAfterValuesChangedInPropertyPanel()));
1530   }
1531   else {
1532     disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1533                 this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1534     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1535                 this, SLOT(onAfterValuesChangedInPropertyPanel()));
1536   }
1537 }
1538
1539 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1540 {
1541   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1542                                                                            (getCurrentOperation());
1543   if (aFOperation) {
1544     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1545         PartSet_SketcherMgr::isNestedSketchOperation(aFOperation) &&
1546         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1547       FeaturePtr aFeature = aFOperation->feature();
1548       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1549     }
1550   }
1551 }
1552
1553 void PartSet_SketcherMgr::customizePresentation(const ObjectPtr& theObject)
1554 {
1555   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1556                                                                            (getCurrentOperation());
1557   if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1558                       PartSet_SketcherMgr::isNestedSketchOperation(aFOperation)))
1559     SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
1560 }
1561
1562 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1563 {
1564   return myModule->workshop()->currentOperation();
1565 }
1566
1567 //**************************************************************
1568 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1569 {
1570   ModuleBase_ModelWidget* aWidget = 0;
1571   ModuleBase_Operation* anOperation = getCurrentOperation();
1572   if (anOperation) {
1573     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1574     if (aPanel)
1575       aWidget = aPanel->activeWidget();
1576   }
1577   return aWidget;
1578 }
1579
1580 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1581                                            const bool isEditOperation,
1582                                            const bool isToDisplay,
1583                                            const bool isFlushRedisplay)
1584 {
1585   #ifdef DEBUG_DO_NOT_BY_ENTER
1586   return;
1587   #endif
1588
1589   if (isEditOperation || !theFeature.get())
1590     return;
1591
1592   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1593   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1594
1595   // 1. change visibility of the object itself, here the presentable object is processed,
1596   // e.g. constraints features
1597   //FeaturePtr aFeature = aFOperation->feature();
1598   std::list<ResultPtr> aResults = theFeature->results();
1599   if (isToDisplay)
1600     theFeature->setDisplayed(true);
1601   else
1602     theFeature->setDisplayed(false);
1603
1604   // change visibility of the object results, e.g. non-constraint features
1605   std::list<ResultPtr>::const_iterator aIt;
1606   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1607     if (isToDisplay) {
1608       (*aIt)->setDisplayed(true);
1609     }
1610     else {
1611       (*aIt)->setDisplayed(false);
1612     }
1613   }
1614   if (isFlushRedisplay)
1615     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1616 }
1617
1618 void PartSet_SketcherMgr::storeSelection(const bool theHighlightedOnly)
1619 {
1620   if (!myCurrentSketch.get())
1621     return;
1622
1623   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1624   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1625   QList<ModuleBase_ViewerPrsPtr> aHighlighted = aSelect->getHighlighted();
1626
1627   QList<FeaturePtr> aFeatureList;
1628   if (theHighlightedOnly) {
1629     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1630   }
1631   else {
1632     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1633
1634     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(ModuleBase_ISelection::AllControls);
1635     fillFeatureList(aSelected, myCurrentSketch, aFeatureList);
1636   }
1637
1638   // 1. it is necessary to save current selection in order to restore it after the features moving
1639   myCurrentSelection.clear();
1640   QList<FeaturePtr>::const_iterator anIt = aFeatureList.begin(), aLast = aFeatureList.end();
1641   for (; anIt != aLast; anIt++) {
1642     getCurrentSelection(*anIt, myCurrentSketch, aWorkshop, myCurrentSelection);
1643   }
1644   //qDebug(QString("  storeSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1645 }
1646
1647 void PartSet_SketcherMgr::restoreSelection()
1648 {
1649   if (!myCurrentSketch.get())
1650     return;
1651
1652   //qDebug(QString("restoreSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1653   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1654   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1655   FeatureToSelectionMap::const_iterator aSIt = myCurrentSelection.begin(),
1656                                         aSLast = myCurrentSelection.end();
1657   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1658   for (; aSIt != aSLast; aSIt++) {
1659     anOwnersToSelect.Clear();
1660     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, myCurrentSelection,
1661                         anOwnersToSelect);
1662     aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1663   }
1664 }
1665
1666 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
1667 {
1668   PartSet_Tools::ConstraintVisibleState aType = (PartSet_Tools::ConstraintVisibleState)theType;
1669
1670   updateBySketchParameters(aType, theState);
1671 }
1672
1673 void PartSet_SketcherMgr::updateBySketchParameters(
1674                                    const PartSet_Tools::ConstraintVisibleState& theType,
1675                                    bool theState)
1676 {
1677   if (myCurrentSketch.get() == NULL)
1678     return;
1679
1680   bool aPrevState = myIsConstraintsShown[theType];
1681   myIsConstraintsShown[theType] = theState;
1682
1683   switch (theType) {
1684     case PartSet_Tools::Geometrical:
1685     case PartSet_Tools::Dimensional: {
1686       if (aPrevState != theState) {
1687         ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1688         XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1689         for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1690           FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1691           bool aProcessed = false;
1692           bool aConstraintDisplayed = canDisplayConstraint(aSubFeature, theType, aProcessed);
1693           if (aProcessed)
1694             aSubFeature->setDisplayed(aConstraintDisplayed);
1695         }
1696         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1697       }
1698     }
1699     break;
1700     case PartSet_Tools::Expressions: {
1701       /// call all sketch features redisplay, the expression state will be corrected in customize
1702       /// of distance presentation
1703       Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1704       PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
1705     }
1706     break;
1707   }
1708 }
1709
1710 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
1711 {
1712   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1713   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1714   return aConnector->workshop();
1715 }
1716
1717 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1718 {
1719   return workshop()->operationMgr();
1720 }
1721