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