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