Salome HOME
03d2cb29865f33adaa6cc572f731e14499a0d09a
[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_Module.h"
9 #include "PartSet_WidgetPoint2d.h"
10 #include "PartSet_WidgetPoint2dDistance.h"
11 #include "PartSet_Tools.h"
12 #include "PartSet_WidgetSketchLabel.h"
13
14 #include <XGUI_ModuleConnector.h>
15 #include <XGUI_Displayer.h>
16 #include <XGUI_Workshop.h>
17 #include <XGUI_ContextMenuMgr.h>
18 #include <XGUI_Selection.h>
19 #include <XGUI_SelectionMgr.h>
20 #include <XGUI_ModuleConnector.h>
21 #include <XGUI_PropertyPanel.h>
22 #include <XGUI_ViewerProxy.h>
23 #include <XGUI_OperationMgr.h>
24
25 #include <ModuleBase_IPropertyPanel.h>
26 #include <ModuleBase_ISelection.h>
27 #include <ModuleBase_IViewer.h>
28 #include <ModuleBase_IWorkshop.h>
29 #include <ModuleBase_IViewWindow.h>
30 #include <ModuleBase_ModelWidget.h>
31 #include <ModuleBase_Operation.h>
32 #include <ModuleBase_OperationFeature.h>
33 #include <ModuleBase_Operation.h>
34 #include <ModuleBase_WidgetEditor.h>
35
36 #include <GeomDataAPI_Point2D.h>
37
38 #include <Events_Loop.h>
39
40 #include <SketchPlugin_Line.h>
41 #include <SketchPlugin_Sketch.h>
42 #include <SketchPlugin_Point.h>
43 #include <SketchPlugin_Arc.h>
44 #include <SketchPlugin_Circle.h>
45 #include <SketchPlugin_ConstraintLength.h>
46 #include <SketchPlugin_ConstraintDistance.h>
47 #include <SketchPlugin_ConstraintParallel.h>
48 #include <SketchPlugin_ConstraintPerpendicular.h>
49 #include <SketchPlugin_ConstraintRadius.h>
50 #include <SketchPlugin_ConstraintRigid.h>
51 #include <SketchPlugin_ConstraintHorizontal.h>
52 #include <SketchPlugin_ConstraintVertical.h>
53 #include <SketchPlugin_ConstraintEqual.h>
54 #include <SketchPlugin_ConstraintTangent.h>
55 #include <SketchPlugin_ConstraintCoincidence.h>
56 #include <SketchPlugin_ConstraintFillet.h>
57 #include <SketchPlugin_ConstraintMirror.h>
58 #include <SketchPlugin_ConstraintAngle.h>
59 #include <SketchPlugin_MultiRotation.h>
60 #include <SketchPlugin_MultiTranslation.h>
61
62 #include <SketcherPrs_Tools.h>
63
64 #include <SelectMgr_IndexedMapOfOwner.hxx>
65 #include <StdSelect_BRepOwner.hxx>
66
67 //#include <AIS_DimensionSelectionMode.hxx>
68 #include <AIS_Shape.hxx>
69
70 #include <ModelAPI_Events.h>
71 #include <ModelAPI_Session.h>
72 #include <ModelAPI_AttributeString.h>
73
74 #include <QMouseEvent>
75 #include <QApplication>
76
77 //#define DEBUG_DO_NOT_BY_ENTER
78
79 /// Returns list of unique objects by sum of objects from List1 and List2
80 /*QList<ModuleBase_ViewerPrs> getSumList(const QList<ModuleBase_ViewerPrs>& theList1,
81                                        const QList<ModuleBase_ViewerPrs>& theList2)
82 {
83   QList<ModuleBase_ViewerPrs> aRes;
84   foreach (ModuleBase_ViewerPrs aPrs, theList1) {
85     if (!aRes.contains(aPrs))
86       aRes.append(aPrs);
87   }
88   foreach (ModuleBase_ViewerPrs aPrs, theList2) {
89     if (!aRes.contains(aPrs))
90       aRes.append(aPrs);
91   }
92   return aRes;
93 }*/
94
95 // Fills the list of features the list of selected presentations.
96 // \param theList a list of selected presentations
97 // \param theSketch a sketch to project a vertex shape of a presentation to the plane
98 // and find the corresponded attribute
99 // \param theFeatureList  an output list of features
100 void fillFeatureList(const QList<ModuleBase_ViewerPrs>& theList,
101                      const FeaturePtr theSketch,
102                      QList<FeaturePtr>& theFeatureList)
103 {
104   QList<ModuleBase_ViewerPrs> aRes;
105
106   QList<ModuleBase_ViewerPrs>::const_iterator anIt = theList.begin(),
107                                               aLast = theList.end();
108   for (; anIt != aLast; anIt++)
109   {
110     ModuleBase_ViewerPrs aPrs = *anIt;
111     FeaturePtr aFeature = ModelAPI_Feature::feature(aPrs.object());
112     if (aFeature.get()  && !theFeatureList.contains(aFeature))
113       theFeatureList.append(aFeature);
114   }
115 }
116
117 /// Fills attribute and result lists by the selected owner. In case if the attribute is found,
118 /// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge, put the function
119 /// result as is to the list of results.
120 /// \param theOwner a viewer selected owner
121 /// \param theFeature a feature, where the attribute is searched
122 /// \param theSketch a current sketch
123 /// \param theSelectedAttribute an output list of attributes
124 /// \param theSelectedResults an output list of edge results
125 void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
126                             const FeaturePtr& theFeature, const FeaturePtr& theSketch,
127                             const ResultPtr& theResult,
128                             std::set<AttributePtr>& aSelectedAttributes,
129                             std::set<ResultPtr>& aSelectedResults)
130 {
131   Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(theOwner);
132   if (aBRepOwner.IsNull())
133     return;
134   Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(
135                                                                     aBRepOwner->Selectable());
136   if (aBRepOwner->HasShape()) {
137     const TopoDS_Shape& aShape = aBRepOwner->Shape();
138     TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
139     if (aShapeType == TopAbs_VERTEX) {
140       AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature,
141                                                                     aShape, theSketch);
142       if (aPntAttr.get() != NULL)
143         aSelectedAttributes.insert(aPntAttr);
144     }
145     else if (aShapeType == TopAbs_EDGE &&
146              aSelectedResults.find(theResult) == aSelectedResults.end()) {
147       aSelectedResults.insert(theResult);
148     }
149   }
150 }
151
152 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
153   : QObject(theModule), myModule(theModule), myIsDragging(false), myDragDone(false),
154     myIsMouseOverWindow(false),
155     myIsMouseOverViewProcessed(true), myPreviousUpdateViewerEnabled(true),
156     myIsPopupMenuActive(false), myIsConstraintsShown(true)
157 {
158   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
159   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
160
161   myPreviousDrawModeEnabled = true;//aViewer->isSelectionEnabled();
162
163   connect(aViewer, SIGNAL(mousePress(ModuleBase_IViewWindow*, QMouseEvent*)),
164           this, SLOT(onMousePressed(ModuleBase_IViewWindow*, QMouseEvent*)));
165
166   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)),
167           this, SLOT(onMouseReleased(ModuleBase_IViewWindow*, QMouseEvent*)));
168
169   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
170           this, SLOT(onMouseMoved(ModuleBase_IViewWindow*, QMouseEvent*)));
171
172   connect(aViewer, SIGNAL(mouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)),
173           this, SLOT(onMouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)));
174
175   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
176   XGUI_Workshop* aWorkshop = aConnector->workshop();
177   connect(aWorkshop, SIGNAL(applicationStarted()), this, SLOT(onApplicationStarted()));
178 }
179
180 PartSet_SketcherMgr::~PartSet_SketcherMgr()
181 {
182   if (!myPlaneFilter.IsNull())
183     myPlaneFilter.Nullify();
184 }
185
186 void PartSet_SketcherMgr::onEnterViewPort()
187 {
188   // 1. if the mouse over window, update the next flag. Do not perform update visibility of
189   // created feature because it should be done in onMouseMove(). Some widgets watch
190   // the mouse move and use the cursor position to update own values. If the presentaion is
191   // redisplayed before this update, the feature presentation jumps from reset value to current.
192   myIsMouseOverWindow = true;
193
194   #ifdef DEBUG_DO_NOT_BY_ENTER
195   return;
196   #endif
197
198   if (!isNestedCreateOperation(getCurrentOperation()))
199     return;
200
201   QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));//QIcon(":pictures/button_plus.png").pixmap(20,20)));
202
203   operationMgr()->onValidateOperation();
204
205   // we need change displayed state of the current operation feature
206   // if the feature is presentable, e.g. distance construction. It has no results, so workshop does
207   // not accept a signal about the result created. Nothing is shown until mouse is moved out/in view
208   // port. If the isDisplayed flag is true, the presentable feature is displayed as soon as the
209   // presentation becomes valid and redisplay happens
210   //ModuleBase_Operation* aOperation = getCurrentOperation();
211   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
212                                                                            (getCurrentOperation());
213   if (aFOperation) {
214     FeaturePtr aFeature = aFOperation->feature();
215     if (aFeature.get() && aFeature->data()->isValid()) {
216       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature), false);
217     }
218   }
219 }
220
221 void PartSet_SketcherMgr::onLeaveViewPort()
222 {
223   myIsMouseOverViewProcessed = false;
224   myIsMouseOverWindow = false;
225   // it is important to validate operation here only if sketch entity create operation is active
226   // because at this operation we reacts to the mouse leave/enter view port
227   //operationMgr()->onValidateOperation();
228
229   #ifdef DEBUG_DO_NOT_BY_ENTER
230   return;
231   #endif
232
233   if (!isNestedCreateOperation(getCurrentOperation()))
234     return;
235
236   QApplication::restoreOverrideCursor();
237
238   // the method should be performed if the popup menu is called,
239   // the reset of the current widget should not happen
240   if (myIsPopupMenuActive)
241     return;
242
243   operationMgr()->onValidateOperation();
244
245   // 2. if the mouse IS NOT over window, reset the active widget value and hide the presentation
246   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
247   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
248   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
249   // disable the viewer update in order to avoid visualization of redisplayed feature in viewer
250   // obtained after reset value
251   bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
252   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
253   if (anActiveWidget)
254     anActiveWidget->reset();
255   aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
256
257   // hides the presentation of the current operation feature
258   // the feature is to be erased here, but it is correct to call canDisplayObject because
259   // there can be additional check (e.g. editor widget in distance constraint)
260   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
261                                                                            (getCurrentOperation());
262   if (aFOperation) {
263     FeaturePtr aFeature = aFOperation->feature();
264     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
265   }
266 }
267
268 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
269 {
270   if (isNestedCreateOperation(getCurrentOperation()))
271     return;
272   // it is necessary to save current selection in order to restore it after the values are modifed
273   storeSelection();
274
275   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
276   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
277   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
278   myPreviousUpdateViewerEnabled = aDisplayer->enableUpdateViewer(false);
279 }
280
281 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
282 {
283   if (isNestedCreateOperation(getCurrentOperation()))
284     return;
285   // it is necessary to restore current selection in order to restore it after the values are modified
286   restoreSelection();
287   myCurrentSelection.clear();
288
289   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
290   // viewer happens by deselect/select the modified objects. The flag should be restored after
291   // the selection processing. The update viewer should be also called.
292   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
293   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
294   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
295   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
296   aDisplayer->updateViewer();
297 }
298
299 void PartSet_SketcherMgr::onValuesChangedInPropertyPanel()
300 {
301   if (!isNestedCreateOperation(getCurrentOperation()))
302     return;
303
304   operationMgr()->onValidateOperation();
305   // the feature is to be erased here, but it is correct to call canDisplayObject because
306   // there can be additional check (e.g. editor widget in distance constraint)
307   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
308                                                                            (getCurrentOperation());
309   if (aFOperation) {
310     FeaturePtr aFeature = aFOperation->feature();
311     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
312   }
313 }
314
315 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
316 {
317   get2dPoint(theWnd, theEvent, myClickedPoint);
318
319   if (!(theEvent->buttons() & Qt::LeftButton))
320     return;
321
322   // Clear dragging mode
323   myIsDragging = false;
324
325   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
326   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
327   if (!aViewer->canDragByMouse())
328     return;
329
330   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
331                                                                (getCurrentOperation());
332   if (!aFOperation)
333     return;
334
335   if (aFOperation->isEditOperation()) {
336     // If the current widget is a selector, do nothing, it processes the mouse press
337     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
338     if(anActiveWidget && anActiveWidget->isViewerSelector()) {
339       return;
340     }
341   }
342
343   // Use only for sketch operations
344   if (myCurrentSketch) {
345     if (!PartSet_Tools::sketchPlane(myCurrentSketch))
346       return;
347
348     bool isSketcher = isSketchOperation(aFOperation);
349     bool isSketchOpe = isNestedSketchOperation(aFOperation);
350
351     // Avoid non-sketch operations
352     if ((!isSketchOpe) && (!isSketcher))
353       return;
354
355     bool isEditing = aFOperation->isEditOperation();
356
357     // Ignore creation sketch operation
358     if ((!isSketcher) && (!isEditing))
359       return;
360
361     Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
362     if (!aContext.IsNull()) {
363       // MoveTo in order to highlight current object
364       aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
365     }
366     // Remember highlighted objects for editing
367     ModuleBase_ISelection* aSelect = aWorkshop->selection();
368
369     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
370     storeSelection(!aHasShift);
371
372     if (myCurrentSelection.empty()) {
373       if (isSketchOpe && (!isSketcher))
374         // commit previous operation
375         if (!aFOperation->commit())
376           aFOperation->abort();
377       return;
378     }
379     // Init flyout point for radius rotation
380     FeaturePtr aFeature = myCurrentSelection.begin().key();
381
382     if (isSketcher) {
383       myIsDragging = true;
384       get2dPoint(theWnd, theEvent, myCurrentPoint);
385       myDragDone = false;
386       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
387       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
388       launchEditing();
389       if (aFeature.get() != NULL) {
390         std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
391                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
392       if (aSPFeature.get() && aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID()) {
393           DataPtr aData = aSPFeature->data();
394           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
395           std::shared_ptr<GeomDataAPI_Point2D> aFPAttr = 
396             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
397           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
398         }
399       }
400     } else if (isSketchOpe && isEditing) {
401       // If selected another object commit current result
402       aFOperation->commit();
403
404       myIsDragging = true;
405       get2dPoint(theWnd, theEvent, myCurrentPoint);
406       myDragDone = false;
407       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
408       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
409
410       // This is necessary in order to finalize previous operation
411       QApplication::processEvents();
412       launchEditing();
413     }
414   }
415 }
416
417 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
418 {
419   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
420   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
421   if (!aViewer->canDragByMouse())
422     return;
423   ModuleBase_Operation* aOp = getCurrentOperation();
424   if (aOp) {
425     if (isNestedSketchOperation(aOp)) {
426       get2dPoint(theWnd, theEvent, myClickedPoint);
427
428       // Only for sketcher operations
429       if (myIsDragging) {
430         if (myDragDone) {
431           //aOp->commit();
432           myCurrentSelection.clear();
433           /*Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
434           if (!aContext.IsNull()) {
435           // Reselect edited object
436           aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
437           if (theEvent->modifiers() & Qt::ShiftModifier)
438             aContext->ShiftSelect();
439           else
440             aContext->Select();
441           */
442         }
443       }
444     }
445   }
446       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
447   aWorkshop->viewer()->enableDrawMode(myPreviousDrawModeEnabled);
448   //aWorkshop->viewer()->enableSelection(myPreviousDrawModeEnabled);
449   myIsDragging = false;
450 }
451
452 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
453 {
454   if (isNestedCreateOperation(getCurrentOperation()) && !myIsMouseOverViewProcessed) {
455     myIsMouseOverViewProcessed = true;
456     // 1. perform the widget mouse move functionality and display the presentation
457     // the mouse move should be processed in the widget, if it can in order to visualize correct
458     // presentation. These widgets correct the feature attribute according to the mouse position
459     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
460     PartSet_WidgetPoint2D* aPoint2DWdg = dynamic_cast<PartSet_WidgetPoint2D*>(anActiveWidget);
461     if (aPoint2DWdg) {
462       aPoint2DWdg->onMouseMove(theWnd, theEvent);
463     }
464     PartSet_WidgetPoint2dDistance* aDistanceWdg = dynamic_cast<PartSet_WidgetPoint2dDistance*>
465                                                                 (anActiveWidget);
466     if (aDistanceWdg) {
467       aDistanceWdg->onMouseMove(theWnd, theEvent);
468     }
469     // the feature is to be erased here, but it is correct to call canDisplayObject because
470     // there can be additional check (e.g. editor widget in distance constraint)
471     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
472                                                                              (getCurrentOperation());
473     if (aFOperation) {
474       FeaturePtr aFeature = aFOperation->feature();
475       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
476     }
477   }
478
479   myClickedPoint.clear();
480
481   if (myIsDragging) {
482     // 1. the current selection is saved in the mouse press method in order to restore it after moving
483     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
484     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
485     // deselected). This flag should be restored in the slot, processed the mouse release signal.
486
487     // TODO: Has to be commented out when SALOME patch on draw mode become avialable
488     //ModuleBase_IViewer* aViewer = myModule->workshop()->viewer();
489     //aViewer->enableSelection(false);
490
491     ModuleBase_Operation* aCurrentOperation = getCurrentOperation();
492     if (!aCurrentOperation)
493       return;
494     if (isSketchOperation(aCurrentOperation))
495       return; // No edit operation activated
496
497     Handle(V3d_View) aView = theWnd->v3dView();
498     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
499     double aX, aY;
500     PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, aY);
501     double dX =  aX - myCurrentPoint.myCurX;
502     double dY =  aY - myCurrentPoint.myCurY;
503
504     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
505     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
506     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
507     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
508     // viewer happens by deselect/select the modified objects. The flag should be restored after
509     // the selection processing. The update viewer should be also called.
510     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
511
512     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
513     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
514     FeatureToSelectionMap::const_iterator anIt = myCurrentSelection.begin(),
515                                           aLast = myCurrentSelection.end();
516     // 4. the features and attributes modification(move)
517     bool isModified = false;
518     for (; anIt != aLast; anIt++) {
519       FeaturePtr aFeature = anIt.key();
520
521       std::set<AttributePtr> anAttributes = anIt.value().first;
522       // Process selection by attribute: the priority to the attribute
523       if (!anAttributes.empty()) {
524         std::set<AttributePtr>::const_iterator anAttIt = anAttributes.begin(),
525                                                anAttLast = anAttributes.end();
526         for (; anAttIt != anAttLast; anAttIt++) {
527           AttributePtr anAttr = *anAttIt;
528           if (anAttr.get() == NULL)
529             continue;
530           std::string aAttrId = anAttr->id();
531           DataPtr aData = aFeature->data();
532           if (aData->isValid()) {
533             std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
534               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
535             if (aPoint.get() != NULL) {
536               bool isImmutable = aPoint->setImmutable(true);
537               aPoint->move(dX, dY);
538               isModified = true;
539               ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
540               aPoint->setImmutable(isImmutable);
541             }
542           }
543         }
544       } else {
545         // Process selection by feature
546         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
547           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
548         if (aSketchFeature) {
549           aSketchFeature->move(dX, dY);
550           isModified = true;
551           ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
552         }
553       }
554     }
555     // the modified state of the current operation should be updated if there are features, which
556     // were changed here
557     if (isModified) {
558       aCurrentOperation->onValuesChanged();
559     }
560     Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
561     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
562
563     // 5. it is necessary to save current selection in order to restore it after the features moving
564     restoreSelection();
565     // 6. restore the update viewer flag and call this update
566     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
567     aDisplayer->updateViewer();
568
569     myDragDone = true;
570     myCurrentPoint.setValue(aX, aY);
571   }
572 }
573
574 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
575 {
576   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
577                                                                (getCurrentOperation());
578   if (aFOperation && aFOperation->isEditOperation()) {
579     std::string aId = aFOperation->id().toStdString();
580     if (isDistanceOperation(aFOperation))
581     {
582       // Activate dimension value editing on double click
583       ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
584       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
585       // Find corresponded widget to activate value editing
586       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
587         if (aWgt->attributeID() == "ConstraintValue") {
588           aWgt->focusTo();
589           return;
590         }
591       }
592     }
593   }
594 }
595
596 void PartSet_SketcherMgr::onApplicationStarted()
597 {
598   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
599   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
600   XGUI_Workshop* aWorkshop = aConnector->workshop();
601   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
602   if (aPropertyPanel) {
603     connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
604             this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
605   }
606
607   XGUI_ViewerProxy* aViewerProxy = aWorkshop->viewer();
608   connect(aViewerProxy, SIGNAL(enterViewPort()), this, SLOT(onEnterViewPort()));
609   connect(aViewerProxy, SIGNAL(leaveViewPort()), this, SLOT(onLeaveViewPort()));
610
611   XGUI_ContextMenuMgr* aContextMenuMgr = aWorkshop->contextMenuMgr();
612   connect(aContextMenuMgr, SIGNAL(beforeContextMenu()), this, SLOT(onBeforeContextMenu()));
613   connect(aContextMenuMgr, SIGNAL(afterContextMenu()), this, SLOT(onAfterContextMenu()));
614 }
615
616 void PartSet_SketcherMgr::onBeforeWidgetActivated(ModuleBase_ModelWidget* theWidget)
617 {
618   if (!myClickedPoint.myIsInitialized)
619     return;
620
621   ModuleBase_Operation* aOperation = getCurrentOperation();
622   // the distance constraint feature should not use the clickedd point
623   // this is workaround in order to don't throw down the flyout point value,
624   // set by execute() method of these type of features
625   if (isDistanceOperation(aOperation))
626     return;
627
628   PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(theWidget);
629   if (aPnt2dWgt) {
630     aPnt2dWgt->setPoint(myClickedPoint.myCurX, myClickedPoint.myCurY);
631   }
632 }
633
634 void PartSet_SketcherMgr::onBeforeContextMenu()
635 {
636   myIsPopupMenuActive = true;
637 }
638
639 void PartSet_SketcherMgr::onAfterContextMenu()
640 {
641   myIsPopupMenuActive = false;
642 }
643
644 void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent, 
645                                      Point& thePoint)
646 {
647   Handle(V3d_View) aView = theWnd->v3dView();
648   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
649   double aX, anY;
650   PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, anY);
651   thePoint.setValue(aX, anY);
652 }
653
654 void PartSet_SketcherMgr::launchEditing()
655 {
656   if (!myCurrentSelection.empty()) {
657     FeaturePtr aFeature = myCurrentSelection.begin().key();
658     std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
659               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
660     if (aSPFeature) {
661       myModule->editFeature(aSPFeature);
662     }
663   }
664 }
665
666 bool PartSet_SketcherMgr::sketchSolverError()
667 {
668   bool anError = false;
669   CompositeFeaturePtr aSketch = activeSketch();
670   if (aSketch.get()) {
671     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
672     anError = !aAttributeString->value().empty();
673   }
674   return anError;
675 }
676
677 QString PartSet_SketcherMgr::getFeatureError(const FeaturePtr& theFeature)
678 {
679   QString anError = "";
680   if (!theFeature.get() || !theFeature->data()->isValid())
681     return anError;
682
683   CompositeFeaturePtr aSketch = activeSketch();
684   if (aSketch.get() && aSketch == theFeature) {
685     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
686     anError = aAttributeString->value().c_str();
687   }
688   else {
689     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
690     if (anActiveWidget) {
691       ModuleBase_ModelWidget::ValueState aState = anActiveWidget->getValueState();
692       if (aState != ModuleBase_ModelWidget::Stored) {
693         AttributePtr anAttr = anActiveWidget->feature()->attribute(anActiveWidget->attributeID());
694         if (anAttr.get()) {
695           QString anAttributeName = anAttr->id().c_str();
696           switch (aState) {
697             case ModuleBase_ModelWidget::ModifiedInPP:
698               anError = "Attribute \"" + anAttributeName +
699                         "\" modification is not applyed. Please click \"Enter\" or \"Tab\".";
700               break;
701             case ModuleBase_ModelWidget::ModifiedInViewer:
702               anError = "Attribute \"" + anAttributeName +
703                         "\" is locked by modification value in the viewer.";
704               break;
705             case ModuleBase_ModelWidget::Reset:
706               anError = "Attribute \"" + anAttributeName + "\" is not initialized.";
707               break;
708           }
709         }
710       }
711     }
712   }
713   return anError;
714 }
715
716 const QStringList& PartSet_SketcherMgr::sketchOperationIdList()
717 {
718   static QStringList aIds;
719   if (aIds.size() == 0) {
720     aIds << SketchPlugin_Line::ID().c_str();
721     aIds << SketchPlugin_Point::ID().c_str();
722     aIds << SketchPlugin_Arc::ID().c_str();
723     aIds << SketchPlugin_Circle::ID().c_str();
724     aIds << SketchPlugin_ConstraintFillet::ID().c_str();
725     aIds.append(constraintsIdList());
726   }
727   return aIds;
728 }
729
730 const QStringList& PartSet_SketcherMgr::constraintsIdList()
731 {
732   static QStringList aIds;
733   if (aIds.size() == 0) {
734     aIds << SketchPlugin_ConstraintLength::ID().c_str();
735     aIds << SketchPlugin_ConstraintDistance::ID().c_str();
736     aIds << SketchPlugin_ConstraintRigid::ID().c_str();
737     aIds << SketchPlugin_ConstraintRadius::ID().c_str();
738     aIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
739     aIds << SketchPlugin_ConstraintParallel::ID().c_str();
740     aIds << SketchPlugin_ConstraintHorizontal::ID().c_str();
741     aIds << SketchPlugin_ConstraintVertical::ID().c_str();
742     aIds << SketchPlugin_ConstraintEqual::ID().c_str();
743     aIds << SketchPlugin_ConstraintTangent::ID().c_str();
744     aIds << SketchPlugin_ConstraintCoincidence::ID().c_str();
745     aIds << SketchPlugin_ConstraintMirror::ID().c_str();
746     aIds << SketchPlugin_ConstraintAngle::ID().c_str();
747     aIds << SketchPlugin_MultiRotation::ID().c_str();
748     aIds << SketchPlugin_MultiTranslation::ID().c_str();
749   }
750   return aIds;
751 }
752
753 void PartSet_SketcherMgr::sketchSelectionModes(QIntList& theModes)
754 {
755   theModes.clear();
756
757   theModes.append(SketcherPrs_Tools::Sel_Dimension_Text);
758   theModes.append(SketcherPrs_Tools::Sel_Dimension_Line);
759   theModes.append(SketcherPrs_Tools::Sel_Constraint);
760   theModes.append(TopAbs_VERTEX);
761   theModes.append(TopAbs_EDGE);
762 }
763
764 bool PartSet_SketcherMgr::isSketchOperation(ModuleBase_Operation* theOperation)
765 {
766   return theOperation && theOperation->id().toStdString() == SketchPlugin_Sketch::ID();
767 }
768
769 bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation)
770 {
771   return theOperation &&
772          PartSet_SketcherMgr::sketchOperationIdList().contains(theOperation->id());
773 }
774
775 bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation)
776 {
777   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
778                                                                (theOperation);
779   return aFOperation && !aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
780 }
781
782 bool PartSet_SketcherMgr::isEntity(const std::string& theId)
783 {
784   return (theId == SketchPlugin_Line::ID()) ||
785          (theId == SketchPlugin_Point::ID()) ||
786          (theId == SketchPlugin_Arc::ID()) ||
787          (theId == SketchPlugin_Circle::ID());
788 }
789
790 bool PartSet_SketcherMgr::isDistanceOperation(ModuleBase_Operation* theOperation)
791 {
792   std::string aId = theOperation ? theOperation->id().toStdString() : "";
793
794   return (aId == SketchPlugin_ConstraintLength::ID()) ||
795          (aId == SketchPlugin_ConstraintDistance::ID()) ||
796          (aId == SketchPlugin_ConstraintRadius::ID()) ||
797          (aId == SketchPlugin_ConstraintAngle::ID());
798 }
799
800 void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
801 {
802   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
803                                                                (getCurrentOperation());
804   if (!aFOperation)
805     return;
806
807   myModule->onViewTransformed();
808
809   // Display all sketcher sub-Objects
810   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFOperation->feature());
811   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
812
813   // Hide sketcher result
814   std::list<ResultPtr> aResults = myCurrentSketch->results();
815   std::list<ResultPtr>::const_iterator aIt;
816   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
817     (*aIt)->setDisplayed(false);
818   }
819   myCurrentSketch->setDisplayed(false);
820
821   // Display sketcher objects
822   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
823     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
824     std::list<ResultPtr> aResults = aFeature->results();
825     std::list<ResultPtr>::const_iterator aIt;
826     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
827       (*aIt)->setDisplayed(true);
828     }
829     aFeature->setDisplayed(true);
830   }
831
832   if (myPlaneFilter.IsNull()) 
833     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
834
835   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
836
837   bool aHasPlane = false;
838   std::shared_ptr<GeomAPI_Pln> aPln;
839   if (aFOperation->isEditOperation()) {
840     // If it is editing of sketch then it means that plane is already defined
841     aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
842     if (aPln.get())
843       aHasPlane = true;
844   }
845   myPlaneFilter->setPlane(aPln);
846
847   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
848   // all sketch objects should be activated in the sketch selection modes by edit operation start
849   // in case of creation operation, there is an active widget, which activates own selection mode
850   if (aFOperation->isEditOperation() && aHasPlane)
851     aConnector->activateModuleSelectionModes();
852 }
853
854 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
855 {
856   myIsMouseOverWindow = false;
857   myIsConstraintsShown = true;
858
859   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
860
861   DataPtr aData = myCurrentSketch->data();
862   if (!aData->isValid()) {
863     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
864     // The sketch was aborted
865     myCurrentSketch = CompositeFeaturePtr();
866     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
867
868     // Erase all sketcher objects
869     QStringList aSketchIds = sketchOperationIdList();
870     QObjectPtrList aObjects = aDisplayer->displayedObjects();
871     foreach (ObjectPtr aObj, aObjects) {
872       DataPtr aObjData = aObj->data();
873       if (!aObjData->isValid())
874         aObj->setDisplayed(false);
875     }
876   }
877   else {
878     // Hide all sketcher sub-Objects
879     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
880       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
881       std::list<ResultPtr> aResults = aFeature->results();
882       std::list<ResultPtr>::const_iterator aIt;
883       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
884         (*aIt)->setDisplayed(false);
885       }
886       aFeature->setDisplayed(false);
887     }
888     // Display sketcher result
889     std::list<ResultPtr> aResults = myCurrentSketch->results();
890     std::list<ResultPtr>::const_iterator aIt;
891     Events_Loop* aLoop = Events_Loop::loop();
892     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
893
894     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
895                                                                            (theOperation);
896     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
897       if (!aFOperation->isDisplayedOnStart(*aIt)) {
898         (*aIt)->setDisplayed(true);
899         // this display event is needed because sketch already may have "displayed" state,
900         // but not displayed while it is still active (issue 613, abort of existing sketch)
901         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
902       }
903     }
904     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
905       myCurrentSketch->setDisplayed(true);
906     
907     myCurrentSketch = CompositeFeaturePtr();
908     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
909
910     Events_Loop::loop()->flush(aDispEvent);
911   }
912   // restore the module selection modes, which were changed on startSketch
913   aConnector->activateModuleSelectionModes();
914 }
915
916 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
917 {
918   if (isNestedCreateOperation(theOperation) && myIsMouseOverWindow)
919     QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));//QIcon(":pictures/button_plus.png").pixmap(20,20)));
920 }
921
922 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOp)
923 {
924   myIsMouseOverViewProcessed = true;
925   operationMgr()->onValidateOperation();
926   if (isNestedCreateOperation(theOp))
927     QApplication::restoreOverrideCursor();
928 }
929
930 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
931 {
932   if (isNestedCreateOperation(theOperation)) {
933     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
934                                                                              (theOperation);
935     if (aFOperation) {
936       FeaturePtr aFeature = aFOperation->feature();
937       // it is necessary to check the the feature data validity because
938       // some kind of features are removed by an operation commit(the macro state of a feature)
939       if (aFeature.get() && aFeature->data()->isValid()) {
940         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
941       }
942     }
943   }
944 }
945
946 bool PartSet_SketcherMgr::canUndo() const
947 {
948   return isNestedCreateOperation(getCurrentOperation());
949 }
950
951 bool PartSet_SketcherMgr::canRedo() const
952 {
953   return isNestedCreateOperation(getCurrentOperation());
954 }
955
956 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
957 {
958   bool aCanErase = true;
959   // when the sketch operation is active, results of sketch sub-feature can not be hidden
960   if (myCurrentSketch.get()) {
961     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
962     if (aResult.get()) {
963       // Display sketcher objects
964       for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
965
966         FeaturePtr aFeature = myCurrentSketch->subFeature(i);
967         std::list<ResultPtr> aResults = aFeature->results();
968         std::list<ResultPtr>::const_iterator anIt;
969         for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
970           aCanErase = *anIt != aResult;
971         }
972       }
973     }
974   }
975   return aCanErase;
976 }
977
978 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
979 {
980   bool aCanDisplay = true;
981
982   bool aHasActiveSketch = activeSketch().get() != NULL;
983   if (aHasActiveSketch) {
984     // 1. the sketch feature should not be displayed during the sketch active operation
985     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch 
986     // nested features can be visualized
987     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
988     if (aFeature.get() != NULL && aFeature == activeSketch()) {
989       aCanDisplay = false;
990     }
991   }
992   else { // there are no an active sketch
993     // 2. sketch sub-features should not be visualized if the sketch operation is not active
994     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
995     if (aFeature.get() != NULL) {
996       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
997                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
998       if (aSketchFeature.get()) {
999         aCanDisplay = false;
1000       }
1001     }
1002   }
1003
1004   // 3. the method should not filter the objects, which are not related to the current operation.
1005   // The object is filtered just if it is a current operation feature or this feature result
1006   bool isObjectFound = false;
1007   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1008                                                                (getCurrentOperation());
1009   if (aFOperation) {
1010     FeaturePtr aFeature = aFOperation->feature();
1011     if (aFeature.get()) {
1012       std::list<ResultPtr> aResults = aFeature->results();
1013       if (theObject == aFeature)
1014         isObjectFound = true;
1015       else {
1016         std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1017         for (; anIt != aLast && !isObjectFound; anIt++) {
1018           isObjectFound = *anIt == theObject;
1019         }
1020       }
1021     }
1022   }
1023   if (!isObjectFound) 
1024     return aCanDisplay;
1025   
1026   // 4. For created nested feature operation do not display the created feature if
1027   // the mouse curstor leaves the OCC window.
1028   // The correction cases, which ignores this condition:
1029   // a. the property panel values modification
1030   // b. the popup menu activated
1031   // c. widget editor control
1032   #ifndef DEBUG_DO_NOT_BY_ENTER
1033   if (aCanDisplay && isNestedCreateOperation(getCurrentOperation())) {
1034     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1035     ModuleBase_WidgetEditor* anEditorWdg = anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1036     // the active widget editor should not influence here. The presentation should be visible always
1037     // when this widget is active.
1038     if (!anEditorWdg && !myIsPopupMenuActive) {
1039       // during a nested create operation, the feature is redisplayed only if the mouse over view
1040       // of there was a value modified in the property panel after the mouse left the view
1041       aCanDisplay = canDisplayCurrentCreatedFeature();
1042     }
1043   }
1044   #endif
1045   return aCanDisplay;
1046 }
1047
1048 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1049 {
1050   bool aCanDisplay = myIsMouseOverWindow;
1051   if (!aCanDisplay) {
1052     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1053     if (anActiveWidget)
1054       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1055   }
1056   return aCanDisplay;
1057 }
1058
1059 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1060 {
1061   bool isFoundObject = false;
1062
1063   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1064   if (anObjectFeature.get()) {
1065     int aSize = myCurrentSketch->numberOfSubs();
1066     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1067       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1068       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1069     }
1070   }
1071   return isFoundObject;
1072 }
1073
1074 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
1075 {
1076   if (myPlaneFilter.IsNull()) 
1077    myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
1078
1079   myPlaneFilter->setPlane(thePln);
1080 }
1081
1082 void PartSet_SketcherMgr::getCurrentSelection(const FeaturePtr& theFeature,
1083                                               const FeaturePtr& theSketch,
1084                                               ModuleBase_IWorkshop* theWorkshop,
1085                                               FeatureToSelectionMap& theSelection)
1086 {
1087   if (theFeature.get() == NULL)
1088     return;
1089
1090   std::set<AttributePtr> aSelectedAttributes;
1091   std::set<ResultPtr> aSelectedResults;
1092
1093   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1094   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
1095   if (!aContext.IsNull()) {
1096     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1097     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1098
1099     std::list<ResultPtr> aResults = theFeature->results();
1100     std::list<ResultPtr>::const_iterator aIt;
1101     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1102     {
1103       ResultPtr aResult = *aIt;
1104       AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1105       if (aAISObj.get() == NULL)
1106         continue;
1107       Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1108       for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
1109       {
1110         Handle(SelectMgr_EntityOwner) anOwner = aContext->SelectedOwner();
1111         if (anOwner->Selectable() != anAISIO)
1112           continue;
1113         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1114                                aSelectedAttributes, aSelectedResults);
1115       }
1116       for (aContext->InitDetected(); aContext->MoreDetected(); aContext->NextDetected()) {
1117         Handle(SelectMgr_EntityOwner) anOwner = aContext->DetectedOwner();
1118         if (anOwner.IsNull())
1119           continue;
1120         if (anOwner->Selectable() != anAISIO)
1121           continue;
1122         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1123                                aSelectedAttributes, aSelectedResults);
1124       }
1125     }
1126   }
1127   theSelection[theFeature] = std::make_pair(aSelectedAttributes, aSelectedResults);
1128 }
1129
1130 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1131                                              const FeaturePtr& theSketch,
1132                                              ModuleBase_IWorkshop* theWorkshop,
1133                                              const FeatureToSelectionMap& theSelection,
1134                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1135 {
1136   if (theFeature.get() == NULL)
1137     return;
1138
1139   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1140   std::set<AttributePtr> aSelectedAttributes = anIt.value().first;
1141   std::set<ResultPtr> aSelectedResults = anIt.value().second;
1142
1143   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1144
1145   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1146   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1147
1148   // 1. found the feature's owners. Check the AIS objects of the constructions
1149   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1150   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1151     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1152
1153     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1154     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1155     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1156       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1157       if (!anOwner.IsNull())
1158         theOwnersToSelect.Add(anOwner);
1159     }
1160   }
1161
1162   // 2. found the feature results's owners
1163   std::list<ResultPtr> aResults = theFeature->results();
1164   std::list<ResultPtr>::const_iterator aIt;
1165   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1166   {
1167     ResultPtr aResult = *aIt;
1168     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1169     if (aAISObj.get() == NULL)
1170       continue; 
1171     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1172
1173     SelectMgr_IndexedMapOfOwner aSelectedOwners;  
1174     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1175     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1176       Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1177       if ( anOwner.IsNull() || !anOwner->HasShape() )
1178         continue;
1179       const TopoDS_Shape& aShape = anOwner->Shape();
1180       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1181       if (aShapeType == TopAbs_VERTEX) {
1182         AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1183         if (aPntAttr.get() != NULL &&
1184             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end()) {
1185           theOwnersToSelect.Add(anOwner);
1186         }
1187       }
1188       else if (aShapeType == TopAbs_EDGE) {
1189         bool aFound = aSelectedResults.find(aResult) != aSelectedResults.end();
1190         if (aSelectedResults.find(aResult) != aSelectedResults.end() &&
1191             theOwnersToSelect.FindIndex(anOwner) <= 0)
1192           theOwnersToSelect.Add(anOwner);
1193       }
1194     }
1195   }
1196 }
1197
1198 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget, const bool isToConnect)
1199 {
1200   if (isToConnect) {
1201     connect(theWidget, SIGNAL(beforeValuesChanged()),
1202             this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1203     connect(theWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChangedInPropertyPanel()));
1204     connect(theWidget, SIGNAL(afterValuesChanged()),
1205             this, SLOT(onAfterValuesChangedInPropertyPanel()));
1206   }
1207   else {
1208     disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1209                 this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1210     disconnect(theWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChangedInPropertyPanel()));
1211     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1212                 this, SLOT(onAfterValuesChangedInPropertyPanel()));
1213   }
1214 }
1215
1216 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1217 {
1218   return myModule->workshop()->currentOperation();
1219 }
1220
1221 //**************************************************************
1222 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1223 {
1224   ModuleBase_ModelWidget* aWidget = 0;
1225   ModuleBase_Operation* anOperation = getCurrentOperation();
1226   if (anOperation) {
1227     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1228     if (aPanel)
1229       aWidget = aPanel->activeWidget();
1230   }
1231   return aWidget;
1232 }
1233
1234 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1235                                            const bool isEditOperation,
1236                                            const bool isToDisplay,
1237                                            const bool isFlushRedisplay)
1238 {
1239   #ifdef DEBUG_DO_NOT_BY_ENTER
1240   return;
1241   #endif
1242
1243   if (isEditOperation || !theFeature.get())
1244     return;
1245
1246   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1247   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1248
1249   // 1. change visibility of the object itself, here the presentable object is processed,
1250   // e.g. constraints features
1251   //FeaturePtr aFeature = aFOperation->feature();
1252   std::list<ResultPtr> aResults = theFeature->results();
1253   if (isToDisplay)
1254     theFeature->setDisplayed(true);
1255   else
1256     theFeature->setDisplayed(false);
1257
1258   // change visibility of the object results, e.g. non-constraint features
1259   std::list<ResultPtr>::const_iterator aIt;
1260   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1261     if (isToDisplay) {
1262       (*aIt)->setDisplayed(true);
1263     }
1264     else {
1265       (*aIt)->setDisplayed(false);
1266     }
1267   }
1268   if (isFlushRedisplay)
1269     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1270 }
1271
1272 void PartSet_SketcherMgr::storeSelection(const bool theHighlightedOnly)
1273 {
1274   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1275   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1276   QList<ModuleBase_ViewerPrs> aHighlighted = aSelect->getHighlighted();
1277
1278   QList<FeaturePtr> aFeatureList;
1279   if (theHighlightedOnly) {
1280     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1281   }
1282   else {
1283     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1284
1285     QList<ModuleBase_ViewerPrs> aSelected = aSelect->getSelected(ModuleBase_ISelection::AllControls);
1286     fillFeatureList(aSelected, myCurrentSketch, aFeatureList);
1287   }
1288
1289   // 1. it is necessary to save current selection in order to restore it after the features moving
1290   myCurrentSelection.clear();
1291   QList<FeaturePtr>::const_iterator anIt = aFeatureList.begin(), aLast = aFeatureList.end();
1292   for (; anIt != aLast; anIt++) {
1293     getCurrentSelection(*anIt, myCurrentSketch, aWorkshop, myCurrentSelection);
1294   }
1295   //qDebug(QString("  storeSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1296 }
1297
1298 void PartSet_SketcherMgr::restoreSelection()
1299 {
1300   //qDebug(QString("restoreSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1301   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1302   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1303   FeatureToSelectionMap::const_iterator aSIt = myCurrentSelection.begin(),
1304                                         aSLast = myCurrentSelection.end();
1305   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1306   for (; aSIt != aSLast; aSIt++) {
1307     anOwnersToSelect.Clear();
1308     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, myCurrentSelection,
1309                         anOwnersToSelect);
1310     aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1311   }
1312 }
1313
1314 void PartSet_SketcherMgr::onShowConstraintsToggle(bool theOn)
1315 {
1316   if (myIsConstraintsShown == theOn)
1317     return;
1318   if (myCurrentSketch.get() == NULL)
1319     return;
1320
1321   myIsConstraintsShown = theOn;
1322
1323   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1324   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1325
1326   const QStringList& aConstrIds = constraintsIdList();
1327   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1328     FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1329     if (aConstrIds.contains(QString(aSubFeature->getKind().c_str()))) {
1330       if (myIsConstraintsShown) 
1331         aSubFeature->setDisplayed(true);
1332       else
1333         aSubFeature->setDisplayed(false);
1334     }
1335   }
1336   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1337 }
1338
1339 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1340 {
1341   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1342   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1343   XGUI_Workshop* aWorkshop = aConnector->workshop();
1344
1345   return aWorkshop->operationMgr();
1346 }