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