Salome HOME
a67aa0f36fc60f44ea18a9a3eb13156a6ea66440
[modules/shaper.git] / src / PartSet / PartSet_SketcherMgr.cpp
1 // Copyright (C) 2014-2017  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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "PartSet_SketcherMgr.h"
22
23 #include "PartSet_Filters.h"
24 #include "PartSet_SketcherReentrantMgr.h"
25 #include "PartSet_Module.h"
26 #include "PartSet_MouseProcessor.h"
27 #include "PartSet_Tools.h"
28 #include "PartSet_WidgetSketchLabel.h"
29 #include "PartSet_WidgetEditor.h"
30 #include "PartSet_ResultSketchPrs.h"
31 #include "PartSet_ExternalPointsMgr.h"
32 #include "PartSet_PreviewSketchPlane.h"
33
34 #include <XGUI_ModuleConnector.h>
35 #include <XGUI_Displayer.h>
36 #include <XGUI_Workshop.h>
37 #include <XGUI_ContextMenuMgr.h>
38 #include <XGUI_Selection.h>
39 #include <XGUI_SelectionActivate.h>
40 #include <XGUI_SelectionMgr.h>
41 #include <XGUI_ModuleConnector.h>
42 #include <XGUI_PropertyPanel.h>
43 #include <XGUI_ViewerProxy.h>
44 #include <XGUI_OperationMgr.h>
45 #include <XGUI_ErrorMgr.h>
46 #include <XGUI_Tools.h>
47
48 #include <ModuleBase_IPropertyPanel.h>
49 #include <ModuleBase_ISelection.h>
50 #include <ModuleBase_IViewer.h>
51 #include <ModuleBase_IWorkshop.h>
52 #include <ModuleBase_IViewWindow.h>
53 #include <ModuleBase_ModelWidget.h>
54 #include <ModuleBase_Operation.h>
55 #include <ModuleBase_OperationFeature.h>
56 #include <ModuleBase_Operation.h>
57 #include <ModuleBase_WidgetEditor.h>
58 #include <ModuleBase_ViewerPrs.h>
59 #include <ModuleBase_Tools.h>
60 #include <ModuleBase_ResultPrs.h>
61 #include <ModuleBase_ViewerFilters.h>
62
63 #include <GeomDataAPI_Point2D.h>
64
65 #include <Events_Loop.h>
66
67 #include <SketchPlugin_Line.h>
68 #include <SketchPlugin_Sketch.h>
69 #include <SketchPlugin_Point.h>
70 #include <SketchPlugin_Arc.h>
71 #include <SketchPlugin_Circle.h>
72 #include <SketchPlugin_ConstraintLength.h>
73 #include <SketchPlugin_ConstraintDistance.h>
74 #include <SketchPlugin_ConstraintParallel.h>
75 #include <SketchPlugin_ConstraintPerpendicular.h>
76 #include <SketchPlugin_ConstraintRadius.h>
77 #include <SketchPlugin_ConstraintRigid.h>
78 #include <SketchPlugin_ConstraintHorizontal.h>
79 #include <SketchPlugin_ConstraintVertical.h>
80 #include <SketchPlugin_ConstraintEqual.h>
81 #include <SketchPlugin_ConstraintTangent.h>
82 #include <SketchPlugin_ConstraintCoincidence.h>
83 #include <SketchPlugin_Fillet.h>
84 #include <SketchPlugin_ConstraintMirror.h>
85 #include <SketchPlugin_ConstraintAngle.h>
86 #include <SketchPlugin_ConstraintCollinear.h>
87 #include <SketchPlugin_ConstraintMiddle.h>
88 #include <SketchPlugin_MultiRotation.h>
89 #include <SketchPlugin_MultiTranslation.h>
90 #include <SketchPlugin_IntersectionPoint.h>
91 #include <SketchPlugin_Projection.h>
92 #include <SketchPlugin_ConstraintDistanceAlongDir.h>
93 #include <SketchPlugin_ConstraintDistanceHorizontal.h>
94 #include <SketchPlugin_ConstraintDistanceVertical.h>
95
96 #include <SketcherPrs_Tools.h>
97
98 #include <SelectMgr_IndexedMapOfOwner.hxx>
99 #include <StdSelect_BRepOwner.hxx>
100
101 //#include <AIS_DimensionSelectionMode.hxx>
102 #include <AIS_Shape.hxx>
103 #include <AIS_Dimension.hxx>
104
105 #include <ModelAPI_Events.h>
106 #include <ModelAPI_Session.h>
107 #include <ModelAPI_AttributeString.h>
108
109 #include <ModelAPI_Validator.h>
110 #include <ModelAPI_Tools.h>
111
112 #include <QMouseEvent>
113 #include <QApplication>
114 #include <QCursor>
115 #include <QMessageBox>
116 #include <QMainWindow>
117
118 //#define DEBUG_DO_NOT_BY_ENTER
119 //#define DEBUG_SKETCHER_ENTITIES
120 //#define DEBUG_SKETCH_ENTITIES_ON_MOVE
121
122 //#define DEBUG_CURSOR
123
124 /// Fills attribute and result lists by the selected owner. In case if the attribute is found,
125 /// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge,
126 /// put the function result as is to the list of results.
127 /// \param theOwner a viewer selected owner
128 /// \param theFeature a feature, where the attribute is searched
129 /// \param theSketch a current sketch
130 /// \param theSelectedAttribute an output list of attributes
131 /// \param theSelectedResults an output list of edge results
132 void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
133                             const FeaturePtr& theFeature, const FeaturePtr& theSketch,
134                             const ResultPtr& theResult,
135                             std::set<AttributePtr>& theSelectedAttributes,
136                             std::set<ResultPtr>& theSelectedResults,
137                             TopTools_MapOfShape& theShapes)
138 {
139   Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(theOwner);
140   if (aBRepOwner.IsNull())
141     return;
142   Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(
143                                                                     aBRepOwner->Selectable());
144   if (aBRepOwner->HasShape()) {
145     const TopoDS_Shape& aShape = aBRepOwner->Shape();
146     theShapes.Add(aShape);
147     TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
148     if (aShapeType == TopAbs_VERTEX) {
149       AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature,
150                                                                     aShape, theSketch);
151       if (aPntAttr.get() != NULL)
152         theSelectedAttributes.insert(aPntAttr);
153     }
154     else if (aShapeType == TopAbs_EDGE &&
155              theSelectedResults.find(theResult) == theSelectedResults.end()) {
156       theSelectedResults.insert(theResult);
157     }
158   }
159 }
160
161 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
162   : QObject(theModule), myModule(theModule), myIsEditLaunching(false), myIsDragging(false),
163     myDragDone(false), myIsMouseOverWindow(false),
164     myIsMouseOverViewProcessed(true), myPreviousUpdateViewerEnabled(true),
165     myIsPopupMenuActive(false), myExternalPointsMgr(0)
166 {
167   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
168   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
169
170   myPreviousDrawModeEnabled = true;//aViewer->isSelectionEnabled();
171
172   connect(aViewer, SIGNAL(mousePress(ModuleBase_IViewWindow*, QMouseEvent*)),
173           this, SLOT(onMousePressed(ModuleBase_IViewWindow*, QMouseEvent*)));
174
175   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)),
176           this, SLOT(onMouseReleased(ModuleBase_IViewWindow*, QMouseEvent*)));
177
178   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
179           this, SLOT(onMouseMoved(ModuleBase_IViewWindow*, QMouseEvent*)));
180
181   connect(aViewer, SIGNAL(mouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)),
182           this, SLOT(onMouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)));
183
184   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
185   XGUI_Workshop* aWorkshop = aConnector->workshop();
186   connect(aWorkshop, SIGNAL(applicationStarted()), this, SLOT(onApplicationStarted()));
187
188   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
189   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
190   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
191
192   mySketchPlane = new PartSet_PreviewSketchPlane();
193
194   registerSelectionFilter(SF_SketchCirclePointFilter, new PartSet_CirclePointFilter(anIWorkshop));
195   registerSelectionFilter(SF_SketchPlaneFilter, new ModuleBase_ShapeInPlaneFilter());
196 }
197
198 PartSet_SketcherMgr::~PartSet_SketcherMgr()
199 {
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   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
974     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
975     if (aFeature.get()) {
976       if (!aFactory->validate(aFeature))
977         anInvalidFeatures.insert(aFeature);
978     }
979   }
980   if (!anInvalidFeatures.empty()) {
981     std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
982     ModelAPI_Tools::findAllReferences(anInvalidFeatures, aReferences, false);
983
984     std::set<FeaturePtr>::const_iterator anIt = anInvalidFeatures.begin(),
985                                          aLast = anInvalidFeatures.end();
986     // separate features to references to parameter features and references to others
987     QStringList anInvalidFeatureNames;
988     for (; anIt != aLast; anIt++) {
989       FeaturePtr aFeature = *anIt;
990       if (aFeature.get())
991         anInvalidFeatureNames.append(aFeature->name().c_str());
992     }
993     std::string aPrefixInfo = QString("Invalid features of the sketch will be deleted: %1.\n\n").
994                                   arg(anInvalidFeatureNames.join(", ")).toStdString().c_str();
995     std::set<FeaturePtr> aFeatureRefsToDelete;
996     if (ModuleBase_Tools::askToDelete(anInvalidFeatures, aReferences, aConnector->desktop(),
997                                       aFeatureRefsToDelete, aPrefixInfo)) {
998       if (!aFeatureRefsToDelete.empty())
999         anInvalidFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
1000       ModelAPI_Tools::removeFeatures(anInvalidFeatures, true);
1001       Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1002       // TODO: call the next method in the XGUI_OperationMgr::onOperationStarted().
1003       workshop()->errorMgr()->updateAcceptAllAction(myCurrentSketch);
1004     }
1005   }
1006
1007   // update state of overconstraint listener should be done before sketch features/results
1008   // display (as the display will ask custom color from the listener)
1009   myModule->overconstraintListener()->setActive(true);
1010   // Display sketcher objects
1011   QStringList anInfo;
1012   Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1013   const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
1014   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1015     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1016 #ifdef DEBUG_SKETCHER_ENTITIES
1017     anInfo.append(ModuleBase_Tools::objectInfo(aFeature));
1018 #endif
1019     std::list<ResultPtr> aResults = aFeature->results();
1020     std::list<ResultPtr>::const_iterator aIt;
1021     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1022       if ((*aIt)->isDisplayed())
1023         // Display object if it was created outside of GUI
1024         aECreator->sendUpdated((*aIt), EVENT_DISP);
1025       else
1026         (*aIt)->setDisplayed(true);
1027     }
1028     if (aFeature->isDisplayed())
1029       aECreator->sendUpdated(aFeature, EVENT_DISP);
1030     else
1031       aFeature->setDisplayed(true);
1032   }
1033 #ifdef DEBUG_SKETCHER_ENTITIES
1034   QString anInfoStr = anInfo.join(";\t");
1035   qDebug(QString("startSketch: %1, %2").arg(anInfo.size()).arg(anInfoStr).toStdString().c_str());
1036 #endif
1037
1038   bool aHasPlane = false;
1039   std::shared_ptr<GeomAPI_Pln> aPln;
1040   aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
1041   Handle(SelectMgr_Filter) aFilter = myModule->selectionFilter(SF_SketchPlaneFilter);
1042   if (!aFilter.IsNull())
1043     Handle(ModuleBase_ShapeInPlaneFilter)::DownCast(aFilter)->setPlane(aPln);
1044
1045   workshop()->selectionActivate()->updateSelectionFilters();
1046   workshop()->selectionActivate()->updateSelectionModes();
1047
1048   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1049
1050   myExternalPointsMgr = new PartSet_ExternalPointsMgr(myModule->workshop(), myCurrentSketch);
1051 }
1052
1053 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
1054 {
1055   myIsMouseOverWindow = false;
1056   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
1057   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
1058   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
1059
1060   if (myExternalPointsMgr) {
1061     delete myExternalPointsMgr;
1062     myExternalPointsMgr = 0;
1063   }
1064
1065   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
1066
1067   DataPtr aData = myCurrentSketch->data();
1068   if (!aData->isValid()) {
1069     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1070     // The sketch was aborted
1071     myCurrentSketch = CompositeFeaturePtr();
1072     mySketchPlane->eraseSketchPlane(myModule->workshop());
1073
1074     // Erase all sketcher objects
1075     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1076     foreach (ObjectPtr aObj, aObjects) {
1077       DataPtr aObjData = aObj->data();
1078       if (!aObjData->isValid())
1079         aObj->setDisplayed(false);
1080     }
1081   }
1082   else {
1083     // Hide all sketcher sub-Objects
1084     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1085       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1086       std::list<ResultPtr> aResults = aFeature->results();
1087       std::list<ResultPtr>::const_iterator aIt;
1088       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1089         (*aIt)->setDisplayed(false);
1090       }
1091       aFeature->setDisplayed(false);
1092     }
1093     // Display sketcher result
1094     std::list<ResultPtr> aResults = myCurrentSketch->results();
1095     std::list<ResultPtr>::const_iterator aIt;
1096     Events_Loop* aLoop = Events_Loop::loop();
1097     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1098
1099     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1100                                                                            (theOperation);
1101     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1102       if (!aFOperation->isDisplayedOnStart(*aIt)) {
1103         (*aIt)->setDisplayed(true);
1104         // this display event is needed because sketch already may have "displayed" state,
1105         // but not displayed while it is still active (issue 613, abort of existing sketch)
1106         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
1107       }
1108     }
1109     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
1110       myCurrentSketch->setDisplayed(true);
1111
1112     myCurrentSketch = CompositeFeaturePtr();
1113     mySketchPlane->eraseSketchPlane(myModule->workshop());
1114
1115     Events_Loop::loop()->flush(aDispEvent);
1116   }
1117   workshop()->selectionActivate()->updateSelectionFilters();
1118   workshop()->selectionActivate()->updateSelectionModes();
1119 }
1120
1121 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
1122 {
1123   if (canChangeCursor(theOperation) && myIsMouseOverWindow) {
1124     QCursor* aCurrentCursor = QApplication::overrideCursor();
1125     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
1126       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
1127 #ifdef DEBUG_CURSOR
1128       qDebug("startNestedSketch() : Qt::CrossCursor");
1129 #endif
1130     }
1131   }
1132 }
1133
1134 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
1135 {
1136   myIsMouseOverViewProcessed = true;
1137   operationMgr()->onValidateOperation();
1138   // when sketch nested operation is stopped the cursor should be restored unconditionally
1139   //if (canChangeCursor(theOperation)) {
1140     QApplication::restoreOverrideCursor();
1141 #ifdef DEBUG_CURSOR
1142     qDebug("stopNestedSketch() : None");
1143 #endif
1144   //}
1145   /// improvement to deselect automatically all eventual selected objects, when
1146   // returning to the neutral point of the Sketcher
1147   bool isClearSelectionPossible = true;
1148   if (myIsEditLaunching) {
1149     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1150                                                                           (theOperation);
1151     if (aFOperation) {
1152       FeaturePtr aFeature = aFOperation->feature();
1153       if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1154         isClearSelectionPossible = false;
1155       }
1156     }
1157   }
1158   if (isClearSelectionPossible)
1159     workshop()->selector()->clearSelection();
1160 }
1161
1162 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
1163 {
1164   if (isNestedCreateOperation(theOperation, activeSketch())) {
1165     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1166                                                                              (theOperation);
1167     if (aFOperation) {
1168       FeaturePtr aFeature = aFOperation->feature();
1169       // it is necessary to check the the feature data validity because
1170       // some kind of features are removed by an operation commit(the macro state of a feature)
1171       if (aFeature.get() && aFeature->data()->isValid()) {
1172         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
1173       }
1174     }
1175   }
1176 }
1177
1178 bool PartSet_SketcherMgr::sketchSelectionFilter(const XGUI_SelectionFilterType theFilterType)
1179 {
1180   return mySelectionFilterTypes.find(theFilterType) != mySelectionFilterTypes.end();
1181 }
1182
1183 void PartSet_SketcherMgr::registerSelectionFilter(const XGUI_SelectionFilterType theFilterType,
1184                                                   const Handle(SelectMgr_Filter)& theFilter)
1185 {
1186   mySelectionFilterTypes.insert(theFilterType);
1187   myModule->registerSelectionFilter(theFilterType, theFilter);
1188 }
1189
1190 bool PartSet_SketcherMgr::operationActivatedByPreselection()
1191 {
1192   bool isOperationStopped = false;
1193   ModuleBase_Operation* anOperation = getCurrentOperation();
1194   if(anOperation && isNestedSketchOperation(anOperation)) {
1195     // Set final definitions if they are necessary
1196     //propertyPanelDefined(aOperation);
1197     /// Commit sketcher operations automatically
1198     /// distance operation are able to show popup editor to modify the distance value
1199     /// after entering the value, the operation should be committed/aborted(by Esc key)
1200     bool aCanCommitOperation = true;
1201     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1202                                                                             (anOperation);
1203     if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation)) {
1204       bool aValueAccepted = setDistanceValueByPreselection(anOperation, myModule->workshop(),
1205                                                            aCanCommitOperation);
1206       if (!aValueAccepted)
1207         return isOperationStopped;
1208     }
1209
1210     if (aCanCommitOperation)
1211       isOperationStopped = anOperation->commit();
1212     else {
1213       anOperation->abort();
1214       isOperationStopped = true;
1215     }
1216   }
1217   return isOperationStopped;
1218 }
1219
1220 bool PartSet_SketcherMgr::canUndo() const
1221 {
1222   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1223 }
1224
1225 bool PartSet_SketcherMgr::canRedo() const
1226 {
1227   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1228 }
1229
1230 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1231 {
1232   bool aCanErase = true;
1233   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1234   if (myCurrentSketch.get()) {
1235     return !isObjectOfSketch(theObject);
1236   }
1237   return aCanErase;
1238 }
1239
1240 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1241 {
1242   bool aCanDisplay = true;
1243
1244   bool aHasActiveSketch = activeSketch().get() != NULL;
1245   if (aHasActiveSketch) {
1246     // 1. the sketch feature should not be displayed during the sketch active operation
1247     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch
1248     // nested features can be visualized
1249     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1250     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1251       aCanDisplay = false;
1252     }
1253     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1254                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1255     /// some sketch entities should be never shown, e.g. projection feature
1256     if (aSketchFeature.get())
1257       aCanDisplay = aSketchFeature->canBeDisplayed();
1258   }
1259   else { // there are no an active sketch
1260     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1261     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1262     if (aFeature.get() != NULL) {
1263       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1264                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1265       if (aSketchFeature.get()) {
1266         aCanDisplay = false;
1267       }
1268     }
1269   }
1270
1271   // 3. the method should not filter the objects, which are not related to the current operation.
1272   // The object is filtered just if it is a current operation feature or this feature result
1273   if (aCanDisplay) {
1274     bool isObjectFound = false;
1275     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1276                                                                  (getCurrentOperation());
1277     if (aFOperation) {
1278       FeaturePtr aFeature = aFOperation->feature();
1279       if (aFeature.get()) {
1280         std::list<ResultPtr> aResults = aFeature->results();
1281         if (theObject == aFeature)
1282           isObjectFound = true;
1283         else {
1284           std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1285           for (; anIt != aLast && !isObjectFound; anIt++) {
1286             isObjectFound = *anIt == theObject;
1287           }
1288         }
1289       }
1290     }
1291     if (isObjectFound) {
1292       // 4. For created nested feature operation do not display the created feature if
1293       // the mouse curstor leaves the OCC window.
1294       // The correction cases, which ignores this condition:
1295       // a. the property panel values modification
1296       // b. the popup menu activated
1297       // c. widget editor control
1298       #ifndef DEBUG_DO_NOT_BY_ENTER
1299       if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
1300         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1301         ModuleBase_WidgetEditor* anEditorWdg =
1302           anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1303         // the active widget editor should not influence here. The presentation should be visible
1304         // always when this widget is active.
1305         if (!anEditorWdg && !myIsPopupMenuActive) {
1306           // during a nested create operation, the feature is redisplayed only
1307           // if the mouse over view
1308           // of there was a value modified in the property panel after the mouse left the view
1309           aCanDisplay = canDisplayCurrentCreatedFeature();
1310         }
1311       }
1312       #endif
1313     }
1314   }
1315
1316   // checks the sketcher constraints visibility according to active sketch check box states
1317   if (aCanDisplay) {
1318     bool aProcessed = false;
1319     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1320     if (aFeature.get()) {
1321       bool aConstraintDisplayed = canDisplayConstraint(aFeature, PartSet_Tools::Any, aProcessed);
1322       if (aProcessed)
1323         aCanDisplay = aConstraintDisplayed;
1324     }
1325   }
1326
1327   return aCanDisplay;
1328 }
1329
1330 bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
1331                                              const PartSet_Tools::ConstraintVisibleState& theState,
1332                                              bool& isProcessed) const
1333 {
1334   bool aSwitchedOn = true;
1335
1336   const QStringList& aConstrIds = constraintsIdList();
1337
1338   std::string aKind = theFeature->getKind();
1339   if (aConstrIds.contains(QString(aKind.c_str()))) {
1340     bool isTypedConstraint = false;
1341
1342     switch (theState) {
1343       case PartSet_Tools::Dimensional: {
1344         bool isDistance = isDistanceKind(aKind);
1345         if (isDistance) {
1346           isProcessed = true;
1347           aSwitchedOn = myIsConstraintsShown[theState];
1348         }
1349       }
1350       break;
1351       case PartSet_Tools::Geometrical: {
1352         bool isGeometrical = !isDistanceKind(aKind);
1353         if (isGeometrical) {
1354           isProcessed = true;
1355           aSwitchedOn = myIsConstraintsShown[theState];
1356         }
1357       }
1358       break;
1359       case PartSet_Tools::Any: {
1360         isProcessed = true;
1361         bool isDistance = isDistanceKind(aKind);
1362         if (isDistance)
1363           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Dimensional];
1364         else
1365           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Geometrical];
1366       }
1367       break;
1368     default:
1369       break;
1370     }
1371   }
1372   return aSwitchedOn;
1373 }
1374
1375 /*void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
1376 {
1377   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1378                                                                            (getCurrentOperation());
1379   if (aFOperation && myCurrentSketch.get()) {
1380     // find results of the current operation
1381     // these results should not be proposed to be deleted
1382     FeaturePtr anOperationFeature = aFOperation->feature();
1383     std::list<ResultPtr> anOperationResultList = anOperationFeature->results();
1384     std::set<ResultPtr> anOperationResults;
1385     std::list<ResultPtr>::const_iterator aRIt = anOperationResultList.begin(),
1386                                         aRLast = anOperationResultList.end();
1387     for (; aRIt != aRLast; aRIt++)
1388       anOperationResults.insert(*aRIt);
1389
1390     std::set<FeaturePtr> anObjectsToBeDeleted;
1391     QStringList anObjectsToBeDeletedNames;
1392     std::list<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1393     for (; anIt != aLast; anIt++) {
1394       ObjectPtr anObject = *anIt;
1395       bool aCanErase = true;
1396       // when the sketch operation is active, results of sketch sub-feature can not be hidden
1397       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1398       // the result is found between current feature results
1399       if (anOperationResults.find(aResult) != anOperationResults.end())
1400         continue;
1401
1402       if (aResult.get()) {
1403         // Display sketcher objects
1404         for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1405           FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1406           std::list<ResultPtr> aResults = aFeature->results();
1407           std::list<ResultPtr>::const_iterator anIt;
1408           for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1409             aCanErase = *anIt != aResult;
1410           }
1411         }
1412       }
1413       if (!aCanErase) {
1414         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
1415         if (aFeature.get() && anObjectsToBeDeleted.find(aFeature) == anObjectsToBeDeleted.end()) {
1416           anObjectsToBeDeleted.insert(aFeature);
1417           anObjectsToBeDeletedNames.append(aFeature->name().c_str());
1418         }
1419       }
1420     }
1421     if (!anObjectsToBeDeleted.empty()) {
1422       QString aFeatureNames = anObjectsToBeDeletedNames.join(", ");
1423       QString aMessage = tr("The following features have incorrect presentation and \
1424 will be hidden: %1. Would you like to delete them?")
1425                          .arg(aFeatureNames);
1426       int anAnswer = QMessageBox::question(qApp->activeWindow(), tr("Features hide"),
1427                                            aMessage, QMessageBox::Ok | QMessageBox::Cancel,
1428                                            QMessageBox::Cancel);
1429       if (anAnswer == QMessageBox::Ok) {
1430         QObjectPtrList anObjects;
1431         std::set<FeaturePtr>::const_iterator anIt = anObjectsToBeDeleted.begin(),
1432                                              aLast = anObjectsToBeDeleted.end();
1433         for (; anIt != aLast; anIt++)
1434           anObjects.append(*anIt);
1435         SessionPtr aMgr = ModelAPI_Session::get();
1436         DocumentPtr aDoc = aMgr->activeDocument();
1437         bool aIsOp = aMgr->isOperation();
1438         if (!aIsOp)
1439           aMgr->startOperation();
1440         workshop()->deleteFeatures(anObjects);
1441         //static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
1442         //static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
1443         //Events_Loop::loop()->flush(aDeletedEvent);
1444         //Events_Loop::loop()->flush(aRedispEvent);
1445
1446         if (!aIsOp)
1447           aMgr->finishOperation();
1448       }
1449     }
1450   }
1451 }*/
1452
1453 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1454 {
1455   bool aCanDisplay = myIsMouseOverWindow;
1456   if (!aCanDisplay) {
1457     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1458     if (anActiveWidget)
1459       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1460   }
1461   return aCanDisplay;
1462 }
1463
1464 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1465 {
1466   return isNestedCreateOperation(theOperation, activeSketch()) ||
1467          myModule->sketchReentranceMgr()->isInternalEditActive();
1468 }
1469
1470 const QMap<PartSet_Tools::ConstraintVisibleState, bool>& PartSet_SketcherMgr::showConstraintStates()
1471 {
1472   return myIsConstraintsShown;
1473 }
1474
1475 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1476 {
1477   bool isFoundObject = false;
1478
1479   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1480   if (anObjectFeature.get()) {
1481     int aSize = myCurrentSketch->numberOfSubs();
1482     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1483       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1484       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1485     }
1486   }
1487   return isFoundObject;
1488 }
1489
1490 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePlane)
1491 {
1492   Handle(SelectMgr_Filter) aFilter = myModule->selectionFilter(SF_SketchPlaneFilter);
1493   if (!aFilter.IsNull())
1494     Handle(ModuleBase_ShapeInPlaneFilter)::DownCast(aFilter)->setPlane(thePlane);
1495
1496   workshop()->selectionActivate()->updateSelectionModes();
1497 }
1498
1499 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
1500                                                          ModuleBase_IWorkshop* theWorkshop,
1501                                                          bool& theCanCommitOperation)
1502 {
1503   bool isValueAccepted = false;
1504   theCanCommitOperation = false;
1505
1506   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1507                                                                               (theOperation);
1508   FeaturePtr aFeature = aFOperation->feature();
1509   // editor is shown only if all attribute references are filled by preseletion
1510   bool anAllRefAttrInitialized = true;
1511
1512   std::list<AttributePtr> aRefAttrs = aFeature->data()->attributes(
1513                                               ModelAPI_AttributeRefAttr::typeId());
1514   std::list<AttributePtr>::const_iterator anIt = aRefAttrs.begin(), aLast = aRefAttrs.end();
1515   for (; anIt != aLast && anAllRefAttrInitialized; anIt++) {
1516     anAllRefAttrInitialized = (*anIt)->isInitialized();
1517   }
1518   if (anAllRefAttrInitialized) {
1519     // Activate dimension value editing on double click
1520     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
1521     QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
1522     // Find corresponded widget to activate value editing
1523     foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
1524       if (aWgt->attributeID() == "ConstraintValue") {
1525         // the featue should be displayed in order to find the AIS text position,
1526         // the place where the editor will be shown
1527         aFeature->setDisplayed(true);
1528         /// the execute is necessary to perform in the feature compute for flyout position
1529         aFeature->execute();
1530
1531         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1532         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1533
1534         PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
1535         if (anEditor) {
1536           int aX = 0, anY = 0;
1537
1538           XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(theWorkshop);
1539           XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1540           AISObjectPtr anAIS = aDisplayer->getAISObject(aFeature);
1541           Handle(AIS_InteractiveObject) anAISIO;
1542           if (anAIS.get() != NULL) {
1543             anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1544           }
1545           if (anAIS.get() != NULL) {
1546             Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1547
1548             if (!anAISIO.IsNull()) {
1549               Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAISIO);
1550               if (!aDim.IsNull()) {
1551                 gp_Pnt aPosition = aDim->GetTextPosition();
1552
1553                 ModuleBase_IViewer* aViewer = aWorkshop->viewer();
1554                 Handle(V3d_View) aView = aViewer->activeView();
1555                 int aCX, aCY;
1556                 aView->Convert(aPosition.X(), aPosition.Y(), aPosition.Z(), aCX, aCY);
1557
1558                 QWidget* aViewPort = aViewer->activeViewPort();
1559                 QPoint aGlPoint = aViewPort->mapToGlobal(QPoint(aCX, aCY));
1560                 aX = aGlPoint.x();
1561                 anY = aGlPoint.y();
1562               }
1563             }
1564             anEditor->setCursorPosition(aX, anY);
1565             isValueAccepted = anEditor->showPopupEditor(false);
1566             theCanCommitOperation = true;
1567           }
1568         }
1569       }
1570     }
1571   }
1572   return isValueAccepted;
1573 }
1574
1575 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1576                                              const FeaturePtr& theSketch,
1577                                              ModuleBase_IWorkshop* theWorkshop,
1578                                              const FeatureToSelectionMap& theSelection,
1579                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1580 {
1581   if (theFeature.get() == NULL)
1582     return;
1583
1584   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1585   SelectionInfo anInfo = anIt.value();
1586   std::set<AttributePtr> aSelectedAttributes = anInfo.myAttributes;
1587   std::set<ResultPtr> aSelectedResults = anInfo.myResults;
1588
1589   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1590
1591   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1592   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1593
1594   // 1. found the feature's owners. Check the AIS objects of the constructions
1595   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1596   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1597     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1598
1599     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1600     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1601     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1602       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1603       if (!anOwner.IsNull())
1604         theOwnersToSelect.Add(anOwner);
1605     }
1606   }
1607
1608   // 2. found the feature results's owners
1609   std::list<ResultPtr> aResults = theFeature->results();
1610   std::list<ResultPtr>::const_iterator aIt;
1611
1612   bool isSameShape = false;
1613   if (aResults.size() > 0) {
1614     ResultPtr aFirstResult = theFeature->firstResult();
1615     if (aFirstResult.get() && aFirstResult->shape().get()) {
1616       TopoDS_Shape aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
1617       isSameShape = aFirstShape.IsEqual(anInfo.myFirstResultShape);
1618     }
1619   }
1620   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1621     ResultPtr aResult = *aIt;
1622     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1623     if (aAISObj.get() == NULL)
1624       continue;
1625     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1626
1627     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1628     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1629     bool aFoundLocalShape = false;
1630     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1631       Handle(StdSelect_BRepOwner) anOwner =
1632         Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1633       if ( anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
1634         continue;
1635       const TopoDS_Shape& aShape = anOwner->Shape();
1636       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1637       if (aShapeType == TopAbs_VERTEX) {
1638         AttributePtr aPntAttr =
1639           PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1640         if (aPntAttr.get() != NULL &&
1641             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end())
1642           theOwnersToSelect.Add(anOwner);
1643         else if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
1644           theOwnersToSelect.Add(anOwner);
1645         }
1646       }
1647       else if (aShapeType == TopAbs_EDGE) {
1648         if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
1649           // try to restore local selection on Shape result
1650           // we can do this only if the shape was not changed
1651           theOwnersToSelect.Add(anOwner);
1652           aFoundLocalShape = true;
1653           break;
1654         }
1655       }
1656     }
1657     if (!aFoundLocalShape) {
1658       // result owners are put in the list of selection only if local selected shapes were not
1659       // found
1660       if (aSelectedResults.find(aResult) != aSelectedResults.end()) {
1661         for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1662           Handle(StdSelect_BRepOwner) anOwner =
1663             Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1664           if ( anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
1665             continue;
1666             // select whole result
1667             theOwnersToSelect.Add(anOwner);
1668         }
1669       }
1670     }
1671   }
1672 }
1673
1674 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
1675                                                  const bool isToConnect)
1676 {
1677   //Temporary commented as we do not modify values in property panel
1678   if (isToConnect) {
1679     //connect(theWidget, SIGNAL(beforeValuesChanged()),
1680     //        this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1681     //connect(theWidget, SIGNAL(afterValuesChanged()),
1682     //        this, SLOT(onAfterValuesChangedInPropertyPanel()));
1683     connect(theWidget, SIGNAL(afterValuesChanged()),
1684             myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
1685   }
1686   else {
1687     //disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1688     //            this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1689     //disconnect(theWidget, SIGNAL(afterValuesChanged()),
1690     //            this, SLOT(onAfterValuesChangedInPropertyPanel()));
1691     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1692                myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
1693   }
1694 }
1695
1696 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1697 {
1698   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1699                                                                            (getCurrentOperation());
1700   if (aFOperation) {
1701     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1702         isNestedSketchOperation(aFOperation) &&
1703         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1704       FeaturePtr aFeature = aFOperation->feature();
1705       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1706     }
1707   }
1708 }
1709
1710 void PartSet_SketcherMgr::customizePresentation(const ObjectPtr& theObject)
1711 {
1712   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1713                                                                            (getCurrentOperation());
1714   if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1715                       isNestedSketchOperation(aFOperation)))
1716     SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
1717
1718   // update entities selection priorities
1719   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1720   if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1721     // update priority for feature
1722     updateSelectionPriority(aFeature, aFeature);
1723     // update priority for results of the feature
1724     std::list<ResultPtr> aResults = aFeature->results();
1725     std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLastIt = aResults.end();
1726     for (; anIt != aLastIt; anIt++)
1727       updateSelectionPriority(*anIt, aFeature);
1728   }
1729 }
1730
1731 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1732 {
1733   return myModule->workshop()->currentOperation();
1734 }
1735
1736 //**************************************************************
1737 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1738 {
1739   ModuleBase_ModelWidget* aWidget = 0;
1740   ModuleBase_Operation* anOperation = getCurrentOperation();
1741   if (anOperation) {
1742     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1743     if (aPanel)
1744       aWidget = aPanel->activeWidget();
1745   }
1746   return aWidget;
1747 }
1748
1749 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1750                                            const bool isEditOperation,
1751                                            const bool isToDisplay,
1752                                            const bool isFlushRedisplay)
1753 {
1754   #ifdef DEBUG_DO_NOT_BY_ENTER
1755   return;
1756   #endif
1757
1758   if (isEditOperation || !theFeature.get())
1759     return;
1760
1761   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1762   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1763
1764   // 1. change visibility of the object itself, here the presentable object is processed,
1765   // e.g. constraints features
1766   //FeaturePtr aFeature = aFOperation->feature();
1767   std::list<ResultPtr> aResults = theFeature->results();
1768   if (isToDisplay)
1769     theFeature->setDisplayed(true);
1770   else
1771     theFeature->setDisplayed(false);
1772
1773   // change visibility of the object results, e.g. non-constraint features
1774   std::list<ResultPtr>::const_iterator aIt;
1775   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1776     if (isToDisplay) {
1777       (*aIt)->setDisplayed(true);
1778     }
1779     else {
1780       (*aIt)->setDisplayed(false);
1781     }
1782   }
1783   if (isFlushRedisplay)
1784     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1785 }
1786
1787 void PartSet_SketcherMgr::storeSelection(const SelectionType theType,
1788                         PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
1789 {
1790   if (!myCurrentSketch.get())
1791     return;
1792
1793   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1794   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1795   QList<ModuleBase_ViewerPrsPtr> aStoredPrs;
1796
1797   if (theType == ST_HighlightType || theType == ST_SelectAndHighlightType)
1798     aStoredPrs = aSelect->getHighlighted();
1799
1800   QList<FeaturePtr> aFeatureList;
1801   if (theType == ST_SelectAndHighlightType || theType == ST_SelectType) {
1802     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(
1803                                                               ModuleBase_ISelection::AllControls);
1804     aStoredPrs.append(aSelected);
1805   }
1806
1807   // 1. it is necessary to save current selection in order to restore it after the features moving
1808   theCurrentSelection.clear();
1809
1810   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = aStoredPrs.begin(),
1811                                                 aLast = aStoredPrs.end();
1812
1813   CompositeFeaturePtr aSketch = activeSketch();
1814   for (; anIt != aLast; anIt++) {
1815     ModuleBase_ViewerPrsPtr aPrs = *anIt;
1816     ObjectPtr anObject = aPrs->object();
1817     if (!anObject.get())
1818       continue;
1819
1820     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1821     FeaturePtr aFeature;
1822     if (aResult.get())
1823       aFeature = ModelAPI_Feature::feature(aResult);
1824     else
1825       aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1826
1827     if (!aFeature.get())
1828       continue;
1829
1830     std::set<AttributePtr> aSelectedAttributes;
1831     std::set<ResultPtr> aSelectedResults;
1832     SelectionInfo anInfo;
1833     if (theCurrentSelection.find(aFeature) != theCurrentSelection.end())
1834       anInfo = theCurrentSelection.find(aFeature).value();
1835
1836     TopoDS_Shape aFirstShape;
1837     ResultPtr aFirstResult = aFeature->firstResult();
1838     if (aFirstResult.get() && aFirstResult->shape().get())
1839       aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
1840     anInfo.myFirstResultShape = aFirstShape;
1841     Handle(SelectMgr_EntityOwner) anOwner = aPrs->owner();
1842     if (aResult.get()) {
1843       getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1844           anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
1845     }
1846     else {
1847       std::list<ResultPtr> aResults = aFeature->results();
1848       std::list<ResultPtr>::const_iterator aIt;
1849       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1850         ResultPtr aResult = *aIt;
1851         getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1852           anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
1853       }
1854     }
1855     theCurrentSelection[aFeature] = anInfo;
1856   }
1857   //qDebug(QString("  storeSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
1858 }
1859
1860 void PartSet_SketcherMgr::restoreSelection(
1861                                 PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
1862 {
1863   if (!myCurrentSketch.get())
1864     return;
1865
1866   //qDebug(QString("restoreSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
1867   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1868   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1869   FeatureToSelectionMap::const_iterator aSIt = theCurrentSelection.begin(),
1870                                         aSLast = theCurrentSelection.end();
1871   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1872   anOwnersToSelect.Clear();
1873   for (; aSIt != aSLast; aSIt++) {
1874     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, theCurrentSelection,
1875                        anOwnersToSelect);
1876   }
1877   aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1878 }
1879
1880 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
1881 {
1882   PartSet_Tools::ConstraintVisibleState aType = (PartSet_Tools::ConstraintVisibleState)theType;
1883
1884   updateBySketchParameters(aType, theState);
1885 }
1886
1887 void PartSet_SketcherMgr::updateBySketchParameters(
1888                                    const PartSet_Tools::ConstraintVisibleState& theType,
1889                                    bool theState)
1890 {
1891   if (myCurrentSketch.get() == NULL)
1892     return;
1893
1894   bool aPrevState = myIsConstraintsShown[theType];
1895   myIsConstraintsShown[theType] = theState;
1896
1897   switch (theType) {
1898     case PartSet_Tools::Geometrical:
1899     case PartSet_Tools::Dimensional: {
1900       if (aPrevState != theState) {
1901         ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1902         XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1903         for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1904           FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1905           bool aProcessed = false;
1906           bool aConstraintDisplayed = canDisplayConstraint(aSubFeature, theType, aProcessed);
1907           if (aProcessed)
1908             aSubFeature->setDisplayed(aConstraintDisplayed);
1909         }
1910         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1911       }
1912     }
1913     break;
1914     case PartSet_Tools::Expressions: {
1915       if (aPrevState != theState) {
1916         /// call all sketch features redisplay, the expression state will be corrected in customize
1917         /// of distance presentation
1918         Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1919         PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
1920       }
1921     }
1922     break;
1923   }
1924 }
1925
1926 void PartSet_SketcherMgr::updateSelectionPriority(ObjectPtr theObject,
1927                                                   FeaturePtr theFeature)
1928 {
1929   if (!theObject.get() || !theFeature.get())
1930     return;
1931
1932   AISObjectPtr anAIS = workshop()->displayer()->getAISObject(theObject);
1933   Handle(AIS_InteractiveObject) anAISIO;
1934   if (anAIS.get() != NULL) {
1935     anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1936   }
1937
1938   if (!anAISIO.IsNull()) { // the presentation for the object is visualized
1939     int anAdditionalPriority = 0;
1940     // current feature
1941     std::shared_ptr<SketchPlugin_Feature> aSPFeature =
1942             std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
1943     if (aSPFeature.get() != NULL) {
1944       // 1. Vertices
1945       // 2. Simple segments
1946       // 3. External objects (violet color)
1947       // 4. Auxiliary segments (dotted)
1948       // StdSelect_BRepSelectionTool::Load uses priority calculating:
1949       // Standard_Integer aPriority =
1950       // (thePriority == -1) ? GetStandardPriority (theShape, theType) : thePriority;
1951       // Priority of Vertex is 8, edge(segment) is 7.
1952       // It might be not corrected as provides the condition above.
1953       bool isExternal = aSPFeature->isExternal();
1954       bool isAuxiliary = PartSet_Tools::isAuxiliarySketchEntity(aSPFeature);
1955       // current feature
1956       if (!isExternal && !isAuxiliary)
1957         anAdditionalPriority = 30;
1958       // external feature
1959       if (isExternal)
1960         anAdditionalPriority = 20;
1961       // auxiliary feature
1962       if (isAuxiliary) {
1963         anAdditionalPriority = 10; /// auxiliary objects should have less priority that
1964         // edges/vertices of local selection on not-sketch objects
1965       }
1966       Handle(ModuleBase_ResultPrs) aResult = Handle(ModuleBase_ResultPrs)::DownCast(anAISIO);
1967       if (!aResult.IsNull()) {
1968         aResult->setAdditionalSelectionPriority(anAdditionalPriority);
1969       }
1970     }
1971   }
1972 }
1973
1974 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
1975 {
1976   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1977   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1978   return aConnector->workshop();
1979 }
1980
1981 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1982 {
1983   return workshop()->operationMgr();
1984 }
1985