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