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