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