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