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