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