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