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