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