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