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