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