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