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