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