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