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