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