Salome HOME
657d140755222f37198db290330151bc396f7a8f
[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 void PartSet_SketcherMgr::activatePlaneFilter(const bool& toActivate)
1168 {
1169   if (toActivate)
1170     myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
1171   else
1172     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
1173 }
1174
1175 bool PartSet_SketcherMgr::operationActivatedByPreselection()
1176 {
1177   bool isOperationStopped = false;
1178   ModuleBase_Operation* anOperation = getCurrentOperation();
1179   if(anOperation && isNestedSketchOperation(anOperation)) {
1180     // Set final definitions if they are necessary
1181     //propertyPanelDefined(aOperation);
1182     /// Commit sketcher operations automatically
1183     /// distance operation are able to show popup editor to modify the distance value
1184     /// after entering the value, the operation should be committed/aborted(by Esc key)
1185     bool aCanCommitOperation = true;
1186     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1187                                                                             (anOperation);
1188     if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation)) {
1189       bool aValueAccepted = setDistanceValueByPreselection(anOperation, myModule->workshop(),
1190                                                            aCanCommitOperation);
1191       if (!aValueAccepted)
1192         return isOperationStopped;
1193     }
1194
1195     if (aCanCommitOperation)
1196       isOperationStopped = anOperation->commit();
1197     else {
1198       anOperation->abort();
1199       isOperationStopped = true;
1200     }
1201   }
1202   return isOperationStopped;
1203 }
1204
1205 bool PartSet_SketcherMgr::canUndo() const
1206 {
1207   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1208 }
1209
1210 bool PartSet_SketcherMgr::canRedo() const
1211 {
1212   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1213 }
1214
1215 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1216 {
1217   bool aCanErase = true;
1218   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1219   if (myCurrentSketch.get()) {
1220     return !isObjectOfSketch(theObject);
1221   }
1222   return aCanErase;
1223 }
1224
1225 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1226 {
1227   bool aCanDisplay = true;
1228
1229   bool aHasActiveSketch = activeSketch().get() != NULL;
1230   if (aHasActiveSketch) {
1231     // 1. the sketch feature should not be displayed during the sketch active operation
1232     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch
1233     // nested features can be visualized
1234     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1235     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1236       aCanDisplay = false;
1237     }
1238     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1239                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1240     /// some sketch entities should be never shown, e.g. projection feature
1241     if (aSketchFeature.get())
1242       aCanDisplay = aSketchFeature->canBeDisplayed();
1243   }
1244   else { // there are no an active sketch
1245     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1246     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1247     if (aFeature.get() != NULL) {
1248       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1249                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1250       if (aSketchFeature.get()) {
1251         aCanDisplay = false;
1252       }
1253     }
1254   }
1255
1256   // 3. the method should not filter the objects, which are not related to the current operation.
1257   // The object is filtered just if it is a current operation feature or this feature result
1258   if (aCanDisplay) {
1259     bool isObjectFound = false;
1260     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1261                                                                  (getCurrentOperation());
1262     if (aFOperation) {
1263       FeaturePtr aFeature = aFOperation->feature();
1264       if (aFeature.get()) {
1265         std::list<ResultPtr> aResults = aFeature->results();
1266         if (theObject == aFeature)
1267           isObjectFound = true;
1268         else {
1269           std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1270           for (; anIt != aLast && !isObjectFound; anIt++) {
1271             isObjectFound = *anIt == theObject;
1272           }
1273         }
1274       }
1275     }
1276     if (isObjectFound) {
1277       // 4. For created nested feature operation do not display the created feature if
1278       // the mouse curstor leaves the OCC window.
1279       // The correction cases, which ignores this condition:
1280       // a. the property panel values modification
1281       // b. the popup menu activated
1282       // c. widget editor control
1283       #ifndef DEBUG_DO_NOT_BY_ENTER
1284       if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
1285         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1286         ModuleBase_WidgetEditor* anEditorWdg =
1287           anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1288         // the active widget editor should not influence here. The presentation should be visible
1289         // always when this widget is active.
1290         if (!anEditorWdg && !myIsPopupMenuActive) {
1291           // during a nested create operation, the feature is redisplayed only
1292           // if the mouse over view
1293           // of there was a value modified in the property panel after the mouse left the view
1294           aCanDisplay = canDisplayCurrentCreatedFeature();
1295         }
1296       }
1297       #endif
1298     }
1299   }
1300
1301   // checks the sketcher constraints visibility according to active sketch check box states
1302   if (aCanDisplay) {
1303     bool aProcessed = false;
1304     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1305     if (aFeature.get()) {
1306       bool aConstraintDisplayed = canDisplayConstraint(aFeature, PartSet_Tools::Any, aProcessed);
1307       if (aProcessed)
1308         aCanDisplay = aConstraintDisplayed;
1309     }
1310   }
1311
1312   return aCanDisplay;
1313 }
1314
1315 bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
1316                                              const PartSet_Tools::ConstraintVisibleState& theState,
1317                                              bool& isProcessed) const
1318 {
1319   bool aSwitchedOn = true;
1320
1321   const QStringList& aConstrIds = constraintsIdList();
1322
1323   std::string aKind = theFeature->getKind();
1324   if (aConstrIds.contains(QString(aKind.c_str()))) {
1325     bool isTypedConstraint = false;
1326
1327     switch (theState) {
1328       case PartSet_Tools::Dimensional: {
1329         bool isDistance = isDistanceKind(aKind);
1330         if (isDistance) {
1331           isProcessed = true;
1332           aSwitchedOn = myIsConstraintsShown[theState];
1333         }
1334       }
1335       break;
1336       case PartSet_Tools::Geometrical: {
1337         bool isGeometrical = !isDistanceKind(aKind);
1338         if (isGeometrical) {
1339           isProcessed = true;
1340           aSwitchedOn = myIsConstraintsShown[theState];
1341         }
1342       }
1343       break;
1344       case PartSet_Tools::Any: {
1345         isProcessed = true;
1346         bool isDistance = isDistanceKind(aKind);
1347         if (isDistance)
1348           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Dimensional];
1349         else
1350           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Geometrical];
1351       }
1352       break;
1353     default:
1354       break;
1355     }
1356   }
1357   return aSwitchedOn;
1358 }
1359
1360 /*void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
1361 {
1362   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1363                                                                            (getCurrentOperation());
1364   if (aFOperation && myCurrentSketch.get()) {
1365     // find results of the current operation
1366     // these results should not be proposed to be deleted
1367     FeaturePtr anOperationFeature = aFOperation->feature();
1368     std::list<ResultPtr> anOperationResultList = anOperationFeature->results();
1369     std::set<ResultPtr> anOperationResults;
1370     std::list<ResultPtr>::const_iterator aRIt = anOperationResultList.begin(),
1371                                         aRLast = anOperationResultList.end();
1372     for (; aRIt != aRLast; aRIt++)
1373       anOperationResults.insert(*aRIt);
1374
1375     std::set<FeaturePtr> anObjectsToBeDeleted;
1376     QStringList anObjectsToBeDeletedNames;
1377     std::list<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1378     for (; anIt != aLast; anIt++) {
1379       ObjectPtr anObject = *anIt;
1380       bool aCanErase = true;
1381       // when the sketch operation is active, results of sketch sub-feature can not be hidden
1382       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1383       // the result is found between current feature results
1384       if (anOperationResults.find(aResult) != anOperationResults.end())
1385         continue;
1386
1387       if (aResult.get()) {
1388         // Display sketcher objects
1389         for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1390           FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1391           std::list<ResultPtr> aResults = aFeature->results();
1392           std::list<ResultPtr>::const_iterator anIt;
1393           for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1394             aCanErase = *anIt != aResult;
1395           }
1396         }
1397       }
1398       if (!aCanErase) {
1399         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
1400         if (aFeature.get() && anObjectsToBeDeleted.find(aFeature) == anObjectsToBeDeleted.end()) {
1401           anObjectsToBeDeleted.insert(aFeature);
1402           anObjectsToBeDeletedNames.append(aFeature->name().c_str());
1403         }
1404       }
1405     }
1406     if (!anObjectsToBeDeleted.empty()) {
1407       QString aFeatureNames = anObjectsToBeDeletedNames.join(", ");
1408       QString aMessage = tr("The following features have incorrect presentation and \
1409 will be hidden: %1. Would you like to delete them?")
1410                          .arg(aFeatureNames);
1411       int anAnswer = QMessageBox::question(qApp->activeWindow(), tr("Features hide"),
1412                                            aMessage, QMessageBox::Ok | QMessageBox::Cancel,
1413                                            QMessageBox::Cancel);
1414       if (anAnswer == QMessageBox::Ok) {
1415         QObjectPtrList anObjects;
1416         std::set<FeaturePtr>::const_iterator anIt = anObjectsToBeDeleted.begin(),
1417                                              aLast = anObjectsToBeDeleted.end();
1418         for (; anIt != aLast; anIt++)
1419           anObjects.append(*anIt);
1420         SessionPtr aMgr = ModelAPI_Session::get();
1421         DocumentPtr aDoc = aMgr->activeDocument();
1422         bool aIsOp = aMgr->isOperation();
1423         if (!aIsOp)
1424           aMgr->startOperation();
1425         workshop()->deleteFeatures(anObjects);
1426         //static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
1427         //static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
1428         //Events_Loop::loop()->flush(aDeletedEvent);
1429         //Events_Loop::loop()->flush(aRedispEvent);
1430
1431         if (!aIsOp)
1432           aMgr->finishOperation();
1433       }
1434     }
1435   }
1436 }*/
1437
1438 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1439 {
1440   bool aCanDisplay = myIsMouseOverWindow;
1441   if (!aCanDisplay) {
1442     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1443     if (anActiveWidget)
1444       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1445   }
1446   return aCanDisplay;
1447 }
1448
1449 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1450 {
1451   return isNestedCreateOperation(theOperation, activeSketch()) ||
1452          myModule->sketchReentranceMgr()->isInternalEditActive();
1453 }
1454
1455 const QMap<PartSet_Tools::ConstraintVisibleState, bool>& PartSet_SketcherMgr::showConstraintStates()
1456 {
1457   return myIsConstraintsShown;
1458 }
1459
1460 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1461 {
1462   bool isFoundObject = false;
1463
1464   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1465   if (anObjectFeature.get()) {
1466     int aSize = myCurrentSketch->numberOfSubs();
1467     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1468       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1469       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1470     }
1471   }
1472   return isFoundObject;
1473 }
1474
1475 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
1476 {
1477   myPlaneFilter->setPlane(thePln);
1478   workshop()->selectionActivate()->updateSelectionModes();
1479 }
1480
1481 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
1482                                                          ModuleBase_IWorkshop* theWorkshop,
1483                                                          bool& theCanCommitOperation)
1484 {
1485   bool isValueAccepted = false;
1486   theCanCommitOperation = false;
1487
1488   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1489                                                                               (theOperation);
1490   FeaturePtr aFeature = aFOperation->feature();
1491   // editor is shown only if all attribute references are filled by preseletion
1492   bool anAllRefAttrInitialized = true;
1493
1494   std::list<AttributePtr> aRefAttrs = aFeature->data()->attributes(
1495                                               ModelAPI_AttributeRefAttr::typeId());
1496   std::list<AttributePtr>::const_iterator anIt = aRefAttrs.begin(), aLast = aRefAttrs.end();
1497   for (; anIt != aLast && anAllRefAttrInitialized; anIt++) {
1498     anAllRefAttrInitialized = (*anIt)->isInitialized();
1499   }
1500   if (anAllRefAttrInitialized) {
1501     // Activate dimension value editing on double click
1502     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
1503     QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
1504     // Find corresponded widget to activate value editing
1505     foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
1506       if (aWgt->attributeID() == "ConstraintValue") {
1507         // the featue should be displayed in order to find the AIS text position,
1508         // the place where the editor will be shown
1509         aFeature->setDisplayed(true);
1510         /// the execute is necessary to perform in the feature compute for flyout position
1511         aFeature->execute();
1512
1513         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1514         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1515
1516         PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
1517         if (anEditor) {
1518           int aX = 0, anY = 0;
1519
1520           XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(theWorkshop);
1521           XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1522           AISObjectPtr anAIS = aDisplayer->getAISObject(aFeature);
1523           Handle(AIS_InteractiveObject) anAISIO;
1524           if (anAIS.get() != NULL) {
1525             anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1526           }
1527           if (anAIS.get() != NULL) {
1528             Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1529
1530             if (!anAISIO.IsNull()) {
1531               Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAISIO);
1532               if (!aDim.IsNull()) {
1533                 gp_Pnt aPosition = aDim->GetTextPosition();
1534
1535                 ModuleBase_IViewer* aViewer = aWorkshop->viewer();
1536                 Handle(V3d_View) aView = aViewer->activeView();
1537                 int aCX, aCY;
1538                 aView->Convert(aPosition.X(), aPosition.Y(), aPosition.Z(), aCX, aCY);
1539
1540                 QWidget* aViewPort = aViewer->activeViewPort();
1541                 QPoint aGlPoint = aViewPort->mapToGlobal(QPoint(aCX, aCY));
1542                 aX = aGlPoint.x();
1543                 anY = aGlPoint.y();
1544               }
1545             }
1546             anEditor->setCursorPosition(aX, anY);
1547             isValueAccepted = anEditor->showPopupEditor(false);
1548             theCanCommitOperation = true;
1549           }
1550         }
1551       }
1552     }
1553   }
1554   return isValueAccepted;
1555 }
1556
1557 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1558                                              const FeaturePtr& theSketch,
1559                                              ModuleBase_IWorkshop* theWorkshop,
1560                                              const FeatureToSelectionMap& theSelection,
1561                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1562 {
1563   if (theFeature.get() == NULL)
1564     return;
1565
1566   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1567   SelectionInfo anInfo = anIt.value();
1568   std::set<AttributePtr> aSelectedAttributes = anInfo.myAttributes;
1569   std::set<ResultPtr> aSelectedResults = anInfo.myResults;
1570
1571   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1572
1573   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1574   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1575
1576   // 1. found the feature's owners. Check the AIS objects of the constructions
1577   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1578   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1579     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1580
1581     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1582     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1583     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1584       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1585       if (!anOwner.IsNull())
1586         theOwnersToSelect.Add(anOwner);
1587     }
1588   }
1589
1590   // 2. found the feature results's owners
1591   std::list<ResultPtr> aResults = theFeature->results();
1592   std::list<ResultPtr>::const_iterator aIt;
1593
1594   bool isSameShape = false;
1595   if (aResults.size() > 0) {
1596     ResultPtr aFirstResult = theFeature->firstResult();
1597     if (aFirstResult.get() && aFirstResult->shape().get()) {
1598       TopoDS_Shape aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
1599       isSameShape = aFirstShape.IsEqual(anInfo.myFirstResultShape);
1600     }
1601   }
1602   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1603     ResultPtr aResult = *aIt;
1604     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1605     if (aAISObj.get() == NULL)
1606       continue;
1607     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1608
1609     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1610     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1611     bool aFoundLocalShape = false;
1612     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1613       Handle(StdSelect_BRepOwner) anOwner =
1614         Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1615       if ( anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
1616         continue;
1617       const TopoDS_Shape& aShape = anOwner->Shape();
1618       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1619       if (aShapeType == TopAbs_VERTEX) {
1620         AttributePtr aPntAttr =
1621           PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1622         if (aPntAttr.get() != NULL &&
1623             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end())
1624           theOwnersToSelect.Add(anOwner);
1625         else if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
1626           theOwnersToSelect.Add(anOwner);
1627         }
1628       }
1629       else if (aShapeType == TopAbs_EDGE) {
1630         if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
1631           // try to restore local selection on Shape result
1632           // we can do this only if the shape was not changed
1633           theOwnersToSelect.Add(anOwner);
1634           aFoundLocalShape = true;
1635           break;
1636         }
1637       }
1638     }
1639     if (!aFoundLocalShape) {
1640       // result owners are put in the list of selection only if local selected shapes were not
1641       // found
1642       if (aSelectedResults.find(aResult) != aSelectedResults.end()) {
1643         for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1644           Handle(StdSelect_BRepOwner) anOwner =
1645             Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1646           if ( anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
1647             continue;
1648             // select whole result
1649             theOwnersToSelect.Add(anOwner);
1650         }
1651       }
1652     }
1653   }
1654 }
1655
1656 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
1657                                                  const bool isToConnect)
1658 {
1659   //Temporary commented as we do not modify values in property panel
1660   if (isToConnect) {
1661     //connect(theWidget, SIGNAL(beforeValuesChanged()),
1662     //        this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1663     //connect(theWidget, SIGNAL(afterValuesChanged()),
1664     //        this, SLOT(onAfterValuesChangedInPropertyPanel()));
1665     connect(theWidget, SIGNAL(afterValuesChanged()),
1666             myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
1667   }
1668   else {
1669     //disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1670     //            this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1671     //disconnect(theWidget, SIGNAL(afterValuesChanged()),
1672     //            this, SLOT(onAfterValuesChangedInPropertyPanel()));
1673     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1674                myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
1675   }
1676 }
1677
1678 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1679 {
1680   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1681                                                                            (getCurrentOperation());
1682   if (aFOperation) {
1683     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1684         isNestedSketchOperation(aFOperation) &&
1685         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1686       FeaturePtr aFeature = aFOperation->feature();
1687       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1688     }
1689   }
1690 }
1691
1692 void PartSet_SketcherMgr::customizePresentation(const ObjectPtr& theObject)
1693 {
1694   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1695                                                                            (getCurrentOperation());
1696   if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1697                       isNestedSketchOperation(aFOperation)))
1698     SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
1699
1700   // update entities selection priorities
1701   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1702   if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1703     // update priority for feature
1704     updateSelectionPriority(aFeature, aFeature);
1705     // update priority for results of the feature
1706     std::list<ResultPtr> aResults = aFeature->results();
1707     std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLastIt = aResults.end();
1708     for (; anIt != aLastIt; anIt++)
1709       updateSelectionPriority(*anIt, aFeature);
1710   }
1711 }
1712
1713 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1714 {
1715   return myModule->workshop()->currentOperation();
1716 }
1717
1718 //**************************************************************
1719 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1720 {
1721   ModuleBase_ModelWidget* aWidget = 0;
1722   ModuleBase_Operation* anOperation = getCurrentOperation();
1723   if (anOperation) {
1724     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1725     if (aPanel)
1726       aWidget = aPanel->activeWidget();
1727   }
1728   return aWidget;
1729 }
1730
1731 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1732                                            const bool isEditOperation,
1733                                            const bool isToDisplay,
1734                                            const bool isFlushRedisplay)
1735 {
1736   #ifdef DEBUG_DO_NOT_BY_ENTER
1737   return;
1738   #endif
1739
1740   if (isEditOperation || !theFeature.get())
1741     return;
1742
1743   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1744   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1745
1746   // 1. change visibility of the object itself, here the presentable object is processed,
1747   // e.g. constraints features
1748   //FeaturePtr aFeature = aFOperation->feature();
1749   std::list<ResultPtr> aResults = theFeature->results();
1750   if (isToDisplay)
1751     theFeature->setDisplayed(true);
1752   else
1753     theFeature->setDisplayed(false);
1754
1755   // change visibility of the object results, e.g. non-constraint features
1756   std::list<ResultPtr>::const_iterator aIt;
1757   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1758     if (isToDisplay) {
1759       (*aIt)->setDisplayed(true);
1760     }
1761     else {
1762       (*aIt)->setDisplayed(false);
1763     }
1764   }
1765   if (isFlushRedisplay)
1766     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1767 }
1768
1769 void PartSet_SketcherMgr::storeSelection(const SelectionType theType,
1770                         PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
1771 {
1772   if (!myCurrentSketch.get())
1773     return;
1774
1775   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1776   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1777   QList<ModuleBase_ViewerPrsPtr> aStoredPrs;
1778
1779   if (theType == ST_HighlightType || theType == ST_SelectAndHighlightType)
1780     aStoredPrs = aSelect->getHighlighted();
1781
1782   QList<FeaturePtr> aFeatureList;
1783   if (theType == ST_SelectAndHighlightType || theType == ST_SelectType) {
1784     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(
1785                                                               ModuleBase_ISelection::AllControls);
1786     aStoredPrs.append(aSelected);
1787   }
1788
1789   // 1. it is necessary to save current selection in order to restore it after the features moving
1790   theCurrentSelection.clear();
1791
1792   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = aStoredPrs.begin(),
1793                                                 aLast = aStoredPrs.end();
1794
1795   CompositeFeaturePtr aSketch = activeSketch();
1796   for (; anIt != aLast; anIt++) {
1797     ModuleBase_ViewerPrsPtr aPrs = *anIt;
1798     ObjectPtr anObject = aPrs->object();
1799     if (!anObject.get())
1800       continue;
1801
1802     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1803     FeaturePtr aFeature;
1804     if (aResult.get())
1805       aFeature = ModelAPI_Feature::feature(aResult);
1806     else
1807       aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1808
1809     if (!aFeature.get())
1810       continue;
1811
1812     std::set<AttributePtr> aSelectedAttributes;
1813     std::set<ResultPtr> aSelectedResults;
1814     SelectionInfo anInfo;
1815     if (theCurrentSelection.find(aFeature) != theCurrentSelection.end())
1816       anInfo = theCurrentSelection.find(aFeature).value();
1817
1818     TopoDS_Shape aFirstShape;
1819     ResultPtr aFirstResult = aFeature->firstResult();
1820     if (aFirstResult.get() && aFirstResult->shape().get())
1821       aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
1822     anInfo.myFirstResultShape = aFirstShape;
1823     Handle(SelectMgr_EntityOwner) anOwner = aPrs->owner();
1824     if (aResult.get()) {
1825       getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1826           anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
1827     }
1828     else {
1829       std::list<ResultPtr> aResults = aFeature->results();
1830       std::list<ResultPtr>::const_iterator aIt;
1831       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1832         ResultPtr aResult = *aIt;
1833         getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1834           anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
1835       }
1836     }
1837     theCurrentSelection[aFeature] = anInfo;
1838   }
1839   //qDebug(QString("  storeSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
1840 }
1841
1842 void PartSet_SketcherMgr::restoreSelection(
1843                                 PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
1844 {
1845   if (!myCurrentSketch.get())
1846     return;
1847
1848   //qDebug(QString("restoreSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
1849   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1850   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1851   FeatureToSelectionMap::const_iterator aSIt = theCurrentSelection.begin(),
1852                                         aSLast = theCurrentSelection.end();
1853   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1854   anOwnersToSelect.Clear();
1855   for (; aSIt != aSLast; aSIt++) {
1856     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, theCurrentSelection,
1857                        anOwnersToSelect);
1858   }
1859   aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1860 }
1861
1862 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
1863 {
1864   PartSet_Tools::ConstraintVisibleState aType = (PartSet_Tools::ConstraintVisibleState)theType;
1865
1866   updateBySketchParameters(aType, theState);
1867 }
1868
1869 void PartSet_SketcherMgr::updateBySketchParameters(
1870                                    const PartSet_Tools::ConstraintVisibleState& theType,
1871                                    bool theState)
1872 {
1873   if (myCurrentSketch.get() == NULL)
1874     return;
1875
1876   bool aPrevState = myIsConstraintsShown[theType];
1877   myIsConstraintsShown[theType] = theState;
1878
1879   switch (theType) {
1880     case PartSet_Tools::Geometrical:
1881     case PartSet_Tools::Dimensional: {
1882       if (aPrevState != theState) {
1883         ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1884         XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1885         for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1886           FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1887           bool aProcessed = false;
1888           bool aConstraintDisplayed = canDisplayConstraint(aSubFeature, theType, aProcessed);
1889           if (aProcessed)
1890             aSubFeature->setDisplayed(aConstraintDisplayed);
1891         }
1892         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1893       }
1894     }
1895     break;
1896     case PartSet_Tools::Expressions: {
1897       if (aPrevState != theState) {
1898         /// call all sketch features redisplay, the expression state will be corrected in customize
1899         /// of distance presentation
1900         Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1901         PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
1902       }
1903     }
1904     break;
1905   }
1906 }
1907
1908 void PartSet_SketcherMgr::updateSelectionPriority(ObjectPtr theObject,
1909                                                   FeaturePtr theFeature)
1910 {
1911   if (!theObject.get() || !theFeature.get())
1912     return;
1913
1914   AISObjectPtr anAIS = workshop()->displayer()->getAISObject(theObject);
1915   Handle(AIS_InteractiveObject) anAISIO;
1916   if (anAIS.get() != NULL) {
1917     anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1918   }
1919
1920   if (!anAISIO.IsNull()) { // the presentation for the object is visualized
1921     int anAdditionalPriority = 0;
1922     // current feature
1923     std::shared_ptr<SketchPlugin_Feature> aSPFeature =
1924             std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
1925     if (aSPFeature.get() != NULL) {
1926       // 1. Vertices
1927       // 2. Simple segments
1928       // 3. External objects (violet color)
1929       // 4. Auxiliary segments (dotted)
1930       // StdSelect_BRepSelectionTool::Load uses priority calculating:
1931       // Standard_Integer aPriority =
1932       // (thePriority == -1) ? GetStandardPriority (theShape, theType) : thePriority;
1933       // Priority of Vertex is 8, edge(segment) is 7.
1934       // It might be not corrected as provides the condition above.
1935       bool isExternal = aSPFeature->isExternal();
1936       bool isAuxiliary = PartSet_Tools::isAuxiliarySketchEntity(aSPFeature);
1937       // current feature
1938       if (!isExternal && !isAuxiliary)
1939         anAdditionalPriority = 30;
1940       // external feature
1941       if (isExternal)
1942         anAdditionalPriority = 20;
1943       // auxiliary feature
1944       if (isAuxiliary) {
1945         anAdditionalPriority = 10; /// auxiliary objects should have less priority that
1946         // edges/vertices of local selection on not-sketch objects
1947       }
1948       Handle(ModuleBase_ResultPrs) aResult = Handle(ModuleBase_ResultPrs)::DownCast(anAISIO);
1949       if (!aResult.IsNull()) {
1950         aResult->setAdditionalSelectionPriority(anAdditionalPriority);
1951       }
1952     }
1953   }
1954 }
1955
1956 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
1957 {
1958   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1959   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1960   return aConnector->workshop();
1961 }
1962
1963 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1964 {
1965   return workshop()->operationMgr();
1966 }
1967