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