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