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