]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_SketcherMgr.cpp
Salome HOME
Issue #2625: Provide correct behavior of arrow of current feature
[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         if (aWgt->attributeID() == SketchPlugin_Constraint::VALUE() ||
652             aWgt->attributeID() == SketchPlugin_ConstraintAngle::ANGLE_VALUE_ID()) {
653           PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
654           if (anEditor)
655             anEditor->showPopupEditor();
656           return;
657         }
658       }
659     }
660   }
661 }
662
663 void PartSet_SketcherMgr::onApplicationStarted()
664 {
665   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
666   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
667   XGUI_Workshop* aWorkshop = aConnector->workshop();
668   PartSet_SketcherReentrantMgr* aReentranceMgr = myModule->sketchReentranceMgr();
669
670   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
671   if (aPropertyPanel) {
672     //connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
673     //        this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
674
675     connect(aPropertyPanel, SIGNAL(noMoreWidgets(const std::string&)),
676             aReentranceMgr, SLOT(onNoMoreWidgets(const std::string&)));
677     //connect(aPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
678     //        aReentranceMgr, SLOT(onWidgetActivated()));
679   }
680
681   XGUI_ViewerProxy* aViewerProxy = aWorkshop->viewer();
682   connect(aViewerProxy, SIGNAL(enterViewPort()), this, SLOT(onEnterViewPort()));
683   connect(aViewerProxy, SIGNAL(leaveViewPort()), this, SLOT(onLeaveViewPort()));
684
685   XGUI_ContextMenuMgr* aContextMenuMgr = aWorkshop->contextMenuMgr();
686   connect(aContextMenuMgr, SIGNAL(beforeContextMenu()), this, SLOT(onBeforeContextMenu()));
687   connect(aContextMenuMgr, SIGNAL(afterContextMenu()), this, SLOT(onAfterContextMenu()));
688 }
689
690 //void PartSet_SketcherMgr::onBeforeWidgetActivated(ModuleBase_ModelWidget* theWidget)
691 //{
692   //if (!myClickedPoint.myIsInitialized)
693   //  return;
694
695   //ModuleBase_Operation* aOperation = getCurrentOperation();
696   // the distance constraint feature should not use the clickedd point
697   // this is workaround in order to don't throw down the flyout point value,
698   // set by execute() method of these type of features
699   //if (isDistanceOperation(aOperation))
700   //  return;
701
702   //PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(theWidget);
703   //if (aPnt2dWgt) {
704   //  aPnt2dWgt->setPoint(myClickedPoint.myCurX, myClickedPoint.myCurY);
705   //}
706 //}
707
708 void PartSet_SketcherMgr::onBeforeContextMenu()
709 {
710   myIsPopupMenuActive = true;
711 }
712
713 void PartSet_SketcherMgr::onAfterContextMenu()
714 {
715   myIsPopupMenuActive = false;
716 }
717
718 void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent,
719                                      Point& thePoint)
720 {
721   Handle(V3d_View) aView = theWnd->v3dView();
722   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
723   double aX, anY;
724   PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, anY);
725   thePoint.setValue(aX, anY);
726 }
727
728 void PartSet_SketcherMgr::launchEditing()
729 {
730   if (!myCurrentSelection.empty()) {
731     FeaturePtr aFeature = myCurrentSelection.begin().key();
732     std::shared_ptr<SketchPlugin_Feature> aSPFeature =
733               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
734     if (aSPFeature) {
735       if (!aSPFeature->isExternal())
736         myModule->editFeature(aSPFeature);
737       else {
738         // need to edit a feature (Projection/IntersectionPoint),
739         // which produces current External feature
740         FeaturePtr aProducerFeature = PartSet_Tools::findRefsToMeFeature(aFeature,
741                                                         SketchPlugin_Projection::ID());
742         if (!aProducerFeature.get())
743           aProducerFeature = PartSet_Tools::findRefsToMeFeature(aFeature,
744                                                         SketchPlugin_IntersectionPoint::ID());
745         if (aProducerFeature.get())
746           myModule->editFeature(aProducerFeature);
747       }
748     }
749   }
750 }
751
752 bool PartSet_SketcherMgr::sketchSolverError()
753 {
754   bool anError = false;
755   CompositeFeaturePtr aSketch = activeSketch();
756   if (aSketch.get()) {
757     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
758     anError = !aAttributeString->value().empty();
759   }
760   return anError;
761 }
762
763 QString PartSet_SketcherMgr::getFeatureError(const FeaturePtr& theFeature)
764 {
765   QString anError;
766   if (!theFeature.get() || !theFeature->data()->isValid())
767     return anError;
768
769   CompositeFeaturePtr aSketch = activeSketch();
770   if (aSketch.get() && aSketch == theFeature) {
771     std::string aSolverError = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR())->value();
772     anError = ModuleBase_Tools::translate(aSketch->getKind(), aSolverError);
773   }
774   return anError;
775 }
776
777 void PartSet_SketcherMgr::clearClickedFlags()
778 {
779   //myClickedPoint.clear();
780   myCurrentPoint.clear();
781 }
782
783 const QStringList& PartSet_SketcherMgr::replicationsIdList()
784 {
785   static QStringList aReplicationIds;
786   if (aReplicationIds.size() == 0) {
787     aReplicationIds << SketchPlugin_ConstraintMirror::ID().c_str();
788     aReplicationIds << SketchPlugin_MultiRotation::ID().c_str();
789     aReplicationIds << SketchPlugin_MultiTranslation::ID().c_str();
790   }
791   return aReplicationIds;
792 }
793
794 const QStringList& PartSet_SketcherMgr::constraintsIdList()
795 {
796   static QStringList aConstraintIds;
797   if (aConstraintIds.size() == 0) {
798     aConstraintIds << SketchPlugin_ConstraintLength::ID().c_str();
799     aConstraintIds << SketchPlugin_ConstraintDistance::ID().c_str();
800     aConstraintIds << SketchPlugin_ConstraintRigid::ID().c_str();
801     aConstraintIds << SketchPlugin_ConstraintRadius::ID().c_str();
802     aConstraintIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
803     aConstraintIds << SketchPlugin_ConstraintParallel::ID().c_str();
804     aConstraintIds << SketchPlugin_ConstraintHorizontal::ID().c_str();
805     aConstraintIds << SketchPlugin_ConstraintVertical::ID().c_str();
806     aConstraintIds << SketchPlugin_ConstraintEqual::ID().c_str();
807     aConstraintIds << SketchPlugin_ConstraintTangent::ID().c_str();
808     aConstraintIds << SketchPlugin_ConstraintCoincidence::ID().c_str();
809     aConstraintIds << SketchPlugin_ConstraintAngle::ID().c_str();
810     aConstraintIds << SketchPlugin_ConstraintCollinear::ID().c_str();
811     aConstraintIds << SketchPlugin_ConstraintMiddle::ID().c_str();
812     aConstraintIds << SketchPlugin_ConstraintMirror::ID().c_str();
813     aConstraintIds << SketchPlugin_MultiTranslation::ID().c_str();
814     aConstraintIds << SketchPlugin_MultiRotation::ID().c_str();
815     aConstraintIds << SketchPlugin_ConstraintDistanceAlongDir::ID().c_str();
816     aConstraintIds << SketchPlugin_ConstraintDistanceHorizontal::ID().c_str();
817     aConstraintIds << SketchPlugin_ConstraintDistanceVertical::ID().c_str();
818   }
819   return aConstraintIds;
820 }
821
822 void PartSet_SketcherMgr::sketchSelectionModes(const CompositeFeaturePtr& theSketch,
823                                                QIntList& theModes)
824 {
825   if (!theSketch.get() || !PartSet_Tools::sketchPlane(theSketch).get())
826     return;
827
828   theModes.append(SketcherPrs_Tools::Sel_Dimension_Text);
829   theModes.append(SketcherPrs_Tools::Sel_Dimension_Line);
830   theModes.append(SketcherPrs_Tools::Sel_Constraint);
831   theModes.append(TopAbs_VERTEX);
832   theModes.append(TopAbs_EDGE);
833 }
834
835 Handle(AIS_InteractiveObject) PartSet_SketcherMgr::createPresentation(const ResultPtr& theResult)
836 {
837   Handle(AIS_InteractiveObject) aPrs;
838
839   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
840   if (aFeature.get() && aFeature->getKind() == SketchPlugin_Sketch::ID()) {
841     aPrs = new PartSet_ResultSketchPrs(theResult);
842   }
843   return aPrs;
844 }
845
846 bool PartSet_SketcherMgr::isSketchOperation(ModuleBase_Operation* theOperation)
847 {
848   return theOperation && theOperation->id().toStdString() == SketchPlugin_Sketch::ID();
849 }
850
851 bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation) const
852 {
853   bool aNestedSketch = false;
854
855   FeaturePtr anActiveSketch = activeSketch();
856   if (anActiveSketch.get() && theOperation) {
857     ModuleBase_Operation* aSketchOperation = operationMgr()->findOperation(
858                                                               anActiveSketch->getKind().c_str());
859     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
860                                                                                   (theOperation);
861     if (aSketchOperation && aFOperation) {
862       FeaturePtr aFeature = aFOperation->feature();
863       if (aFeature.get()) {
864         QStringList aGrantedOpIds = aSketchOperation->grantedOperationIds();
865         aNestedSketch = aGrantedOpIds.contains(aFeature->getKind().c_str());
866       }
867     }
868   }
869   return aNestedSketch;
870 }
871
872 bool PartSet_SketcherMgr::isNestedSketchFeature(const QString& theFeatureKind) const
873 {
874   bool aNestedSketch = false;
875
876   FeaturePtr anActiveSketch = activeSketch();
877   if (anActiveSketch.get()) {
878     ModuleBase_Operation* aSketchOperation = operationMgr()->findOperation(
879                                                               anActiveSketch->getKind().c_str());
880     if (aSketchOperation) {
881       QStringList aGrantedOpIds = aSketchOperation->grantedOperationIds();
882       aNestedSketch = aGrantedOpIds.contains(theFeatureKind);
883     }
884   }
885   return aNestedSketch;
886 }
887
888 bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation,
889                                                   const CompositeFeaturePtr& theSketch) const
890 {
891   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
892                                                                (theOperation);
893   return aFOperation && !aFOperation->isEditOperation() &&
894          isNestedSketchOperation(aFOperation);
895 }
896
897 bool PartSet_SketcherMgr::isNestedEditOperation(ModuleBase_Operation* theOperation,
898                                                 const CompositeFeaturePtr& theSketch) const
899 {
900   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
901                                                                (theOperation);
902   return aFOperation && aFOperation->isEditOperation() &&
903     isNestedSketchOperation(aFOperation);
904 }
905
906 bool PartSet_SketcherMgr::isEntity(const std::string& theId)
907 {
908   return (theId == SketchPlugin_Line::ID()) ||
909          (theId == SketchPlugin_Point::ID()) ||
910          (theId == SketchPlugin_Arc::ID()) ||
911          (theId == SketchPlugin_Circle::ID());
912 }
913
914 bool PartSet_SketcherMgr::isExternalFeature(const FeaturePtr& theFeature)
915 {
916   std::shared_ptr<SketchPlugin_Feature> aSPFeature =
917           std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
918   return aSPFeature.get() && aSPFeature->isExternal();
919 }
920
921 bool PartSet_SketcherMgr::isDistanceOperation(ModuleBase_Operation* theOperation)
922 {
923   std::string anId = theOperation ? theOperation->id().toStdString() : "";
924
925   return isDistanceKind(anId);
926 }
927
928 bool PartSet_SketcherMgr::isDistanceKind(std::string& theKind)
929 {
930   return (theKind == SketchPlugin_ConstraintLength::ID()) ||
931          (theKind == SketchPlugin_ConstraintDistance::ID()) ||
932          (theKind == SketchPlugin_ConstraintRadius::ID()) ||
933          (theKind == SketchPlugin_ConstraintAngle::ID()) ||
934          (theKind == SketchPlugin_ConstraintDistanceHorizontal::ID()) ||
935          (theKind == SketchPlugin_ConstraintDistanceVertical::ID()) ||
936          (theKind == SketchPlugin_ConstraintDistanceAlongDir::ID());
937 }
938
939 void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
940 {
941   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
942                                                                (getCurrentOperation());
943   if (!aFOperation)
944     return;
945
946   myModule->onViewTransformed();
947
948   // Display all sketcher sub-Objects
949   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFOperation->feature());
950   double aSizeOfView = 0;
951   std::shared_ptr<GeomAPI_Pnt> aCentralPoint;
952   if (aFOperation->isEditOperation() &&
953       mySketchPlane->getDefaultSizeOfView(myCurrentSketch, aSizeOfView, aCentralPoint)) {
954     mySketchPlane->setSizeOfView(aSizeOfView, true, aCentralPoint);
955   }
956
957   mySketchPlane->createSketchPlane(myCurrentSketch, myModule->workshop());
958   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
959
960   // Hide sketcher result
961   std::list<ResultPtr> aResults = myCurrentSketch->results();
962   std::list<ResultPtr>::const_iterator aIt;
963   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
964     (*aIt)->setDisplayed(false);
965   }
966   myCurrentSketch->setDisplayed(false);
967
968   // Remove invalid sketch entities
969   std::set<FeaturePtr> anInvalidFeatures;
970   ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
971   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
972     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
973     if (aFeature.get()) {
974       if (!aFactory->validate(aFeature))
975         anInvalidFeatures.insert(aFeature);
976     }
977   }
978   if (!anInvalidFeatures.empty()) {
979     std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
980     ModelAPI_Tools::findAllReferences(anInvalidFeatures, aReferences, false);
981
982     std::set<FeaturePtr>::const_iterator anIt = anInvalidFeatures.begin(),
983                                          aLast = anInvalidFeatures.end();
984     // separate features to references to parameter features and references to others
985     QStringList anInvalidFeatureNames;
986     for (; anIt != aLast; anIt++) {
987       FeaturePtr aFeature = *anIt;
988       if (aFeature.get())
989         anInvalidFeatureNames.append(aFeature->name().c_str());
990     }
991     std::string aPrefixInfo = QString("Invalid features of the sketch will be deleted: %1.\n\n").
992                                   arg(anInvalidFeatureNames.join(", ")).toStdString().c_str();
993     std::set<FeaturePtr> aFeatureRefsToDelete;
994     if (ModuleBase_Tools::askToDelete(anInvalidFeatures, aReferences, aConnector->desktop(),
995                                       aFeatureRefsToDelete, aPrefixInfo)) {
996       if (!aFeatureRefsToDelete.empty())
997         anInvalidFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
998       ModelAPI_Tools::removeFeatures(anInvalidFeatures, true);
999       Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1000       // TODO: call the next method in the XGUI_OperationMgr::onOperationStarted().
1001       workshop()->errorMgr()->updateAcceptAllAction(myCurrentSketch);
1002     }
1003   }
1004
1005   // update state of overconstraint listener should be done before sketch features/results
1006   // display (as the display will ask custom color from the listener)
1007   myModule->overconstraintListener()->setActive(true);
1008   // Display sketcher objects
1009   QStringList anInfo;
1010   Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1011   const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
1012   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1013     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1014 #ifdef DEBUG_SKETCHER_ENTITIES
1015     anInfo.append(ModuleBase_Tools::objectInfo(aFeature));
1016 #endif
1017     std::list<ResultPtr> aResults = aFeature->results();
1018     std::list<ResultPtr>::const_iterator aIt;
1019     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1020       if ((*aIt)->isDisplayed())
1021         // Display object if it was created outside of GUI
1022         aECreator->sendUpdated((*aIt), EVENT_DISP);
1023       else
1024         (*aIt)->setDisplayed(true);
1025     }
1026     if (aFeature->isDisplayed())
1027       aECreator->sendUpdated(aFeature, EVENT_DISP);
1028     else
1029       aFeature->setDisplayed(true);
1030   }
1031 #ifdef DEBUG_SKETCHER_ENTITIES
1032   QString anInfoStr = anInfo.join(";\t");
1033   qDebug(QString("startSketch: %1, %2").arg(anInfo.size()).arg(anInfoStr).toStdString().c_str());
1034 #endif
1035
1036   bool aHasPlane = false;
1037   std::shared_ptr<GeomAPI_Pln> aPln;
1038   aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
1039   Handle(SelectMgr_Filter) aFilter = myModule->selectionFilter(SF_SketchPlaneFilter);
1040   if (!aFilter.IsNull())
1041     Handle(ModuleBase_ShapeInPlaneFilter)::DownCast(aFilter)->setPlane(aPln);
1042
1043   workshop()->selectionActivate()->updateSelectionFilters();
1044   workshop()->selectionActivate()->updateSelectionModes();
1045
1046   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1047
1048   myExternalPointsMgr = new PartSet_ExternalPointsMgr(myModule->workshop(), myCurrentSketch);
1049 }
1050
1051 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
1052 {
1053   myIsMouseOverWindow = false;
1054   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
1055   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
1056   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
1057
1058   if (myExternalPointsMgr) {
1059     delete myExternalPointsMgr;
1060     myExternalPointsMgr = 0;
1061   }
1062
1063   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
1064
1065   DataPtr aData = myCurrentSketch->data();
1066   if (!aData->isValid()) {
1067     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1068     // The sketch was aborted
1069     myCurrentSketch = CompositeFeaturePtr();
1070     mySketchPlane->eraseSketchPlane(myModule->workshop());
1071
1072     // Erase all sketcher objects
1073     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1074     foreach (ObjectPtr aObj, aObjects) {
1075       DataPtr aObjData = aObj->data();
1076       if (!aObjData->isValid())
1077         aObj->setDisplayed(false);
1078     }
1079   }
1080   else {
1081     // Hide all sketcher sub-Objects
1082     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1083       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1084       std::list<ResultPtr> aResults = aFeature->results();
1085       std::list<ResultPtr>::const_iterator aIt;
1086       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1087         (*aIt)->setDisplayed(false);
1088       }
1089       aFeature->setDisplayed(false);
1090     }
1091     // Display sketcher result
1092     std::list<ResultPtr> aResults = myCurrentSketch->results();
1093     std::list<ResultPtr>::const_iterator aIt;
1094     Events_Loop* aLoop = Events_Loop::loop();
1095     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1096
1097     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1098                                                                            (theOperation);
1099     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1100       if (!aFOperation->isDisplayedOnStart(*aIt)) {
1101         (*aIt)->setDisplayed(true);
1102         // this display event is needed because sketch already may have "displayed" state,
1103         // but not displayed while it is still active (issue 613, abort of existing sketch)
1104         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
1105       }
1106     }
1107     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
1108       myCurrentSketch->setDisplayed(true);
1109
1110     myCurrentSketch = CompositeFeaturePtr();
1111     mySketchPlane->eraseSketchPlane(myModule->workshop());
1112
1113     Events_Loop::loop()->flush(aDispEvent);
1114   }
1115   workshop()->selectionActivate()->updateSelectionFilters();
1116   workshop()->selectionActivate()->updateSelectionModes();
1117 }
1118
1119 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
1120 {
1121   if (canChangeCursor(theOperation) && myIsMouseOverWindow) {
1122     QCursor* aCurrentCursor = QApplication::overrideCursor();
1123     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
1124       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
1125 #ifdef DEBUG_CURSOR
1126       qDebug("startNestedSketch() : Qt::CrossCursor");
1127 #endif
1128     }
1129   }
1130 }
1131
1132 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
1133 {
1134   myIsMouseOverViewProcessed = true;
1135   operationMgr()->onValidateOperation();
1136   // when sketch nested operation is stopped the cursor should be restored unconditionally
1137   //if (canChangeCursor(theOperation)) {
1138     QApplication::restoreOverrideCursor();
1139 #ifdef DEBUG_CURSOR
1140     qDebug("stopNestedSketch() : None");
1141 #endif
1142   //}
1143   /// improvement to deselect automatically all eventual selected objects, when
1144   // returning to the neutral point of the Sketcher
1145   bool isClearSelectionPossible = true;
1146   if (myIsEditLaunching) {
1147     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1148                                                                           (theOperation);
1149     if (aFOperation) {
1150       FeaturePtr aFeature = aFOperation->feature();
1151       if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1152         isClearSelectionPossible = false;
1153       }
1154     }
1155   }
1156   if (isClearSelectionPossible)
1157     workshop()->selector()->clearSelection();
1158 }
1159
1160 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
1161 {
1162   if (isNestedCreateOperation(theOperation, activeSketch())) {
1163     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1164                                                                              (theOperation);
1165     if (aFOperation) {
1166       FeaturePtr aFeature = aFOperation->feature();
1167       // it is necessary to check the the feature data validity because
1168       // some kind of features are removed by an operation commit(the macro state of a feature)
1169       if (aFeature.get() && aFeature->data()->isValid()) {
1170         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
1171       }
1172     }
1173   }
1174 }
1175
1176 bool PartSet_SketcherMgr::sketchSelectionFilter(const XGUI_SelectionFilterType theFilterType)
1177 {
1178   return mySelectionFilterTypes.find(theFilterType) != mySelectionFilterTypes.end();
1179 }
1180
1181 void PartSet_SketcherMgr::registerSelectionFilter(const XGUI_SelectionFilterType theFilterType,
1182                                                   const Handle(SelectMgr_Filter)& theFilter)
1183 {
1184   mySelectionFilterTypes.insert(theFilterType);
1185   myModule->registerSelectionFilter(theFilterType, theFilter);
1186 }
1187
1188 bool PartSet_SketcherMgr::operationActivatedByPreselection()
1189 {
1190   bool isOperationStopped = false;
1191   ModuleBase_Operation* anOperation = getCurrentOperation();
1192   if(anOperation && isNestedSketchOperation(anOperation)) {
1193     // Set final definitions if they are necessary
1194     //propertyPanelDefined(aOperation);
1195     /// Commit sketcher operations automatically
1196     /// distance operation are able to show popup editor to modify the distance value
1197     /// after entering the value, the operation should be committed/aborted(by Esc key)
1198     bool aCanCommitOperation = true;
1199     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1200                                                                             (anOperation);
1201     if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation)) {
1202       bool aValueAccepted = setDistanceValueByPreselection(anOperation, myModule->workshop(),
1203                                                            aCanCommitOperation);
1204       if (!aValueAccepted)
1205         return isOperationStopped;
1206     }
1207
1208     if (aCanCommitOperation)
1209       isOperationStopped = anOperation->commit();
1210     else {
1211       anOperation->abort();
1212       isOperationStopped = true;
1213     }
1214   }
1215   return isOperationStopped;
1216 }
1217
1218 bool PartSet_SketcherMgr::canUndo() const
1219 {
1220   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1221 }
1222
1223 bool PartSet_SketcherMgr::canRedo() const
1224 {
1225   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1226 }
1227
1228 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1229 {
1230   bool aCanErase = true;
1231   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1232   if (myCurrentSketch.get()) {
1233     return !isObjectOfSketch(theObject);
1234   }
1235   return aCanErase;
1236 }
1237
1238 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1239 {
1240   bool aCanDisplay = true;
1241
1242   bool aHasActiveSketch = activeSketch().get() != NULL;
1243   if (aHasActiveSketch) {
1244     // 1. the sketch feature should not be displayed during the sketch active operation
1245     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch
1246     // nested features can be visualized
1247     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1248     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1249       aCanDisplay = false;
1250     }
1251     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1252                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1253     /// some sketch entities should be never shown, e.g. projection feature
1254     if (aSketchFeature.get())
1255       aCanDisplay = aSketchFeature->canBeDisplayed();
1256   }
1257   else { // there are no an active sketch
1258     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1259     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1260     if (aFeature.get() != NULL) {
1261       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1262                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1263       if (aSketchFeature.get()) {
1264         aCanDisplay = false;
1265       }
1266     }
1267   }
1268
1269   // 3. the method should not filter the objects, which are not related to the current operation.
1270   // The object is filtered just if it is a current operation feature or this feature result
1271   if (aCanDisplay) {
1272     bool isObjectFound = false;
1273     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1274                                                                  (getCurrentOperation());
1275     if (aFOperation) {
1276       FeaturePtr aFeature = aFOperation->feature();
1277       if (aFeature.get()) {
1278         std::list<ResultPtr> aResults = aFeature->results();
1279         if (theObject == aFeature)
1280           isObjectFound = true;
1281         else {
1282           std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1283           for (; anIt != aLast && !isObjectFound; anIt++) {
1284             isObjectFound = *anIt == theObject;
1285           }
1286         }
1287       }
1288     }
1289     if (isObjectFound) {
1290       // 4. For created nested feature operation do not display the created feature if
1291       // the mouse curstor leaves the OCC window.
1292       // The correction cases, which ignores this condition:
1293       // a. the property panel values modification
1294       // b. the popup menu activated
1295       // c. widget editor control
1296       #ifndef DEBUG_DO_NOT_BY_ENTER
1297       if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
1298         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1299         ModuleBase_WidgetEditor* anEditorWdg =
1300           anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1301         // the active widget editor should not influence here. The presentation should be visible
1302         // always when this widget is active.
1303         if (!anEditorWdg && !myIsPopupMenuActive) {
1304           // during a nested create operation, the feature is redisplayed only
1305           // if the mouse over view
1306           // of there was a value modified in the property panel after the mouse left the view
1307           aCanDisplay = canDisplayCurrentCreatedFeature();
1308         }
1309       }
1310       #endif
1311     }
1312   }
1313
1314   // checks the sketcher constraints visibility according to active sketch check box states
1315   if (aCanDisplay) {
1316     bool aProcessed = false;
1317     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1318     if (aFeature.get()) {
1319       bool aConstraintDisplayed = canDisplayConstraint(aFeature, PartSet_Tools::Any, aProcessed);
1320       if (aProcessed)
1321         aCanDisplay = aConstraintDisplayed;
1322     }
1323   }
1324
1325   return aCanDisplay;
1326 }
1327
1328 bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
1329                                              const PartSet_Tools::ConstraintVisibleState& theState,
1330                                              bool& isProcessed) const
1331 {
1332   bool aSwitchedOn = true;
1333
1334   const QStringList& aConstrIds = constraintsIdList();
1335
1336   std::string aKind = theFeature->getKind();
1337   if (aConstrIds.contains(QString(aKind.c_str()))) {
1338     bool isTypedConstraint = false;
1339
1340     switch (theState) {
1341       case PartSet_Tools::Dimensional: {
1342         bool isDistance = isDistanceKind(aKind);
1343         if (isDistance) {
1344           isProcessed = true;
1345           aSwitchedOn = myIsConstraintsShown[theState];
1346         }
1347       }
1348       break;
1349       case PartSet_Tools::Geometrical: {
1350         bool isGeometrical = !isDistanceKind(aKind);
1351         if (isGeometrical) {
1352           isProcessed = true;
1353           aSwitchedOn = myIsConstraintsShown[theState];
1354         }
1355       }
1356       break;
1357       case PartSet_Tools::Any: {
1358         isProcessed = true;
1359         bool isDistance = isDistanceKind(aKind);
1360         if (isDistance)
1361           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Dimensional];
1362         else
1363           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Geometrical];
1364       }
1365       break;
1366     default:
1367       break;
1368     }
1369   }
1370   return aSwitchedOn;
1371 }
1372
1373 /*void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
1374 {
1375   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1376                                                                            (getCurrentOperation());
1377   if (aFOperation && myCurrentSketch.get()) {
1378     // find results of the current operation
1379     // these results should not be proposed to be deleted
1380     FeaturePtr anOperationFeature = aFOperation->feature();
1381     std::list<ResultPtr> anOperationResultList = anOperationFeature->results();
1382     std::set<ResultPtr> anOperationResults;
1383     std::list<ResultPtr>::const_iterator aRIt = anOperationResultList.begin(),
1384                                         aRLast = anOperationResultList.end();
1385     for (; aRIt != aRLast; aRIt++)
1386       anOperationResults.insert(*aRIt);
1387
1388     std::set<FeaturePtr> anObjectsToBeDeleted;
1389     QStringList anObjectsToBeDeletedNames;
1390     std::list<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1391     for (; anIt != aLast; anIt++) {
1392       ObjectPtr anObject = *anIt;
1393       bool aCanErase = true;
1394       // when the sketch operation is active, results of sketch sub-feature can not be hidden
1395       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1396       // the result is found between current feature results
1397       if (anOperationResults.find(aResult) != anOperationResults.end())
1398         continue;
1399
1400       if (aResult.get()) {
1401         // Display sketcher objects
1402         for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1403           FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1404           std::list<ResultPtr> aResults = aFeature->results();
1405           std::list<ResultPtr>::const_iterator anIt;
1406           for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1407             aCanErase = *anIt != aResult;
1408           }
1409         }
1410       }
1411       if (!aCanErase) {
1412         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
1413         if (aFeature.get() && anObjectsToBeDeleted.find(aFeature) == anObjectsToBeDeleted.end()) {
1414           anObjectsToBeDeleted.insert(aFeature);
1415           anObjectsToBeDeletedNames.append(aFeature->name().c_str());
1416         }
1417       }
1418     }
1419     if (!anObjectsToBeDeleted.empty()) {
1420       QString aFeatureNames = anObjectsToBeDeletedNames.join(", ");
1421       QString aMessage = tr("The following features have incorrect presentation and \
1422 will be hidden: %1. Would you like to delete them?")
1423                          .arg(aFeatureNames);
1424       int anAnswer = QMessageBox::question(qApp->activeWindow(), tr("Features hide"),
1425                                            aMessage, QMessageBox::Ok | QMessageBox::Cancel,
1426                                            QMessageBox::Cancel);
1427       if (anAnswer == QMessageBox::Ok) {
1428         QObjectPtrList anObjects;
1429         std::set<FeaturePtr>::const_iterator anIt = anObjectsToBeDeleted.begin(),
1430                                              aLast = anObjectsToBeDeleted.end();
1431         for (; anIt != aLast; anIt++)
1432           anObjects.append(*anIt);
1433         SessionPtr aMgr = ModelAPI_Session::get();
1434         DocumentPtr aDoc = aMgr->activeDocument();
1435         bool aIsOp = aMgr->isOperation();
1436         if (!aIsOp)
1437           aMgr->startOperation();
1438         workshop()->deleteFeatures(anObjects);
1439         //static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
1440         //static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
1441         //Events_Loop::loop()->flush(aDeletedEvent);
1442         //Events_Loop::loop()->flush(aRedispEvent);
1443
1444         if (!aIsOp)
1445           aMgr->finishOperation();
1446       }
1447     }
1448   }
1449 }*/
1450
1451 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1452 {
1453   bool aCanDisplay = myIsMouseOverWindow;
1454   if (!aCanDisplay) {
1455     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1456     if (anActiveWidget)
1457       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1458   }
1459   return aCanDisplay;
1460 }
1461
1462 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1463 {
1464   return isNestedCreateOperation(theOperation, activeSketch()) ||
1465          myModule->sketchReentranceMgr()->isInternalEditActive();
1466 }
1467
1468 const QMap<PartSet_Tools::ConstraintVisibleState, bool>& PartSet_SketcherMgr::showConstraintStates()
1469 {
1470   return myIsConstraintsShown;
1471 }
1472
1473 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1474 {
1475   bool isFoundObject = false;
1476
1477   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1478   if (anObjectFeature.get()) {
1479     int aSize = myCurrentSketch->numberOfSubs();
1480     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1481       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1482       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1483     }
1484   }
1485   return isFoundObject;
1486 }
1487
1488 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePlane)
1489 {
1490   Handle(SelectMgr_Filter) aFilter = myModule->selectionFilter(SF_SketchPlaneFilter);
1491   if (!aFilter.IsNull())
1492     Handle(ModuleBase_ShapeInPlaneFilter)::DownCast(aFilter)->setPlane(thePlane);
1493
1494   workshop()->selectionActivate()->updateSelectionModes();
1495 }
1496
1497 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
1498                                                          ModuleBase_IWorkshop* theWorkshop,
1499                                                          bool& theCanCommitOperation)
1500 {
1501   bool isValueAccepted = false;
1502   theCanCommitOperation = false;
1503
1504   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1505                                                                               (theOperation);
1506   FeaturePtr aFeature = aFOperation->feature();
1507   // editor is shown only if all attribute references are filled by preseletion
1508   bool anAllRefAttrInitialized = true;
1509
1510   std::list<AttributePtr> aRefAttrs = aFeature->data()->attributes(
1511                                               ModelAPI_AttributeRefAttr::typeId());
1512   std::list<AttributePtr>::const_iterator anIt = aRefAttrs.begin(), aLast = aRefAttrs.end();
1513   for (; anIt != aLast && anAllRefAttrInitialized; anIt++) {
1514     anAllRefAttrInitialized = (*anIt)->isInitialized();
1515   }
1516   if (anAllRefAttrInitialized) {
1517     // Activate dimension value editing on double click
1518     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
1519     QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
1520     // Find corresponded widget to activate value editing
1521     foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
1522       if (aWgt->attributeID() == "ConstraintValue") {
1523         // the featue should be displayed in order to find the AIS text position,
1524         // the place where the editor will be shown
1525         aFeature->setDisplayed(true);
1526         /// the execute is necessary to perform in the feature compute for flyout position
1527         aFeature->execute();
1528
1529         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1530         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1531
1532         PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
1533         if (anEditor) {
1534           int aX = 0, anY = 0;
1535
1536           XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(theWorkshop);
1537           XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1538           AISObjectPtr anAIS = aDisplayer->getAISObject(aFeature);
1539           Handle(AIS_InteractiveObject) anAISIO;
1540           if (anAIS.get() != NULL) {
1541             anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1542           }
1543           if (anAIS.get() != NULL) {
1544             Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1545
1546             if (!anAISIO.IsNull()) {
1547               Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAISIO);
1548               if (!aDim.IsNull()) {
1549                 gp_Pnt aPosition = aDim->GetTextPosition();
1550
1551                 ModuleBase_IViewer* aViewer = aWorkshop->viewer();
1552                 Handle(V3d_View) aView = aViewer->activeView();
1553                 int aCX, aCY;
1554                 aView->Convert(aPosition.X(), aPosition.Y(), aPosition.Z(), aCX, aCY);
1555
1556                 QWidget* aViewPort = aViewer->activeViewPort();
1557                 QPoint aGlPoint = aViewPort->mapToGlobal(QPoint(aCX, aCY));
1558                 aX = aGlPoint.x();
1559                 anY = aGlPoint.y();
1560               }
1561             }
1562             anEditor->setCursorPosition(aX, anY);
1563             isValueAccepted = anEditor->showPopupEditor(false);
1564             theCanCommitOperation = true;
1565           }
1566         }
1567       }
1568     }
1569   }
1570   return isValueAccepted;
1571 }
1572
1573 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1574                                              const FeaturePtr& theSketch,
1575                                              ModuleBase_IWorkshop* theWorkshop,
1576                                              const FeatureToSelectionMap& theSelection,
1577                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1578 {
1579   if (theFeature.get() == NULL)
1580     return;
1581
1582   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1583   SelectionInfo anInfo = anIt.value();
1584   std::set<AttributePtr> aSelectedAttributes = anInfo.myAttributes;
1585   std::set<ResultPtr> aSelectedResults = anInfo.myResults;
1586
1587   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1588
1589   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1590   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1591
1592   // 1. found the feature's owners. Check the AIS objects of the constructions
1593   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1594   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1595     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1596
1597     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1598     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1599     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1600       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1601       if (!anOwner.IsNull())
1602         theOwnersToSelect.Add(anOwner);
1603     }
1604   }
1605
1606   // 2. found the feature results's owners
1607   std::list<ResultPtr> aResults = theFeature->results();
1608   std::list<ResultPtr>::const_iterator aIt;
1609
1610   bool isSameShape = false;
1611   if (aResults.size() > 0) {
1612     ResultPtr aFirstResult = theFeature->firstResult();
1613     if (aFirstResult.get() && aFirstResult->shape().get()) {
1614       TopoDS_Shape aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
1615       isSameShape = aFirstShape.IsEqual(anInfo.myFirstResultShape);
1616     }
1617   }
1618   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1619     ResultPtr aResult = *aIt;
1620     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1621     if (aAISObj.get() == NULL)
1622       continue;
1623     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1624
1625     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1626     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1627     bool aFoundLocalShape = false;
1628     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1629       Handle(StdSelect_BRepOwner) anOwner =
1630         Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1631       if ( anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
1632         continue;
1633       const TopoDS_Shape& aShape = anOwner->Shape();
1634       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1635       if (aShapeType == TopAbs_VERTEX) {
1636         AttributePtr aPntAttr =
1637           PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1638         if (aPntAttr.get() != NULL &&
1639             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end())
1640           theOwnersToSelect.Add(anOwner);
1641         else if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
1642           theOwnersToSelect.Add(anOwner);
1643         }
1644       }
1645       else if (aShapeType == TopAbs_EDGE) {
1646         if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
1647           // try to restore local selection on Shape result
1648           // we can do this only if the shape was not changed
1649           theOwnersToSelect.Add(anOwner);
1650           aFoundLocalShape = true;
1651           break;
1652         }
1653       }
1654     }
1655     if (!aFoundLocalShape) {
1656       // result owners are put in the list of selection only if local selected shapes were not
1657       // found
1658       if (aSelectedResults.find(aResult) != aSelectedResults.end()) {
1659         for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1660           Handle(StdSelect_BRepOwner) anOwner =
1661             Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1662           if ( anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
1663             continue;
1664             // select whole result
1665             theOwnersToSelect.Add(anOwner);
1666         }
1667       }
1668     }
1669   }
1670 }
1671
1672 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
1673                                                  const bool isToConnect)
1674 {
1675   //Temporary commented as we do not modify values in property panel
1676   if (isToConnect) {
1677     //connect(theWidget, SIGNAL(beforeValuesChanged()),
1678     //        this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1679     //connect(theWidget, SIGNAL(afterValuesChanged()),
1680     //        this, SLOT(onAfterValuesChangedInPropertyPanel()));
1681     connect(theWidget, SIGNAL(afterValuesChanged()),
1682             myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
1683   }
1684   else {
1685     //disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1686     //            this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1687     //disconnect(theWidget, SIGNAL(afterValuesChanged()),
1688     //            this, SLOT(onAfterValuesChangedInPropertyPanel()));
1689     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1690                myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
1691   }
1692 }
1693
1694 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1695 {
1696   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1697                                                                            (getCurrentOperation());
1698   if (aFOperation) {
1699     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1700         isNestedSketchOperation(aFOperation) &&
1701         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1702       FeaturePtr aFeature = aFOperation->feature();
1703       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1704     }
1705   }
1706 }
1707
1708 void PartSet_SketcherMgr::customizePresentation(const ObjectPtr& theObject)
1709 {
1710   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1711                                                                            (getCurrentOperation());
1712   if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1713                       isNestedSketchOperation(aFOperation)))
1714     SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
1715
1716   // update entities selection priorities
1717   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1718   if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1719     // update priority for feature
1720     updateSelectionPriority(aFeature, aFeature);
1721     // update priority for results of the feature
1722     std::list<ResultPtr> aResults = aFeature->results();
1723     std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLastIt = aResults.end();
1724     for (; anIt != aLastIt; anIt++)
1725       updateSelectionPriority(*anIt, aFeature);
1726   }
1727 }
1728
1729 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1730 {
1731   return myModule->workshop()->currentOperation();
1732 }
1733
1734 //**************************************************************
1735 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1736 {
1737   ModuleBase_ModelWidget* aWidget = 0;
1738   ModuleBase_Operation* anOperation = getCurrentOperation();
1739   if (anOperation) {
1740     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1741     if (aPanel)
1742       aWidget = aPanel->activeWidget();
1743   }
1744   return aWidget;
1745 }
1746
1747 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1748                                            const bool isEditOperation,
1749                                            const bool isToDisplay,
1750                                            const bool isFlushRedisplay)
1751 {
1752   #ifdef DEBUG_DO_NOT_BY_ENTER
1753   return;
1754   #endif
1755
1756   if (isEditOperation || !theFeature.get())
1757     return;
1758
1759   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1760   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1761
1762   // 1. change visibility of the object itself, here the presentable object is processed,
1763   // e.g. constraints features
1764   //FeaturePtr aFeature = aFOperation->feature();
1765   std::list<ResultPtr> aResults = theFeature->results();
1766   if (isToDisplay)
1767     theFeature->setDisplayed(true);
1768   else
1769     theFeature->setDisplayed(false);
1770
1771   // change visibility of the object results, e.g. non-constraint features
1772   std::list<ResultPtr>::const_iterator aIt;
1773   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1774     if (isToDisplay) {
1775       (*aIt)->setDisplayed(true);
1776     }
1777     else {
1778       (*aIt)->setDisplayed(false);
1779     }
1780   }
1781   if (isFlushRedisplay)
1782     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1783 }
1784
1785 void PartSet_SketcherMgr::storeSelection(const SelectionType theType,
1786                         PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
1787 {
1788   if (!myCurrentSketch.get())
1789     return;
1790
1791   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1792   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1793   QList<ModuleBase_ViewerPrsPtr> aStoredPrs;
1794
1795   if (theType == ST_HighlightType || theType == ST_SelectAndHighlightType)
1796     aStoredPrs = aSelect->getHighlighted();
1797
1798   QList<FeaturePtr> aFeatureList;
1799   if (theType == ST_SelectAndHighlightType || theType == ST_SelectType) {
1800     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(
1801                                                               ModuleBase_ISelection::AllControls);
1802     aStoredPrs.append(aSelected);
1803   }
1804
1805   // 1. it is necessary to save current selection in order to restore it after the features moving
1806   theCurrentSelection.clear();
1807
1808   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = aStoredPrs.begin(),
1809                                                 aLast = aStoredPrs.end();
1810
1811   CompositeFeaturePtr aSketch = activeSketch();
1812   for (; anIt != aLast; anIt++) {
1813     ModuleBase_ViewerPrsPtr aPrs = *anIt;
1814     ObjectPtr anObject = aPrs->object();
1815     if (!anObject.get())
1816       continue;
1817
1818     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1819     FeaturePtr aFeature;
1820     if (aResult.get())
1821       aFeature = ModelAPI_Feature::feature(aResult);
1822     else
1823       aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1824
1825     if (!aFeature.get())
1826       continue;
1827
1828     std::set<AttributePtr> aSelectedAttributes;
1829     std::set<ResultPtr> aSelectedResults;
1830     SelectionInfo anInfo;
1831     if (theCurrentSelection.find(aFeature) != theCurrentSelection.end())
1832       anInfo = theCurrentSelection.find(aFeature).value();
1833
1834     TopoDS_Shape aFirstShape;
1835     ResultPtr aFirstResult = aFeature->firstResult();
1836     if (aFirstResult.get() && aFirstResult->shape().get())
1837       aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
1838     anInfo.myFirstResultShape = aFirstShape;
1839     Handle(SelectMgr_EntityOwner) anOwner = aPrs->owner();
1840     if (aResult.get()) {
1841       getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1842           anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
1843     }
1844     else {
1845       std::list<ResultPtr> aResults = aFeature->results();
1846       std::list<ResultPtr>::const_iterator aIt;
1847       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1848         ResultPtr aResult = *aIt;
1849         getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1850           anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
1851       }
1852     }
1853     theCurrentSelection[aFeature] = anInfo;
1854   }
1855   //qDebug(QString("  storeSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
1856 }
1857
1858 void PartSet_SketcherMgr::restoreSelection(
1859                                 PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
1860 {
1861   if (!myCurrentSketch.get())
1862     return;
1863
1864   //qDebug(QString("restoreSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
1865   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1866   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1867   FeatureToSelectionMap::const_iterator aSIt = theCurrentSelection.begin(),
1868                                         aSLast = theCurrentSelection.end();
1869   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1870   anOwnersToSelect.Clear();
1871   for (; aSIt != aSLast; aSIt++) {
1872     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, theCurrentSelection,
1873                        anOwnersToSelect);
1874   }
1875   aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1876 }
1877
1878 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
1879 {
1880   PartSet_Tools::ConstraintVisibleState aType = (PartSet_Tools::ConstraintVisibleState)theType;
1881
1882   updateBySketchParameters(aType, theState);
1883 }
1884
1885 void PartSet_SketcherMgr::updateBySketchParameters(
1886                                    const PartSet_Tools::ConstraintVisibleState& theType,
1887                                    bool theState)
1888 {
1889   if (myCurrentSketch.get() == NULL)
1890     return;
1891
1892   bool aPrevState = myIsConstraintsShown[theType];
1893   myIsConstraintsShown[theType] = theState;
1894
1895   switch (theType) {
1896     case PartSet_Tools::Geometrical:
1897     case PartSet_Tools::Dimensional: {
1898       if (aPrevState != theState) {
1899         ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1900         XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1901         for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1902           FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1903           bool aProcessed = false;
1904           bool aConstraintDisplayed = canDisplayConstraint(aSubFeature, theType, aProcessed);
1905           if (aProcessed)
1906             aSubFeature->setDisplayed(aConstraintDisplayed);
1907         }
1908         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1909       }
1910     }
1911     break;
1912     case PartSet_Tools::Expressions: {
1913       if (aPrevState != theState) {
1914         /// call all sketch features redisplay, the expression state will be corrected in customize
1915         /// of distance presentation
1916         Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1917         PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
1918       }
1919     }
1920     break;
1921   }
1922 }
1923
1924 void PartSet_SketcherMgr::updateSelectionPriority(ObjectPtr theObject,
1925                                                   FeaturePtr theFeature)
1926 {
1927   if (!theObject.get() || !theFeature.get())
1928     return;
1929
1930   AISObjectPtr anAIS = workshop()->displayer()->getAISObject(theObject);
1931   Handle(AIS_InteractiveObject) anAISIO;
1932   if (anAIS.get() != NULL) {
1933     anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1934   }
1935
1936   if (!anAISIO.IsNull()) { // the presentation for the object is visualized
1937     int anAdditionalPriority = 0;
1938     // current feature
1939     std::shared_ptr<SketchPlugin_Feature> aSPFeature =
1940             std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
1941     if (aSPFeature.get() != NULL) {
1942       // 1. Vertices
1943       // 2. Simple segments
1944       // 3. External objects (violet color)
1945       // 4. Auxiliary segments (dotted)
1946       // StdSelect_BRepSelectionTool::Load uses priority calculating:
1947       // Standard_Integer aPriority =
1948       // (thePriority == -1) ? GetStandardPriority (theShape, theType) : thePriority;
1949       // Priority of Vertex is 8, edge(segment) is 7.
1950       // It might be not corrected as provides the condition above.
1951       bool isExternal = aSPFeature->isExternal();
1952       bool isAuxiliary = PartSet_Tools::isAuxiliarySketchEntity(aSPFeature);
1953       // current feature
1954       if (!isExternal && !isAuxiliary)
1955         anAdditionalPriority = 30;
1956       // external feature
1957       if (isExternal)
1958         anAdditionalPriority = 20;
1959       // auxiliary feature
1960       if (isAuxiliary) {
1961         anAdditionalPriority = 10; /// auxiliary objects should have less priority that
1962         // edges/vertices of local selection on not-sketch objects
1963       }
1964       Handle(ModuleBase_ResultPrs) aResult = Handle(ModuleBase_ResultPrs)::DownCast(anAISIO);
1965       if (!aResult.IsNull()) {
1966         aResult->setAdditionalSelectionPriority(anAdditionalPriority);
1967       }
1968     }
1969   }
1970 }
1971
1972 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
1973 {
1974   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1975   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1976   return aConnector->workshop();
1977 }
1978
1979 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1980 {
1981   return workshop()->operationMgr();
1982 }
1983