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