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