Salome HOME
6128e4038f9ae45e55609ff4b37134cc7eed8d3b
[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::isDistanceOperation(ModuleBase_Operation* theOperation)
842 {
843   std::string anId = theOperation ? theOperation->id().toStdString() : "";
844
845   return isDistanceKind(anId);
846 }
847
848 bool PartSet_SketcherMgr::isDistanceKind(std::string& theKind)
849 {
850   return (theKind == SketchPlugin_ConstraintLength::ID()) ||
851          (theKind == SketchPlugin_ConstraintDistance::ID()) ||
852          (theKind == SketchPlugin_ConstraintRadius::ID()) ||
853          (theKind == SketchPlugin_ConstraintAngle::ID());
854 }
855
856 void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
857 {
858   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
859                                                                (getCurrentOperation());
860   if (!aFOperation)
861     return;
862
863   myModule->onViewTransformed();
864
865   // Display all sketcher sub-Objects
866   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFOperation->feature());
867   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
868
869   // Hide sketcher result
870   std::list<ResultPtr> aResults = myCurrentSketch->results();
871   std::list<ResultPtr>::const_iterator aIt;
872   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
873     (*aIt)->setDisplayed(false);
874   }
875   myCurrentSketch->setDisplayed(false);
876
877   // Remove invalid sketch entities
878   std::set<FeaturePtr> anInvalidFeatures;
879   ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
880   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
881     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
882     if (aFeature.get()) {
883       if (!aFactory->validate(aFeature))
884         anInvalidFeatures.insert(aFeature);
885     }
886   }
887   if (!anInvalidFeatures.empty()) {
888     std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
889     ModelAPI_Tools::findAllReferences(anInvalidFeatures, aReferences, false);
890
891     std::set<FeaturePtr>::const_iterator anIt = anInvalidFeatures.begin(),
892                                          aLast = anInvalidFeatures.end();
893     // separate features to references to parameter features and references to others
894     QStringList anInvalidFeatureNames;
895     for (; anIt != aLast; anIt++) {
896       FeaturePtr aFeature = *anIt;
897       if (aFeature.get())
898         anInvalidFeatureNames.append(aFeature->name().c_str());
899     }
900     std::string aPrefixInfo = QString("Invalid features of the sketch will be deleted: %1.\n\n").
901                                   arg(anInvalidFeatureNames.join(", ")).toStdString().c_str();
902     std::set<FeaturePtr> aFeatureRefsToDelete;
903     if (ModuleBase_Tools::askToDelete(anInvalidFeatures, aReferences, aConnector->desktop(),
904                                       aFeatureRefsToDelete, aPrefixInfo)) {
905       if (!aFeatureRefsToDelete.empty())
906         anInvalidFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
907       ModelAPI_Tools::removeFeatures(anInvalidFeatures, true);
908       Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
909       // TODO: call the next method in the XGUI_OperationMgr::onOperationStarted().
910       workshop()->errorMgr()->updateAcceptAllAction(myCurrentSketch);
911     }
912   }
913
914   // update state of overconstraint listener should be done before sketch features/results
915   // display (as the display will ask custom color from the listener)
916   myModule->overconstraintListener()->setActive(true);
917   // Display sketcher objects
918   QStringList anInfo;
919   Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
920   const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
921   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
922     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
923 #ifdef DEBUG_SKETCHER_ENTITIES
924     anInfo.append(ModuleBase_Tools::objectInfo(aFeature));
925 #endif
926     std::list<ResultPtr> aResults = aFeature->results();
927     std::list<ResultPtr>::const_iterator aIt;
928     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
929       if ((*aIt)->isDisplayed())
930         // Display object if it was created outside of GUI
931         aECreator->sendUpdated((*aIt), EVENT_DISP);
932       else
933         (*aIt)->setDisplayed(true);
934     }
935     if (aFeature->isDisplayed())
936       aECreator->sendUpdated(aFeature, EVENT_DISP);
937     else
938       aFeature->setDisplayed(true);
939   }
940 #ifdef DEBUG_SKETCHER_ENTITIES
941   QString anInfoStr = anInfo.join(";\t");
942   qDebug(QString("startSketch: %1, %2").arg(anInfo.size()).arg(anInfoStr).toStdString().c_str());
943 #endif
944
945   if(myCirclePointFilter.IsNull()) {
946     myCirclePointFilter = new PartSet_CirclePointFilter(myModule->workshop());
947   }
948
949   myModule->workshop()->viewer()->addSelectionFilter(myCirclePointFilter);
950
951   if (myPlaneFilter.IsNull())
952     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
953
954   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
955   bool aHasPlane = false;
956   std::shared_ptr<GeomAPI_Pln> aPln;
957   aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
958   myPlaneFilter->setPlane(aPln);
959
960   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
961   // all displayed objects should be activated in current selection modes according to switched
962   // plane filter
963   if (aPln.get())
964     aConnector->activateModuleSelectionModes();
965 }
966
967 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
968 {
969   myIsMouseOverWindow = false;
970   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
971   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
972   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
973
974   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
975
976   DataPtr aData = myCurrentSketch->data();
977   if (!aData->isValid()) {
978     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
979     // The sketch was aborted
980     myCurrentSketch = CompositeFeaturePtr();
981     // TODO: move this outside of if-else
982     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
983     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
984
985     // Erase all sketcher objects
986     QObjectPtrList aObjects = aDisplayer->displayedObjects();
987     foreach (ObjectPtr aObj, aObjects) {
988       DataPtr aObjData = aObj->data();
989       if (!aObjData->isValid())
990         aObj->setDisplayed(false);
991     }
992   }
993   else {
994     // Hide all sketcher sub-Objects
995     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
996       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
997       std::list<ResultPtr> aResults = aFeature->results();
998       std::list<ResultPtr>::const_iterator aIt;
999       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1000         (*aIt)->setDisplayed(false);
1001       }
1002       aFeature->setDisplayed(false);
1003     }
1004     // Display sketcher result
1005     std::list<ResultPtr> aResults = myCurrentSketch->results();
1006     std::list<ResultPtr>::const_iterator aIt;
1007     Events_Loop* aLoop = Events_Loop::loop();
1008     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1009
1010     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1011                                                                            (theOperation);
1012     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1013       if (!aFOperation->isDisplayedOnStart(*aIt)) {
1014         (*aIt)->setDisplayed(true);
1015         // this display event is needed because sketch already may have "displayed" state,
1016         // but not displayed while it is still active (issue 613, abort of existing sketch)
1017         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
1018       }
1019     }
1020     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
1021       myCurrentSketch->setDisplayed(true);
1022
1023     myCurrentSketch = CompositeFeaturePtr();
1024
1025     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
1026     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
1027
1028     Events_Loop::loop()->flush(aDispEvent);
1029   }
1030   myModule->overconstraintListener()->setActive(false);
1031   // restore the module selection modes, which were changed on startSketch
1032   aConnector->activateModuleSelectionModes();
1033 }
1034
1035 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
1036 {
1037   if (canChangeCursor(theOperation) && myIsMouseOverWindow) {
1038     QCursor* aCurrentCursor = QApplication::overrideCursor();
1039     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
1040       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
1041 #ifdef DEBUG_CURSOR
1042       qDebug("startNestedSketch() : Qt::CrossCursor");
1043 #endif
1044     }
1045   }
1046 }
1047
1048 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
1049 {
1050   myIsMouseOverViewProcessed = true;
1051   operationMgr()->onValidateOperation();
1052   // when sketch nested operation is stopped the cursor should be restored unconditionally
1053   //if (canChangeCursor(theOperation)) {
1054     QApplication::restoreOverrideCursor();
1055 #ifdef DEBUG_CURSOR
1056     qDebug("stopNestedSketch() : None");
1057 #endif
1058   //}
1059   /// improvement to deselect automatically all eventual selected objects, when
1060   // returning to the neutral point of the Sketcher
1061   bool isClearSelectionPossible = true;
1062   if (myIsEditLaunching) {
1063     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1064                                                                           (theOperation);
1065     if (aFOperation) {
1066       FeaturePtr aFeature = aFOperation->feature();
1067       if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1068         isClearSelectionPossible = false;
1069       }
1070     }
1071   }
1072   if (isClearSelectionPossible)
1073     workshop()->selector()->clearSelection();
1074 }
1075
1076 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
1077 {
1078   if (isNestedCreateOperation(theOperation, activeSketch())) {
1079     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1080                                                                              (theOperation);
1081     if (aFOperation) {
1082       FeaturePtr aFeature = aFOperation->feature();
1083       // it is necessary to check the the feature data validity because
1084       // some kind of features are removed by an operation commit(the macro state of a feature)
1085       if (aFeature.get() && aFeature->data()->isValid()) {
1086         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
1087       }
1088     }
1089   }
1090 }
1091
1092 void PartSet_SketcherMgr::activatePlaneFilter(const bool& toActivate)
1093 {
1094   if (toActivate)
1095     myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
1096   else
1097     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
1098 }
1099
1100 bool PartSet_SketcherMgr::operationActivatedByPreselection()
1101 {
1102   bool isOperationStopped = false;
1103   ModuleBase_Operation* anOperation = getCurrentOperation();
1104   if(anOperation && isNestedSketchOperation(anOperation)) {
1105     // Set final definitions if they are necessary
1106     //propertyPanelDefined(aOperation);
1107     /// Commit sketcher operations automatically
1108     /// distance operation are able to show popup editor to modify the distance value
1109     /// after entering the value, the operation should be committed/aborted(by Esc key)
1110     bool aCanCommitOperation = true;
1111     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1112                                                                             (anOperation);
1113     if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation)) {
1114       bool aValueAccepted = setDistanceValueByPreselection(anOperation, myModule->workshop(),
1115                                                            aCanCommitOperation);
1116       if (!aValueAccepted)
1117         return isOperationStopped;
1118     }
1119
1120     if (aCanCommitOperation)
1121       isOperationStopped = anOperation->commit();
1122     else {
1123       anOperation->abort();
1124       isOperationStopped = true;
1125     }
1126   }
1127   return isOperationStopped;
1128 }
1129
1130 bool PartSet_SketcherMgr::canUndo() const
1131 {
1132   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1133 }
1134
1135 bool PartSet_SketcherMgr::canRedo() const
1136 {
1137   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1138 }
1139
1140 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1141 {
1142   bool aCanErase = true;
1143   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1144   if (myCurrentSketch.get()) {
1145     return !isObjectOfSketch(theObject);
1146   }
1147   return aCanErase;
1148 }
1149
1150 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1151 {
1152   bool aCanDisplay = true;
1153
1154   bool aHasActiveSketch = activeSketch().get() != NULL;
1155   if (aHasActiveSketch) {
1156     // 1. the sketch feature should not be displayed during the sketch active operation
1157     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch
1158     // nested features can be visualized
1159     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1160     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1161       aCanDisplay = false;
1162     }
1163     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1164                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1165     /// some sketch entities should be never shown, e.g. projection feature
1166     if (aSketchFeature.get())
1167       aCanDisplay = aSketchFeature->canBeDisplayed();
1168   }
1169   else { // there are no an active sketch
1170     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1171     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1172     if (aFeature.get() != NULL) {
1173       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1174                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1175       if (aSketchFeature.get()) {
1176         aCanDisplay = false;
1177       }
1178     }
1179   }
1180
1181   // 3. the method should not filter the objects, which are not related to the current operation.
1182   // The object is filtered just if it is a current operation feature or this feature result
1183   if (aCanDisplay) {
1184     bool isObjectFound = false;
1185     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1186                                                                  (getCurrentOperation());
1187     if (aFOperation) {
1188       FeaturePtr aFeature = aFOperation->feature();
1189       if (aFeature.get()) {
1190         std::list<ResultPtr> aResults = aFeature->results();
1191         if (theObject == aFeature)
1192           isObjectFound = true;
1193         else {
1194           std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1195           for (; anIt != aLast && !isObjectFound; anIt++) {
1196             isObjectFound = *anIt == theObject;
1197           }
1198         }
1199       }
1200     }
1201     if (isObjectFound) {
1202       // 4. For created nested feature operation do not display the created feature if
1203       // the mouse curstor leaves the OCC window.
1204       // The correction cases, which ignores this condition:
1205       // a. the property panel values modification
1206       // b. the popup menu activated
1207       // c. widget editor control
1208       #ifndef DEBUG_DO_NOT_BY_ENTER
1209       if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
1210         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1211         ModuleBase_WidgetEditor* anEditorWdg =
1212           anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1213         // the active widget editor should not influence here. The presentation should be visible
1214         // always when this widget is active.
1215         if (!anEditorWdg && !myIsPopupMenuActive) {
1216           // during a nested create operation, the feature is redisplayed only
1217           // if the mouse over view
1218           // of there was a value modified in the property panel after the mouse left the view
1219           aCanDisplay = canDisplayCurrentCreatedFeature();
1220         }
1221       }
1222       #endif
1223     }
1224   }
1225
1226   // checks the sketcher constraints visibility according to active sketch check box states
1227   if (aCanDisplay) {
1228     bool aProcessed = false;
1229     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1230     if (aFeature.get()) {
1231       bool aConstraintDisplayed = canDisplayConstraint(aFeature, PartSet_Tools::Any, aProcessed);
1232       if (aProcessed)
1233         aCanDisplay = aConstraintDisplayed;
1234     }
1235   }
1236
1237   return aCanDisplay;
1238 }
1239
1240 bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
1241                                              const PartSet_Tools::ConstraintVisibleState& theState,
1242                                              bool& isProcessed) const
1243 {
1244   bool aSwitchedOn = true;
1245
1246   const QStringList& aConstrIds = constraintsIdList();
1247
1248   std::string aKind = theFeature->getKind();
1249   if (aConstrIds.contains(QString(aKind.c_str()))) {
1250     bool isTypedConstraint = false;
1251
1252     switch (theState) {
1253       case PartSet_Tools::Dimensional: {
1254         bool isDistance = isDistanceKind(aKind);
1255         if (isDistance) {
1256           isProcessed = true;
1257           aSwitchedOn = myIsConstraintsShown[theState];
1258         }
1259       }
1260       break;
1261       case PartSet_Tools::Geometrical: {
1262         bool isGeometrical = !isDistanceKind(aKind);
1263         if (isGeometrical) {
1264           isProcessed = true;
1265           aSwitchedOn = myIsConstraintsShown[theState];
1266         }
1267       }
1268       break;
1269       case PartSet_Tools::Any: {
1270         isProcessed = true;
1271         bool isDistance = isDistanceKind(aKind);
1272         if (isDistance)
1273           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Dimensional];
1274         else
1275           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Geometrical];
1276       }
1277       break;
1278     default:
1279       break;
1280     }
1281   }
1282   return aSwitchedOn;
1283 }
1284
1285 /*void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
1286 {
1287   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1288                                                                            (getCurrentOperation());
1289   if (aFOperation && myCurrentSketch.get()) {
1290     // find results of the current operation
1291     // these results should not be proposed to be deleted
1292     FeaturePtr anOperationFeature = aFOperation->feature();
1293     std::list<ResultPtr> anOperationResultList = anOperationFeature->results();
1294     std::set<ResultPtr> anOperationResults;
1295     std::list<ResultPtr>::const_iterator aRIt = anOperationResultList.begin(),
1296                                         aRLast = anOperationResultList.end();
1297     for (; aRIt != aRLast; aRIt++)
1298       anOperationResults.insert(*aRIt);
1299
1300     std::set<FeaturePtr> anObjectsToBeDeleted;
1301     QStringList anObjectsToBeDeletedNames;
1302     std::list<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1303     for (; anIt != aLast; anIt++) {
1304       ObjectPtr anObject = *anIt;
1305       bool aCanErase = true;
1306       // when the sketch operation is active, results of sketch sub-feature can not be hidden
1307       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1308       // the result is found between current feature results
1309       if (anOperationResults.find(aResult) != anOperationResults.end())
1310         continue;
1311
1312       if (aResult.get()) {
1313         // Display sketcher objects
1314         for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1315           FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1316           std::list<ResultPtr> aResults = aFeature->results();
1317           std::list<ResultPtr>::const_iterator anIt;
1318           for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1319             aCanErase = *anIt != aResult;
1320           }
1321         }
1322       }
1323       if (!aCanErase) {
1324         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
1325         if (aFeature.get() && anObjectsToBeDeleted.find(aFeature) == anObjectsToBeDeleted.end()) {
1326           anObjectsToBeDeleted.insert(aFeature);
1327           anObjectsToBeDeletedNames.append(aFeature->name().c_str());
1328         }
1329       }
1330     }
1331     if (!anObjectsToBeDeleted.empty()) {
1332       QString aFeatureNames = anObjectsToBeDeletedNames.join(", ");
1333       QString aMessage = tr("The following features have incorrect presentation and \
1334 will be hidden: %1. Would you like to delete them?")
1335                          .arg(aFeatureNames);
1336       int anAnswer = QMessageBox::question(qApp->activeWindow(), tr("Features hide"),
1337                                            aMessage, QMessageBox::Ok | QMessageBox::Cancel,
1338                                            QMessageBox::Cancel);
1339       if (anAnswer == QMessageBox::Ok) {
1340         QObjectPtrList anObjects;
1341         std::set<FeaturePtr>::const_iterator anIt = anObjectsToBeDeleted.begin(),
1342                                              aLast = anObjectsToBeDeleted.end();
1343         for (; anIt != aLast; anIt++)
1344           anObjects.append(*anIt);
1345         SessionPtr aMgr = ModelAPI_Session::get();
1346         DocumentPtr aDoc = aMgr->activeDocument();
1347         bool aIsOp = aMgr->isOperation();
1348         if (!aIsOp)
1349           aMgr->startOperation();
1350         workshop()->deleteFeatures(anObjects);
1351         //static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
1352         //static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
1353         //Events_Loop::loop()->flush(aDeletedEvent);
1354         //Events_Loop::loop()->flush(aRedispEvent);
1355
1356         if (!aIsOp)
1357           aMgr->finishOperation();
1358       }
1359     }
1360   }
1361 }*/
1362
1363 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1364 {
1365   bool aCanDisplay = myIsMouseOverWindow;
1366   if (!aCanDisplay) {
1367     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1368     if (anActiveWidget)
1369       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1370   }
1371   return aCanDisplay;
1372 }
1373
1374 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1375 {
1376   return isNestedCreateOperation(theOperation, activeSketch()) ||
1377          myModule->sketchReentranceMgr()->isInternalEditActive();
1378 }
1379
1380 const QMap<PartSet_Tools::ConstraintVisibleState, bool>& PartSet_SketcherMgr::showConstraintStates()
1381 {
1382   return myIsConstraintsShown;
1383 }
1384
1385 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1386 {
1387   bool isFoundObject = false;
1388
1389   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1390   if (anObjectFeature.get()) {
1391     int aSize = myCurrentSketch->numberOfSubs();
1392     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1393       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1394       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1395     }
1396   }
1397   return isFoundObject;
1398 }
1399
1400 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
1401 {
1402   if (myPlaneFilter.IsNull())
1403    myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
1404
1405   myPlaneFilter->setPlane(thePln);
1406 }
1407
1408 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
1409                                                          ModuleBase_IWorkshop* theWorkshop,
1410                                                          bool& theCanCommitOperation)
1411 {
1412   bool isValueAccepted = false;
1413   theCanCommitOperation = false;
1414
1415   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1416                                                                               (theOperation);
1417   FeaturePtr aFeature = aFOperation->feature();
1418   // editor is shown only if all attribute references are filled by preseletion
1419   bool anAllRefAttrInitialized = true;
1420
1421   std::list<AttributePtr> aRefAttrs = aFeature->data()->attributes(
1422                                               ModelAPI_AttributeRefAttr::typeId());
1423   std::list<AttributePtr>::const_iterator anIt = aRefAttrs.begin(), aLast = aRefAttrs.end();
1424   for (; anIt != aLast && anAllRefAttrInitialized; anIt++) {
1425     anAllRefAttrInitialized = (*anIt)->isInitialized();
1426   }
1427   if (anAllRefAttrInitialized) {
1428     // Activate dimension value editing on double click
1429     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
1430     QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
1431     // Find corresponded widget to activate value editing
1432     foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
1433       if (aWgt->attributeID() == "ConstraintValue") {
1434         // the featue should be displayed in order to find the AIS text position,
1435         // the place where the editor will be shown
1436         aFeature->setDisplayed(true);
1437         /// the execute is necessary to perform in the feature compute for flyout position
1438         aFeature->execute();
1439
1440         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1441         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1442
1443         PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
1444         if (anEditor) {
1445           int aX = 0, anY = 0;
1446
1447           XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(theWorkshop);
1448           XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1449           AISObjectPtr anAIS = aDisplayer->getAISObject(aFeature);
1450           Handle(AIS_InteractiveObject) anAISIO;
1451           if (anAIS.get() != NULL) {
1452             anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1453           }
1454           if (anAIS.get() != NULL) {
1455             Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1456
1457             if (!anAISIO.IsNull()) {
1458               Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAISIO);
1459               if (!aDim.IsNull()) {
1460                 gp_Pnt aPosition = aDim->GetTextPosition();
1461
1462                 ModuleBase_IViewer* aViewer = aWorkshop->viewer();
1463                 Handle(V3d_View) aView = aViewer->activeView();
1464                 int aCX, aCY;
1465                 aView->Convert(aPosition.X(), aPosition.Y(), aPosition.Z(), aCX, aCY);
1466
1467                 QWidget* aViewPort = aViewer->activeViewPort();
1468                 QPoint aGlPoint = aViewPort->mapToGlobal(QPoint(aCX, aCY));
1469                 aX = aGlPoint.x();
1470                 anY = aGlPoint.y();
1471               }
1472             }
1473             anEditor->setCursorPosition(aX, anY);
1474             isValueAccepted = anEditor->showPopupEditor(false);
1475             theCanCommitOperation = true;
1476           }
1477         }
1478       }
1479     }
1480   }
1481   return isValueAccepted;
1482 }
1483
1484 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1485                                              const FeaturePtr& theSketch,
1486                                              ModuleBase_IWorkshop* theWorkshop,
1487                                              const FeatureToSelectionMap& theSelection,
1488                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1489 {
1490   if (theFeature.get() == NULL)
1491     return;
1492
1493   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1494   SelectionInfo anInfo = anIt.value();
1495   std::set<AttributePtr> aSelectedAttributes = anInfo.myAttributes;
1496   std::set<ResultPtr> aSelectedResults = anInfo.myResults;
1497
1498   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1499
1500   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1501   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1502
1503   // 1. found the feature's owners. Check the AIS objects of the constructions
1504   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1505   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1506     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1507
1508     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1509     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1510     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1511       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1512       if (!anOwner.IsNull())
1513         theOwnersToSelect.Add(anOwner);
1514     }
1515   }
1516
1517   // 2. found the feature results's owners
1518   std::list<ResultPtr> aResults = theFeature->results();
1519   std::list<ResultPtr>::const_iterator aIt;
1520
1521   bool isSameShape = false;
1522   if (aResults.size() > 0) {
1523     ResultPtr aFirstResult = theFeature->firstResult();
1524     if (aFirstResult.get() && aFirstResult->shape().get()) {
1525       const TopoDS_Shape& aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
1526       isSameShape = aFirstShape.IsEqual(anInfo.myFirstResultShape);
1527     }
1528   }
1529   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1530     ResultPtr aResult = *aIt;
1531     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1532     if (aAISObj.get() == NULL)
1533       continue;
1534     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1535
1536     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1537     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1538     bool aFoundLocalShape = false;
1539     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1540       Handle(StdSelect_BRepOwner) anOwner =
1541         Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1542       if ( anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
1543         continue;
1544       const TopoDS_Shape& aShape = anOwner->Shape();
1545       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1546       if (aShapeType == TopAbs_VERTEX) {
1547         AttributePtr aPntAttr =
1548           PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1549         if (aPntAttr.get() != NULL &&
1550             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end())
1551           theOwnersToSelect.Add(anOwner);
1552         else if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
1553           theOwnersToSelect.Add(anOwner);
1554         }
1555       }
1556       else if (aShapeType == TopAbs_EDGE) {
1557         if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
1558           // try to restore local selection on Shape result
1559           // we can do this only if the shape was not changed
1560           theOwnersToSelect.Add(anOwner);
1561           aFoundLocalShape = true;
1562           break;
1563         }
1564       }
1565     }
1566     if (!aFoundLocalShape) {
1567       // result owners are put in the list of selection only if local selected shapes were not
1568       // found
1569       if (aSelectedResults.find(aResult) != aSelectedResults.end()) {
1570         for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1571           Handle(StdSelect_BRepOwner) anOwner =
1572             Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1573           if ( anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
1574             continue;
1575             // select whole result
1576             theOwnersToSelect.Add(anOwner);
1577         }
1578       }
1579     }
1580   }
1581 }
1582
1583 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
1584                                                  const bool isToConnect)
1585 {
1586   //Temporary commented as we do not modify values in property panel
1587   if (isToConnect) {
1588     //connect(theWidget, SIGNAL(beforeValuesChanged()),
1589     //        this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1590     //connect(theWidget, SIGNAL(afterValuesChanged()),
1591     //        this, SLOT(onAfterValuesChangedInPropertyPanel()));
1592     connect(theWidget, SIGNAL(afterValuesChanged()),
1593             myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
1594   }
1595   else {
1596     //disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1597     //            this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1598     //disconnect(theWidget, SIGNAL(afterValuesChanged()),
1599     //            this, SLOT(onAfterValuesChangedInPropertyPanel()));
1600     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1601                myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
1602   }
1603 }
1604
1605 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1606 {
1607   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1608                                                                            (getCurrentOperation());
1609   if (aFOperation) {
1610     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1611         isNestedSketchOperation(aFOperation) &&
1612         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1613       FeaturePtr aFeature = aFOperation->feature();
1614       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1615     }
1616   }
1617 }
1618
1619 void PartSet_SketcherMgr::customizePresentation(const ObjectPtr& theObject)
1620 {
1621   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1622                                                                            (getCurrentOperation());
1623   if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1624                       isNestedSketchOperation(aFOperation)))
1625     SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
1626
1627   // update entities selection priorities
1628   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1629   if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1630     // update priority for feature
1631     updateSelectionPriority(aFeature, aFeature);
1632     // update priority for results of the feature
1633     std::list<ResultPtr> aResults = aFeature->results();
1634     std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLastIt = aResults.end();
1635     for (; anIt != aLastIt; anIt++)
1636       updateSelectionPriority(*anIt, aFeature);
1637   }
1638 }
1639
1640 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1641 {
1642   return myModule->workshop()->currentOperation();
1643 }
1644
1645 //**************************************************************
1646 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1647 {
1648   ModuleBase_ModelWidget* aWidget = 0;
1649   ModuleBase_Operation* anOperation = getCurrentOperation();
1650   if (anOperation) {
1651     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1652     if (aPanel)
1653       aWidget = aPanel->activeWidget();
1654   }
1655   return aWidget;
1656 }
1657
1658 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1659                                            const bool isEditOperation,
1660                                            const bool isToDisplay,
1661                                            const bool isFlushRedisplay)
1662 {
1663   #ifdef DEBUG_DO_NOT_BY_ENTER
1664   return;
1665   #endif
1666
1667   if (isEditOperation || !theFeature.get())
1668     return;
1669
1670   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1671   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1672
1673   // 1. change visibility of the object itself, here the presentable object is processed,
1674   // e.g. constraints features
1675   //FeaturePtr aFeature = aFOperation->feature();
1676   std::list<ResultPtr> aResults = theFeature->results();
1677   if (isToDisplay)
1678     theFeature->setDisplayed(true);
1679   else
1680     theFeature->setDisplayed(false);
1681
1682   // change visibility of the object results, e.g. non-constraint features
1683   std::list<ResultPtr>::const_iterator aIt;
1684   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1685     if (isToDisplay) {
1686       (*aIt)->setDisplayed(true);
1687     }
1688     else {
1689       (*aIt)->setDisplayed(false);
1690     }
1691   }
1692   if (isFlushRedisplay)
1693     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1694 }
1695
1696 void PartSet_SketcherMgr::storeSelection(const bool theHighlightedOnly,
1697                         PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
1698 {
1699   if (!myCurrentSketch.get())
1700     return;
1701
1702   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1703   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1704   QList<ModuleBase_ViewerPrsPtr> aStoredPrs = aSelect->getHighlighted();
1705
1706   QList<FeaturePtr> aFeatureList;
1707   if (!theHighlightedOnly) {
1708     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(
1709                                                               ModuleBase_ISelection::AllControls);
1710     aStoredPrs.append(aSelected);
1711   }
1712
1713   // 1. it is necessary to save current selection in order to restore it after the features moving
1714   theCurrentSelection.clear();
1715
1716   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = aStoredPrs.begin(),
1717                                                 aLast = aStoredPrs.end();
1718
1719   CompositeFeaturePtr aSketch = activeSketch();
1720   for (; anIt != aLast; anIt++) {
1721     ModuleBase_ViewerPrsPtr aPrs = *anIt;
1722     ObjectPtr anObject = aPrs->object();
1723     if (!anObject.get())
1724       continue;
1725
1726     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1727     FeaturePtr aFeature;
1728     if (aResult.get())
1729       aFeature = ModelAPI_Feature::feature(aResult);
1730     else
1731       aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1732
1733     if (!aFeature.get())
1734       continue;
1735
1736     std::set<AttributePtr> aSelectedAttributes;
1737     std::set<ResultPtr> aSelectedResults;
1738     SelectionInfo anInfo;
1739     if (theCurrentSelection.find(aFeature) != theCurrentSelection.end())
1740       anInfo = theCurrentSelection.find(aFeature).value();
1741
1742     TopoDS_Shape aFirstShape;
1743     ResultPtr aFirstResult = aFeature->firstResult();
1744     if (aFirstResult.get() && aFirstResult->shape().get())
1745       aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
1746     anInfo.myFirstResultShape = aFirstShape;
1747     Handle(SelectMgr_EntityOwner) anOwner = aPrs->owner();
1748     if (aResult.get()) {
1749       getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1750           anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
1751     }
1752     else {
1753       std::list<ResultPtr> aResults = aFeature->results();
1754       std::list<ResultPtr>::const_iterator aIt;
1755       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1756         ResultPtr aResult = *aIt;
1757         getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1758           anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
1759       }
1760     }
1761     theCurrentSelection[aFeature] = anInfo;
1762   }
1763   //qDebug(QString("  storeSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
1764 }
1765
1766 void PartSet_SketcherMgr::restoreSelection(
1767                                 PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
1768 {
1769   if (!myCurrentSketch.get())
1770     return;
1771
1772   //qDebug(QString("restoreSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
1773   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1774   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1775   FeatureToSelectionMap::const_iterator aSIt = theCurrentSelection.begin(),
1776                                         aSLast = theCurrentSelection.end();
1777   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1778   anOwnersToSelect.Clear();
1779   for (; aSIt != aSLast; aSIt++) {
1780     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, theCurrentSelection,
1781                        anOwnersToSelect);
1782   }
1783   aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1784 }
1785
1786 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
1787 {
1788   PartSet_Tools::ConstraintVisibleState aType = (PartSet_Tools::ConstraintVisibleState)theType;
1789
1790   updateBySketchParameters(aType, theState);
1791 }
1792
1793 void PartSet_SketcherMgr::updateBySketchParameters(
1794                                    const PartSet_Tools::ConstraintVisibleState& theType,
1795                                    bool theState)
1796 {
1797   if (myCurrentSketch.get() == NULL)
1798     return;
1799
1800   bool aPrevState = myIsConstraintsShown[theType];
1801   myIsConstraintsShown[theType] = theState;
1802
1803   switch (theType) {
1804     case PartSet_Tools::Geometrical:
1805     case PartSet_Tools::Dimensional: {
1806       if (aPrevState != theState) {
1807         ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1808         XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1809         for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1810           FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1811           bool aProcessed = false;
1812           bool aConstraintDisplayed = canDisplayConstraint(aSubFeature, theType, aProcessed);
1813           if (aProcessed)
1814             aSubFeature->setDisplayed(aConstraintDisplayed);
1815         }
1816         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1817       }
1818     }
1819     break;
1820     case PartSet_Tools::Expressions: {
1821       if (aPrevState != theState) {
1822         /// call all sketch features redisplay, the expression state will be corrected in customize
1823         /// of distance presentation
1824         Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1825         PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
1826       }
1827     }
1828     break;
1829   }
1830 }
1831
1832 void PartSet_SketcherMgr::updateSelectionPriority(ObjectPtr theObject,
1833                                                   FeaturePtr theFeature)
1834 {
1835   if (!theObject.get() || !theFeature.get())
1836     return;
1837
1838   AISObjectPtr anAIS = workshop()->displayer()->getAISObject(theObject);
1839   Handle(AIS_InteractiveObject) anAISIO;
1840   if (anAIS.get() != NULL) {
1841     anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1842   }
1843
1844   if (!anAISIO.IsNull()) { // the presentation for the object is visualized
1845     int anAdditionalPriority = 0;
1846     // current feature
1847     std::shared_ptr<SketchPlugin_Feature> aSPFeature =
1848             std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
1849     if (aSPFeature.get() != NULL) {
1850       // 1. Vertices
1851       // 2. Simple segments
1852       // 3. External objects (violet color)
1853       // 4. Auxiliary segments (dotted)
1854       // StdSelect_BRepSelectionTool::Load uses priority calculating:
1855       // Standard_Integer aPriority =
1856       // (thePriority == -1) ? GetStandardPriority (theShape, theType) : thePriority;
1857       // Priority of Vertex is 8, edge(segment) is 7.
1858       // It might be not corrected as provides the condition above.
1859       bool isExternal = aSPFeature->isExternal();
1860       bool isAuxiliary = PartSet_Tools::isAuxiliarySketchEntity(aSPFeature);
1861       // current feature
1862       if (!isExternal && !isAuxiliary)
1863         anAdditionalPriority = 30;
1864       // external feature
1865       if (isExternal)
1866         anAdditionalPriority = 20;
1867       // auxiliary feature
1868       if (isAuxiliary) {
1869         anAdditionalPriority = 10; /// auxiliary objects should have less priority that
1870         // edges/vertices of local selection on not-sketch objects
1871       }
1872       Handle(ModuleBase_ResultPrs) aResult = Handle(ModuleBase_ResultPrs)::DownCast(anAISIO);
1873       if (!aResult.IsNull()) {
1874         aResult->setAdditionalSelectionPriority(anAdditionalPriority);
1875       }
1876     }
1877   }
1878 }
1879
1880 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
1881 {
1882   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1883   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1884   return aConnector->workshop();
1885 }
1886
1887 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1888 {
1889   return workshop()->operationMgr();
1890 }
1891