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