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