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