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