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