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