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