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