Salome HOME
Issue #1941 Split auxiliary line.
[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), myIsEditLaunching(false), myIsDragging(false),
137     myDragDone(false), 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 /*
270 //Temporary commented as we do not modify values in property panel
271 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
272 {
273   if (!isNestedEditOperation(getCurrentOperation(), myModule->sketchMgr()->activeSketch()) ||
274       myModule->sketchReentranceMgr()->isInternalEditActive())
275     return;
276   // it is necessary to save current selection in order to restore it after the values are modifed
277   storeSelection();
278
279   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
280   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
281   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
282   myPreviousUpdateViewerEnabled = aDisplayer->enableUpdateViewer(false);
283 }
284
285 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
286 {
287   if (!isNestedEditOperation(getCurrentOperation(), myModule->sketchMgr()->activeSketch()) ||
288       myModule->sketchReentranceMgr()->isInternalEditActive()) {
289     myModule->sketchReentranceMgr()->updateInternalEditActiveState();
290     return;
291   }
292   // it is necessary to restore current selection in order to restore it after values are modified
293   restoreSelection();
294   myCurrentSelection.clear();
295
296   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the
297   // viewer happens by deselect/select the modified objects. The flag should be restored after
298   // the selection processing. The update viewer should be also called.
299   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
300   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
301   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
302   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
303   aDisplayer->updateViewer();
304 }
305 */
306
307 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
308 {
309   if (myModule->sketchReentranceMgr()->processMousePressed(theWnd, theEvent))
310     return;
311
312   //get2dPoint(theWnd, theEvent, myClickedPoint);
313
314   if (!(theEvent->buttons() & Qt::LeftButton))
315     return;
316
317   // Clear dragging mode
318   myIsDragging = false;
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);
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   if (myModule->sketchReentranceMgr()->processMouseReleased(theWnd, theEvent))
429     return;
430
431   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
432   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
433   if (!aViewer->canDragByMouse())
434     return;
435   ModuleBase_Operation* aOp = getCurrentOperation();
436   if (aOp) {
437     if (isNestedSketchOperation(aOp)) {
438       // Only for sketcher operations
439       if (myIsDragging) {
440         if (myDragDone) {
441           myCurrentSelection.clear();
442         }
443       }
444     }
445   }
446
447   aWorkshop->viewer()->enableDrawMode(myPreviousDrawModeEnabled);
448   myIsDragging = false;
449
450   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
451   PartSet_MouseProcessor* aProcessor = dynamic_cast<PartSet_MouseProcessor*>(anActiveWidget);
452   if (aProcessor)
453     aProcessor->mouseReleased(theWnd, theEvent);
454 }
455
456 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
457 {
458 #ifdef DEBUG_SKETCH_ENTITIES_ON_MOVE
459   CompositeFeaturePtr aSketch = activeSketch();
460   if (aSketch.get()) {
461     std::cout << "mouse move SKETCH FEATURES [" << aSketch->numberOfSubs() << "]:" << std::endl;
462     QStringList anInfo;
463     for (int i = 0, aNbSubs = aSketch->numberOfSubs(); i < aNbSubs; i++) {
464       //std::cout << getFeatureInfo(aSketch->subFeature(i), false) << std::endl;
465       anInfo.append(ModuleBase_Tools::objectInfo(aSketch->subFeature(i)));
466     }
467     QString anInfoStr = anInfo.join("\n");
468     qDebug(QString("%1").arg(anInfo.size()).arg(anInfoStr).toStdString().c_str());
469   }
470 #endif
471
472   if (myModule->sketchReentranceMgr()->processMouseMoved(theWnd, theEvent))
473     return;
474
475   if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
476     // 1. perform the widget mouse move functionality and display the presentation
477     // the mouse move should be processed in the widget, if it can in order to visualize correct
478     // presentation. These widgets correct the feature attribute according to the mouse position
479     ModuleBase_ModelWidget* anActiveWidget = myModule->activeWidget();
480     PartSet_MouseProcessor* aProcessor = dynamic_cast<PartSet_MouseProcessor*>(anActiveWidget);
481     if (aProcessor)
482       aProcessor->mouseMoved(theWnd, theEvent);
483     if (!myIsMouseOverViewProcessed) {
484       myIsMouseOverViewProcessed = true;
485
486       // the feature is to be erased here, but it is correct to call canDisplayObject because
487       // there can be additional check (e.g. editor widget in distance constraint)
488       ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
489                                                  (getCurrentOperation());
490       if (aFOperation) {
491         FeaturePtr aFeature = aFOperation->feature();
492         visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
493       }
494     }
495   }
496   //myClickedPoint.clear();
497
498   if (myIsDragging) {
499     // 1. the current selection is saved in the mouse press method in order to restore it after
500     //    moving
501     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
502     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
503     // deselected). This flag should be restored in the slot, processed the mouse release signal.
504
505     ModuleBase_Operation* aCurrentOperation = getCurrentOperation();
506     if (!aCurrentOperation)
507       return;
508     if (isSketchOperation(aCurrentOperation))
509       return; // No edit operation activated
510
511     Handle(V3d_View) aView = theWnd->v3dView();
512     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
513     Point aMousePnt;
514     get2dPoint(theWnd, theEvent, aMousePnt);
515     double dX =  aMousePnt.myCurX - myCurrentPoint.myCurX;
516     double dY =  aMousePnt.myCurY - myCurrentPoint.myCurY;
517
518     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
519     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
520     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
521     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the
522     // viewer happens by deselect/select the modified objects. The flag should be restored after
523     // the selection processing. The update viewer should be also called.
524     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
525
526     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
527     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
528     FeatureToSelectionMap::const_iterator anIt = myCurrentSelection.begin(),
529                                           aLast = myCurrentSelection.end();
530     // 4. the features and attributes modification(move)
531     bool isModified = false;
532     for (; anIt != aLast; anIt++) {
533       FeaturePtr aFeature = anIt.key();
534
535       std::set<AttributePtr> anAttributes = anIt.value().first;
536       // Process selection by attribute: the priority to the attribute
537       if (!anAttributes.empty()) {
538         std::set<AttributePtr>::const_iterator anAttIt = anAttributes.begin(),
539                                                anAttLast = anAttributes.end();
540         for (; anAttIt != anAttLast; anAttIt++) {
541           AttributePtr anAttr = *anAttIt;
542           if (anAttr.get() == NULL)
543             continue;
544           std::string aAttrId = anAttr->id();
545           DataPtr aData = aFeature->data();
546           if (aData->isValid()) {
547             std::shared_ptr<GeomDataAPI_Point2D> aPoint =
548               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
549             if (aPoint.get() != NULL) {
550               bool isImmutable = aPoint->setImmutable(true);
551               aPoint->move(dX, dY);
552               isModified = true;
553               ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
554               aPoint->setImmutable(isImmutable);
555             }
556           }
557         }
558       } else {
559         // Process selection by feature
560         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
561           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
562         if (aSketchFeature) {
563           aSketchFeature->move(dX, dY);
564           isModified = true;
565           ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
566         }
567       }
568     }
569     // the modified state of the current operation should be updated if there are features, which
570     // were changed here
571     if (isModified) {
572       aCurrentOperation->onValuesChanged();
573     }
574     Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
575     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
576
577     // 5. it is necessary to save current selection in order to restore it after the features moving
578     restoreSelection();
579     // 6. restore the update viewer flag and call this update
580     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
581     aDisplayer->updateViewer();
582
583     myDragDone = true;
584     myCurrentPoint = aMousePnt;
585   }
586 }
587
588 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
589 {
590   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
591                                                                (getCurrentOperation());
592   if (aFOperation && aFOperation->isEditOperation()) {
593     std::string aId = aFOperation->id().toStdString();
594     if (isDistanceOperation(aFOperation))
595     {
596       // Activate dimension value editing on double click
597       ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
598       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
599       // Find corresponded widget to activate value editing
600       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
601         if (aWgt->attributeID() == SketchPlugin_Constraint::VALUE() ||
602             aWgt->attributeID() == SketchPlugin_ConstraintAngle::ANGLE_VALUE_ID()) {
603           PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
604           if (anEditor)
605             anEditor->showPopupEditor();
606           return;
607         }
608       }
609     }
610   }
611 }
612
613 void PartSet_SketcherMgr::onApplicationStarted()
614 {
615   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
616   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
617   XGUI_Workshop* aWorkshop = aConnector->workshop();
618   PartSet_SketcherReetntrantMgr* aReentranceMgr = myModule->sketchReentranceMgr();
619
620   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
621   if (aPropertyPanel) {
622     //connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
623     //        this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
624
625     connect(aPropertyPanel, SIGNAL(noMoreWidgets(const std::string&)),
626             aReentranceMgr, SLOT(onNoMoreWidgets(const std::string&)));
627     connect(aPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
628             aReentranceMgr, SLOT(onWidgetActivated()));
629   }
630
631   XGUI_ViewerProxy* aViewerProxy = aWorkshop->viewer();
632   connect(aViewerProxy, SIGNAL(enterViewPort()), this, SLOT(onEnterViewPort()));
633   connect(aViewerProxy, SIGNAL(leaveViewPort()), this, SLOT(onLeaveViewPort()));
634
635   XGUI_ContextMenuMgr* aContextMenuMgr = aWorkshop->contextMenuMgr();
636   connect(aContextMenuMgr, SIGNAL(beforeContextMenu()), this, SLOT(onBeforeContextMenu()));
637   connect(aContextMenuMgr, SIGNAL(afterContextMenu()), this, SLOT(onAfterContextMenu()));
638 }
639
640 //void PartSet_SketcherMgr::onBeforeWidgetActivated(ModuleBase_ModelWidget* theWidget)
641 //{
642   //if (!myClickedPoint.myIsInitialized)
643   //  return;
644
645   //ModuleBase_Operation* aOperation = getCurrentOperation();
646   // the distance constraint feature should not use the clickedd point
647   // this is workaround in order to don't throw down the flyout point value,
648   // set by execute() method of these type of features
649   //if (isDistanceOperation(aOperation))
650   //  return;
651
652   //PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(theWidget);
653   //if (aPnt2dWgt) {
654   //  aPnt2dWgt->setPoint(myClickedPoint.myCurX, myClickedPoint.myCurY);
655   //}
656 //}
657
658 void PartSet_SketcherMgr::onBeforeContextMenu()
659 {
660   myIsPopupMenuActive = true;
661 }
662
663 void PartSet_SketcherMgr::onAfterContextMenu()
664 {
665   myIsPopupMenuActive = false;
666 }
667
668 void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent,
669                                      Point& thePoint)
670 {
671   Handle(V3d_View) aView = theWnd->v3dView();
672   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
673   double aX, anY;
674   PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, anY);
675   thePoint.setValue(aX, anY);
676 }
677
678 void PartSet_SketcherMgr::launchEditing()
679 {
680   if (!myCurrentSelection.empty()) {
681     FeaturePtr aFeature = myCurrentSelection.begin().key();
682     std::shared_ptr<SketchPlugin_Feature> aSPFeature =
683               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
684     if (aSPFeature && (!aSPFeature->isExternal())) {
685       myModule->editFeature(aSPFeature);
686     }
687   }
688 }
689
690 bool PartSet_SketcherMgr::sketchSolverError()
691 {
692   bool anError = false;
693   CompositeFeaturePtr aSketch = activeSketch();
694   if (aSketch.get()) {
695     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
696     anError = !aAttributeString->value().empty();
697   }
698   return anError;
699 }
700
701 QString PartSet_SketcherMgr::getFeatureError(const FeaturePtr& theFeature)
702 {
703   QString anError;
704   if (!theFeature.get() || !theFeature->data()->isValid())
705     return anError;
706
707   CompositeFeaturePtr aSketch = activeSketch();
708   if (aSketch.get() && aSketch == theFeature) {
709     std::string aSolverError = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR())->value();
710     anError = ModuleBase_Tools::translate(aSketch->getKind(), aSolverError);
711   }
712   return anError;
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   Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
907   const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
908   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
909     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
910 #ifdef DEBUG_SKETCHER_ENTITIES
911     anInfo.append(ModuleBase_Tools::objectInfo(aFeature));
912 #endif
913     std::list<ResultPtr> aResults = aFeature->results();
914     std::list<ResultPtr>::const_iterator aIt;
915     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
916       if ((*aIt)->isDisplayed())
917         // Display object if it was created outside of GUI
918         aECreator->sendUpdated((*aIt), EVENT_DISP);
919       else
920         (*aIt)->setDisplayed(true);
921     }
922     if (aFeature->isDisplayed())
923       aECreator->sendUpdated(aFeature, EVENT_DISP);
924     else
925       aFeature->setDisplayed(true);
926   }
927 #ifdef DEBUG_SKETCHER_ENTITIES
928   QString anInfoStr = anInfo.join(";\t");
929   qDebug(QString("startSketch: %1, %2").arg(anInfo.size()).arg(anInfoStr).toStdString().c_str());
930 #endif
931
932   if(myCirclePointFilter.IsNull()) {
933     myCirclePointFilter = new PartSet_CirclePointFilter(myModule->workshop());
934   }
935
936   myModule->workshop()->viewer()->addSelectionFilter(myCirclePointFilter);
937
938   if (myPlaneFilter.IsNull())
939     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
940
941   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
942   bool aHasPlane = false;
943   std::shared_ptr<GeomAPI_Pln> aPln;
944   aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
945   myPlaneFilter->setPlane(aPln);
946
947   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
948   // all displayed objects should be activated in current selection modes according to switched
949   // plane filter
950   if (aPln.get())
951     aConnector->activateModuleSelectionModes();
952 }
953
954 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
955 {
956   myIsMouseOverWindow = false;
957   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
958   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
959   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
960
961   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
962
963   DataPtr aData = myCurrentSketch->data();
964   if (!aData->isValid()) {
965     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
966     // The sketch was aborted
967     myCurrentSketch = CompositeFeaturePtr();
968     // TODO: move this outside of if-else
969     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
970     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
971
972     // Erase all sketcher objects
973     QObjectPtrList aObjects = aDisplayer->displayedObjects();
974     foreach (ObjectPtr aObj, aObjects) {
975       DataPtr aObjData = aObj->data();
976       if (!aObjData->isValid())
977         aObj->setDisplayed(false);
978     }
979   }
980   else {
981     // Hide all sketcher sub-Objects
982     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
983       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
984       std::list<ResultPtr> aResults = aFeature->results();
985       std::list<ResultPtr>::const_iterator aIt;
986       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
987         (*aIt)->setDisplayed(false);
988       }
989       aFeature->setDisplayed(false);
990     }
991     // Display sketcher result
992     std::list<ResultPtr> aResults = myCurrentSketch->results();
993     std::list<ResultPtr>::const_iterator aIt;
994     Events_Loop* aLoop = Events_Loop::loop();
995     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
996
997     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
998                                                                            (theOperation);
999     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1000       if (!aFOperation->isDisplayedOnStart(*aIt)) {
1001         (*aIt)->setDisplayed(true);
1002         // this display event is needed because sketch already may have "displayed" state,
1003         // but not displayed while it is still active (issue 613, abort of existing sketch)
1004         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
1005       }
1006     }
1007     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
1008       myCurrentSketch->setDisplayed(true);
1009
1010     myCurrentSketch = CompositeFeaturePtr();
1011
1012     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
1013     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
1014
1015     Events_Loop::loop()->flush(aDispEvent);
1016   }
1017   // restore the module selection modes, which were changed on startSketch
1018   aConnector->activateModuleSelectionModes();
1019 }
1020
1021 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
1022 {
1023   if (canChangeCursor(theOperation) && myIsMouseOverWindow) {
1024     QCursor* aCurrentCursor = QApplication::overrideCursor();
1025     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
1026       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
1027 #ifdef DEBUG_CURSOR
1028       qDebug("startNestedSketch() : Qt::CrossCursor");
1029 #endif
1030     }
1031   }
1032 }
1033
1034 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
1035 {
1036   myIsMouseOverViewProcessed = true;
1037   operationMgr()->onValidateOperation();
1038   // when sketch nested operation is stopped the cursor should be restored unconditionally
1039   //if (canChangeCursor(theOperation)) {
1040     QApplication::restoreOverrideCursor();
1041 #ifdef DEBUG_CURSOR
1042     qDebug("stopNestedSketch() : None");
1043 #endif
1044   //}
1045   /// improvement to deselect automatically all eventual selected objects, when
1046   // returning to the neutral point of the Sketcher
1047   bool isClearSelectionPossible = true;
1048   if (myIsEditLaunching) {
1049     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1050                                                                           (theOperation);
1051     if (aFOperation) {
1052       FeaturePtr aFeature = aFOperation->feature();
1053       if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1054         isClearSelectionPossible = false;
1055       }
1056     }
1057   }
1058   if (isClearSelectionPossible)
1059     workshop()->selector()->clearSelection();
1060 }
1061
1062 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
1063 {
1064   if (isNestedCreateOperation(theOperation, activeSketch())) {
1065     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1066                                                                              (theOperation);
1067     if (aFOperation) {
1068       FeaturePtr aFeature = aFOperation->feature();
1069       // it is necessary to check the the feature data validity because
1070       // some kind of features are removed by an operation commit(the macro state of a feature)
1071       if (aFeature.get() && aFeature->data()->isValid()) {
1072         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
1073       }
1074     }
1075   }
1076 }
1077
1078 void PartSet_SketcherMgr::activatePlaneFilter(const bool& toActivate)
1079 {
1080   if (toActivate)
1081     myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
1082   else
1083     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
1084 }
1085
1086 bool PartSet_SketcherMgr::operationActivatedByPreselection()
1087 {
1088   bool isOperationStopped = false;
1089   ModuleBase_Operation* anOperation = getCurrentOperation();
1090   if(anOperation && isNestedSketchOperation(anOperation)) {
1091     // Set final definitions if they are necessary
1092     //propertyPanelDefined(aOperation);
1093     /// Commit sketcher operations automatically
1094     /// distance operation are able to show popup editor to modify the distance value
1095     /// after entering the value, the operation should be committed/aborted(by Esc key)
1096     bool aCanCommitOperation = true;
1097     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1098                                                                             (anOperation);
1099     if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation)) {
1100       bool aValueAccepted = setDistanceValueByPreselection(anOperation, myModule->workshop(),
1101                                                            aCanCommitOperation);
1102       if (!aValueAccepted)
1103         return isOperationStopped;
1104     }
1105
1106     if (aCanCommitOperation)
1107       isOperationStopped = anOperation->commit();
1108     else {
1109       anOperation->abort();
1110       isOperationStopped = true;
1111     }
1112   }
1113   return isOperationStopped;
1114 }
1115
1116 bool PartSet_SketcherMgr::canUndo() const
1117 {
1118   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1119 }
1120
1121 bool PartSet_SketcherMgr::canRedo() const
1122 {
1123   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1124 }
1125
1126 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1127 {
1128   bool aCanErase = true;
1129   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1130   if (myCurrentSketch.get()) {
1131     return !isObjectOfSketch(theObject);
1132   }
1133   return aCanErase;
1134 }
1135
1136 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1137 {
1138   bool aCanDisplay = true;
1139
1140   bool aHasActiveSketch = activeSketch().get() != NULL;
1141   if (aHasActiveSketch) {
1142     // 1. the sketch feature should not be displayed during the sketch active operation
1143     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch
1144     // nested features can be visualized
1145     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1146     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1147       aCanDisplay = false;
1148     }
1149     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1150                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1151     /// some sketch entities should be never shown, e.g. projection feature
1152     if (aSketchFeature.get())
1153       aCanDisplay = aSketchFeature->canBeDisplayed();
1154   }
1155   else { // there are no an active sketch
1156     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1157     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1158     if (aFeature.get() != NULL) {
1159       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1160                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1161       if (aSketchFeature.get()) {
1162         aCanDisplay = false;
1163       }
1164     }
1165   }
1166
1167   // 3. the method should not filter the objects, which are not related to the current operation.
1168   // The object is filtered just if it is a current operation feature or this feature result
1169   if (aCanDisplay) {
1170     bool isObjectFound = false;
1171     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1172                                                                  (getCurrentOperation());
1173     if (aFOperation) {
1174       FeaturePtr aFeature = aFOperation->feature();
1175       if (aFeature.get()) {
1176         std::list<ResultPtr> aResults = aFeature->results();
1177         if (theObject == aFeature)
1178           isObjectFound = true;
1179         else {
1180           std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1181           for (; anIt != aLast && !isObjectFound; anIt++) {
1182             isObjectFound = *anIt == theObject;
1183           }
1184         }
1185       }
1186     }
1187     if (isObjectFound) {
1188       // 4. For created nested feature operation do not display the created feature if
1189       // the mouse curstor leaves the OCC window.
1190       // The correction cases, which ignores this condition:
1191       // a. the property panel values modification
1192       // b. the popup menu activated
1193       // c. widget editor control
1194       #ifndef DEBUG_DO_NOT_BY_ENTER
1195       if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
1196         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1197         ModuleBase_WidgetEditor* anEditorWdg =
1198           anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1199         // the active widget editor should not influence here. The presentation should be visible
1200         // always when this widget is active.
1201         if (!anEditorWdg && !myIsPopupMenuActive) {
1202           // during a nested create operation, the feature is redisplayed only
1203           // if the mouse over view
1204           // of there was a value modified in the property panel after the mouse left the view
1205           aCanDisplay = canDisplayCurrentCreatedFeature();
1206         }
1207       }
1208       #endif
1209     }
1210   }
1211
1212   // checks the sketcher constraints visibility according to active sketch check box states
1213   if (aCanDisplay) {
1214     bool aProcessed = false;
1215     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1216     if (aFeature.get()) {
1217       bool aConstraintDisplayed = canDisplayConstraint(aFeature, PartSet_Tools::Any, aProcessed);
1218       if (aProcessed)
1219         aCanDisplay = aConstraintDisplayed;
1220     }
1221   }
1222
1223   return aCanDisplay;
1224 }
1225
1226 bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
1227                                              const PartSet_Tools::ConstraintVisibleState& theState,
1228                                              bool& isProcessed) const
1229 {
1230   bool aSwitchedOn = true;
1231
1232   const QStringList& aConstrIds = constraintsIdList();
1233
1234   std::string aKind = theFeature->getKind();
1235   if (aConstrIds.contains(QString(aKind.c_str()))) {
1236     bool isTypedConstraint = false;
1237
1238     switch (theState) {
1239       case PartSet_Tools::Dimensional: {
1240         bool isDistance = isDistanceKind(aKind);
1241         if (isDistance) {
1242           isProcessed = true;
1243           aSwitchedOn = myIsConstraintsShown[theState];
1244         }
1245       }
1246       break;
1247       case PartSet_Tools::Geometrical: {
1248         bool isGeometrical = !isDistanceKind(aKind);
1249         if (isGeometrical) {
1250           isProcessed = true;
1251           aSwitchedOn = myIsConstraintsShown[theState];
1252         }
1253       }
1254       break;
1255       case PartSet_Tools::Any: {
1256         isProcessed = true;
1257         bool isDistance = isDistanceKind(aKind);
1258         if (isDistance)
1259           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Dimensional];
1260         else
1261           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Geometrical];
1262       }
1263       break;
1264     default:
1265       break;
1266     }
1267   }
1268   return aSwitchedOn;
1269 }
1270
1271 /*void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
1272 {
1273   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1274                                                                            (getCurrentOperation());
1275   if (aFOperation && myCurrentSketch.get()) {
1276     // find results of the current operation
1277     // these results should not be proposed to be deleted
1278     FeaturePtr anOperationFeature = aFOperation->feature();
1279     std::list<ResultPtr> anOperationResultList = anOperationFeature->results();
1280     std::set<ResultPtr> anOperationResults;
1281     std::list<ResultPtr>::const_iterator aRIt = anOperationResultList.begin(),
1282                                         aRLast = anOperationResultList.end();
1283     for (; aRIt != aRLast; aRIt++)
1284       anOperationResults.insert(*aRIt);
1285
1286     std::set<FeaturePtr> anObjectsToBeDeleted;
1287     QStringList anObjectsToBeDeletedNames;
1288     std::list<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1289     for (; anIt != aLast; anIt++) {
1290       ObjectPtr anObject = *anIt;
1291       bool aCanErase = true;
1292       // when the sketch operation is active, results of sketch sub-feature can not be hidden
1293       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1294       // the result is found between current feature results
1295       if (anOperationResults.find(aResult) != anOperationResults.end())
1296         continue;
1297
1298       if (aResult.get()) {
1299         // Display sketcher objects
1300         for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1301           FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1302           std::list<ResultPtr> aResults = aFeature->results();
1303           std::list<ResultPtr>::const_iterator anIt;
1304           for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1305             aCanErase = *anIt != aResult;
1306           }
1307         }
1308       }
1309       if (!aCanErase) {
1310         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
1311         if (aFeature.get() && anObjectsToBeDeleted.find(aFeature) == anObjectsToBeDeleted.end()) {
1312           anObjectsToBeDeleted.insert(aFeature);
1313           anObjectsToBeDeletedNames.append(aFeature->name().c_str());
1314         }
1315       }
1316     }
1317     if (!anObjectsToBeDeleted.empty()) {
1318       QString aFeatureNames = anObjectsToBeDeletedNames.join(", ");
1319       QString aMessage = tr("The following features have incorrect presentation and \
1320 will be hidden: %1. Would you like to delete them?")
1321                          .arg(aFeatureNames);
1322       int anAnswer = QMessageBox::question(qApp->activeWindow(), tr("Features hide"),
1323                                            aMessage, QMessageBox::Ok | QMessageBox::Cancel,
1324                                            QMessageBox::Cancel);
1325       if (anAnswer == QMessageBox::Ok) {
1326         QObjectPtrList anObjects;
1327         std::set<FeaturePtr>::const_iterator anIt = anObjectsToBeDeleted.begin(),
1328                                              aLast = anObjectsToBeDeleted.end();
1329         for (; anIt != aLast; anIt++)
1330           anObjects.append(*anIt);
1331         SessionPtr aMgr = ModelAPI_Session::get();
1332         DocumentPtr aDoc = aMgr->activeDocument();
1333         bool aIsOp = aMgr->isOperation();
1334         if (!aIsOp)
1335           aMgr->startOperation();
1336         workshop()->deleteFeatures(anObjects);
1337         //static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
1338         //static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
1339         //Events_Loop::loop()->flush(aDeletedEvent);
1340         //Events_Loop::loop()->flush(aRedispEvent);
1341
1342         if (!aIsOp)
1343           aMgr->finishOperation();
1344       }
1345     }
1346   }
1347 }*/
1348
1349 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1350 {
1351   bool aCanDisplay = myIsMouseOverWindow;
1352   if (!aCanDisplay) {
1353     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1354     if (anActiveWidget)
1355       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1356   }
1357   return aCanDisplay;
1358 }
1359
1360 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1361 {
1362   return isNestedCreateOperation(theOperation, activeSketch()) ||
1363          myModule->sketchReentranceMgr()->isInternalEditActive();
1364 }
1365
1366 const QMap<PartSet_Tools::ConstraintVisibleState, bool>& PartSet_SketcherMgr::showConstraintStates()
1367 {
1368   return myIsConstraintsShown;
1369 }
1370
1371 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1372 {
1373   bool isFoundObject = false;
1374
1375   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1376   if (anObjectFeature.get()) {
1377     int aSize = myCurrentSketch->numberOfSubs();
1378     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1379       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1380       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1381     }
1382   }
1383   return isFoundObject;
1384 }
1385
1386 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
1387 {
1388   if (myPlaneFilter.IsNull())
1389    myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
1390
1391   myPlaneFilter->setPlane(thePln);
1392 }
1393
1394 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
1395                                                          ModuleBase_IWorkshop* theWorkshop,
1396                                                          bool& theCanCommitOperation)
1397 {
1398   bool isValueAccepted = false;
1399   theCanCommitOperation = false;
1400
1401   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1402                                                                               (theOperation);
1403   FeaturePtr aFeature = aFOperation->feature();
1404   // editor is shown only if all attribute references are filled by preseletion
1405   bool anAllRefAttrInitialized = true;
1406
1407   std::list<AttributePtr> aRefAttrs = aFeature->data()->attributes(
1408                                               ModelAPI_AttributeRefAttr::typeId());
1409   std::list<AttributePtr>::const_iterator anIt = aRefAttrs.begin(), aLast = aRefAttrs.end();
1410   for (; anIt != aLast && anAllRefAttrInitialized; anIt++) {
1411     anAllRefAttrInitialized = (*anIt)->isInitialized();
1412   }
1413   if (anAllRefAttrInitialized) {
1414     // Activate dimension value editing on double click
1415     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
1416     QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
1417     // Find corresponded widget to activate value editing
1418     foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
1419       if (aWgt->attributeID() == "ConstraintValue") {
1420         // the featue should be displayed in order to find the AIS text position,
1421         // the place where the editor will be shown
1422         aFeature->setDisplayed(true);
1423         /// the execute is necessary to perform in the feature compute for flyout position
1424         aFeature->execute();
1425
1426         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1427         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1428
1429         PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
1430         if (anEditor) {
1431           int aX = 0, anY = 0;
1432
1433           XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(theWorkshop);
1434           XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1435           AISObjectPtr anAIS = aDisplayer->getAISObject(aFeature);
1436           Handle(AIS_InteractiveObject) anAISIO;
1437           if (anAIS.get() != NULL) {
1438             anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1439           }
1440           if (anAIS.get() != NULL) {
1441             Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1442
1443             if (!anAISIO.IsNull()) {
1444               Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAISIO);
1445               if (!aDim.IsNull()) {
1446                 gp_Pnt aPosition = aDim->GetTextPosition();
1447
1448                 ModuleBase_IViewer* aViewer = aWorkshop->viewer();
1449                 Handle(V3d_View) aView = aViewer->activeView();
1450                 int aCX, aCY;
1451                 aView->Convert(aPosition.X(), aPosition.Y(), aPosition.Z(), aCX, aCY);
1452
1453                 QWidget* aViewPort = aViewer->activeViewPort();
1454                 QPoint aGlPoint = aViewPort->mapToGlobal(QPoint(aCX, aCY));
1455                 aX = aGlPoint.x();
1456                 anY = aGlPoint.y();
1457               }
1458             }
1459             anEditor->setCursorPosition(aX, anY);
1460             isValueAccepted = anEditor->showPopupEditor(false);
1461             theCanCommitOperation = true;
1462           }
1463         }
1464       }
1465     }
1466   }
1467   return isValueAccepted;
1468 }
1469
1470 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1471                                              const FeaturePtr& theSketch,
1472                                              ModuleBase_IWorkshop* theWorkshop,
1473                                              const FeatureToSelectionMap& theSelection,
1474                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1475 {
1476   if (theFeature.get() == NULL)
1477     return;
1478
1479   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1480   std::set<AttributePtr> aSelectedAttributes = anIt.value().first;
1481   std::set<ResultPtr> aSelectedResults = anIt.value().second;
1482
1483   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1484
1485   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1486   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1487
1488   // 1. found the feature's owners. Check the AIS objects of the constructions
1489   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1490   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1491     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1492
1493     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1494     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1495     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1496       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1497       if (!anOwner.IsNull())
1498         theOwnersToSelect.Add(anOwner);
1499     }
1500   }
1501
1502   // 2. found the feature results's owners
1503   std::list<ResultPtr> aResults = theFeature->results();
1504   std::list<ResultPtr>::const_iterator aIt;
1505   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1506   {
1507     ResultPtr aResult = *aIt;
1508     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1509     if (aAISObj.get() == NULL)
1510       continue;
1511     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1512
1513     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1514     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1515     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1516       Handle(StdSelect_BRepOwner) anOwner =
1517         Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1518       if ( anOwner.IsNull() || !anOwner->HasShape() )
1519         continue;
1520       const TopoDS_Shape& aShape = anOwner->Shape();
1521       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1522       if (aShapeType == TopAbs_VERTEX) {
1523         AttributePtr aPntAttr =
1524           PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1525         if (aPntAttr.get() != NULL &&
1526             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end()) {
1527           theOwnersToSelect.Add(anOwner);
1528         }
1529       }
1530       else if (aShapeType == TopAbs_EDGE) {
1531         bool aFound = aSelectedResults.find(aResult) != aSelectedResults.end();
1532         if (aSelectedResults.find(aResult) != aSelectedResults.end() &&
1533             theOwnersToSelect.FindIndex(anOwner) <= 0)
1534           theOwnersToSelect.Add(anOwner);
1535       }
1536     }
1537   }
1538 }
1539
1540 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
1541                                                  const bool isToConnect)
1542 {
1543   /*Temporary commented as we do not modify values in property panel
1544   if (isToConnect) {
1545     connect(theWidget, SIGNAL(beforeValuesChanged()),
1546             this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1547     connect(theWidget, SIGNAL(afterValuesChanged()),
1548             this, SLOT(onAfterValuesChangedInPropertyPanel()));
1549   }
1550   else {
1551     disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1552                 this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1553     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1554                 this, SLOT(onAfterValuesChangedInPropertyPanel()));
1555   }*/
1556 }
1557
1558 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1559 {
1560   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1561                                                                            (getCurrentOperation());
1562   if (aFOperation) {
1563     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1564         isNestedSketchOperation(aFOperation) &&
1565         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1566       FeaturePtr aFeature = aFOperation->feature();
1567       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1568     }
1569   }
1570 }
1571
1572 void PartSet_SketcherMgr::customizePresentation(const ObjectPtr& theObject)
1573 {
1574   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1575                                                                            (getCurrentOperation());
1576   if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1577                       isNestedSketchOperation(aFOperation)))
1578     SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
1579
1580   // update entities selection priorities
1581   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1582   if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1583     // update priority for feature
1584     updateSelectionPriority(aFeature, aFeature);
1585     // update priority for results of the feature
1586     std::list<ResultPtr> aResults = aFeature->results();
1587     std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLastIt = aResults.end();
1588     for (; anIt != aLastIt; anIt++)
1589       updateSelectionPriority(*anIt, aFeature);
1590   }
1591 }
1592
1593 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1594 {
1595   return myModule->workshop()->currentOperation();
1596 }
1597
1598 //**************************************************************
1599 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1600 {
1601   ModuleBase_ModelWidget* aWidget = 0;
1602   ModuleBase_Operation* anOperation = getCurrentOperation();
1603   if (anOperation) {
1604     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1605     if (aPanel)
1606       aWidget = aPanel->activeWidget();
1607   }
1608   return aWidget;
1609 }
1610
1611 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1612                                            const bool isEditOperation,
1613                                            const bool isToDisplay,
1614                                            const bool isFlushRedisplay)
1615 {
1616   #ifdef DEBUG_DO_NOT_BY_ENTER
1617   return;
1618   #endif
1619
1620   if (isEditOperation || !theFeature.get())
1621     return;
1622
1623   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1624   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1625
1626   // 1. change visibility of the object itself, here the presentable object is processed,
1627   // e.g. constraints features
1628   //FeaturePtr aFeature = aFOperation->feature();
1629   std::list<ResultPtr> aResults = theFeature->results();
1630   if (isToDisplay)
1631     theFeature->setDisplayed(true);
1632   else
1633     theFeature->setDisplayed(false);
1634
1635   // change visibility of the object results, e.g. non-constraint features
1636   std::list<ResultPtr>::const_iterator aIt;
1637   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1638     if (isToDisplay) {
1639       (*aIt)->setDisplayed(true);
1640     }
1641     else {
1642       (*aIt)->setDisplayed(false);
1643     }
1644   }
1645   if (isFlushRedisplay)
1646     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1647 }
1648
1649 void PartSet_SketcherMgr::storeSelection(const bool theHighlightedOnly)
1650 {
1651   if (!myCurrentSketch.get())
1652     return;
1653
1654   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1655   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1656   QList<ModuleBase_ViewerPrsPtr> aStoredPrs = aSelect->getHighlighted();
1657
1658   QList<FeaturePtr> aFeatureList;
1659   if (!theHighlightedOnly) {
1660     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(
1661                                                               ModuleBase_ISelection::AllControls);
1662     aStoredPrs.append(aSelected);
1663   }
1664
1665   // 1. it is necessary to save current selection in order to restore it after the features moving
1666   myCurrentSelection.clear();
1667
1668   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = aStoredPrs.begin(),
1669                                                 aLast = aStoredPrs.end();
1670
1671   CompositeFeaturePtr aSketch = activeSketch();
1672   for (; anIt != aLast; anIt++) {
1673     ModuleBase_ViewerPrsPtr aPrs = *anIt;
1674     ObjectPtr anObject = aPrs->object();
1675     if (!anObject.get())
1676       continue;
1677
1678     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1679     FeaturePtr aFeature;
1680     if (aResult.get())
1681       aFeature = ModelAPI_Feature::feature(aResult);
1682     else
1683       aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1684
1685
1686     std::set<AttributePtr> aSelectedAttributes;
1687     std::set<ResultPtr> aSelectedResults;
1688     if (myCurrentSelection.find(aFeature) != myCurrentSelection.end()) {
1689       std::pair<std::set<AttributePtr>, std::set<ResultPtr> > aPair =
1690         myCurrentSelection.find(aFeature).value();
1691       aSelectedAttributes = aPair.first;
1692       aSelectedResults = aPair.second;
1693     }
1694
1695     Handle(SelectMgr_EntityOwner) anOwner = aPrs->owner();
1696     if (aResult.get()) {
1697       getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1698                              aSelectedAttributes, aSelectedResults);
1699     }
1700     else {
1701       std::list<ResultPtr> aResults = aFeature->results();
1702       std::list<ResultPtr>::const_iterator aIt;
1703       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1704         ResultPtr aResult = *aIt;
1705         getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1706                                aSelectedAttributes, aSelectedResults);
1707       }
1708     }
1709     myCurrentSelection[aFeature] = std::make_pair(aSelectedAttributes, aSelectedResults);
1710   }
1711   //qDebug(QString("  storeSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1712 }
1713
1714 void PartSet_SketcherMgr::restoreSelection()
1715 {
1716   if (!myCurrentSketch.get())
1717     return;
1718
1719   //qDebug(QString("restoreSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1720   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1721   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1722   FeatureToSelectionMap::const_iterator aSIt = myCurrentSelection.begin(),
1723                                         aSLast = myCurrentSelection.end();
1724   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1725   anOwnersToSelect.Clear();
1726   for (; aSIt != aSLast; aSIt++) {
1727     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, myCurrentSelection,
1728                         anOwnersToSelect);
1729   }
1730   aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1731 }
1732
1733 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
1734 {
1735   PartSet_Tools::ConstraintVisibleState aType = (PartSet_Tools::ConstraintVisibleState)theType;
1736
1737   updateBySketchParameters(aType, theState);
1738 }
1739
1740 void PartSet_SketcherMgr::updateBySketchParameters(
1741                                    const PartSet_Tools::ConstraintVisibleState& theType,
1742                                    bool theState)
1743 {
1744   if (myCurrentSketch.get() == NULL)
1745     return;
1746
1747   bool aPrevState = myIsConstraintsShown[theType];
1748   myIsConstraintsShown[theType] = theState;
1749
1750   switch (theType) {
1751     case PartSet_Tools::Geometrical:
1752     case PartSet_Tools::Dimensional: {
1753       if (aPrevState != theState) {
1754         ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1755         XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1756         for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1757           FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1758           bool aProcessed = false;
1759           bool aConstraintDisplayed = canDisplayConstraint(aSubFeature, theType, aProcessed);
1760           if (aProcessed)
1761             aSubFeature->setDisplayed(aConstraintDisplayed);
1762         }
1763         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1764       }
1765     }
1766     break;
1767     case PartSet_Tools::Expressions: {
1768       if (aPrevState != theState) {
1769         /// call all sketch features redisplay, the expression state will be corrected in customize
1770         /// of distance presentation
1771         Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1772         PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
1773       }
1774     }
1775     break;
1776   }
1777 }
1778
1779 void PartSet_SketcherMgr::updateSelectionPriority(ObjectPtr theObject,
1780                                                   FeaturePtr theFeature)
1781 {
1782   if (!theObject.get() || !theFeature.get())
1783     return;
1784
1785   AISObjectPtr anAIS = workshop()->displayer()->getAISObject(theObject);
1786   Handle(AIS_InteractiveObject) anAISIO;
1787   if (anAIS.get() != NULL) {
1788     anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1789   }
1790
1791   if (!anAISIO.IsNull()) { // the presentation for the object is visualized
1792     int anAdditionalPriority = 0;
1793     // current feature
1794     std::shared_ptr<SketchPlugin_Feature> aSPFeature =
1795             std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
1796     if (aSPFeature.get() != NULL) {
1797       // 1. Vertices
1798       // 2. Simple segments
1799       // 3. External objects (violet color)
1800       // 4. Auxiliary segments (dotted)
1801       // StdSelect_BRepSelectionTool::Load uses priority calculating:
1802       // Standard_Integer aPriority =
1803       // (thePriority == -1) ? GetStandardPriority (theShape, theType) : thePriority;
1804       // Priority of Vertex is 8, edge(segment) is 7.
1805       // It might be not corrected as provides the condition above.
1806       bool isExternal = aSPFeature->isExternal();
1807       bool isAuxiliary = PartSet_Tools::isAuxiliarySketchEntity(aSPFeature);
1808       // current feature
1809       if (!isExternal && !isAuxiliary)
1810         anAdditionalPriority = 30;
1811       // external feature
1812       if (isExternal)
1813         anAdditionalPriority = 20;
1814       // auxiliary feature
1815       if (isAuxiliary) {
1816         anAdditionalPriority = 10; /// auxiliary objects should have less priority that
1817         // edges/vertices of local selection on not-sketch objects
1818       }
1819       Handle(ModuleBase_ResultPrs) aResult = Handle(ModuleBase_ResultPrs)::DownCast(anAISIO);
1820       if (!aResult.IsNull()) {
1821         aResult->setAdditionalSelectionPriority(anAdditionalPriority);
1822       }
1823     }
1824   }
1825 }
1826
1827 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
1828 {
1829   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1830   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1831   return aConnector->workshop();
1832 }
1833
1834 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1835 {
1836   return workshop()->operationMgr();
1837 }
1838