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