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