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