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