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