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