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