Salome HOME
Issue #390 Selection restore problems during edit operation
[modules/shaper.git] / src / PartSet / PartSet_SketcherMgr.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        PartSet_SketcherMgr.cpp
4 // Created:     19 Dec 2014
5 // Author:      Vitaly SMETANNIKOV
6
7 #include "PartSet_SketcherMgr.h"
8 #include "PartSet_Module.h"
9 #include "PartSet_WidgetPoint2d.h"
10 #include "PartSet_WidgetPoint2dDistance.h"
11 #include "PartSet_Tools.h"
12
13 #include <ModuleBase_WidgetEditor.h>
14
15 #include <XGUI_ModuleConnector.h>
16 #include <XGUI_Displayer.h>
17 #include <XGUI_Workshop.h>
18 #include <XGUI_Selection.h>
19 #include <XGUI_SelectionMgr.h>
20 #include <ModuleBase_ModelWidget.h>
21 #include <XGUI_ModuleConnector.h>
22 #include <XGUI_PropertyPanel.h>
23 #include <XGUI_ViewerProxy.h>
24
25 #include <AppElements_MainWindow.h>
26
27 #include <ModuleBase_IViewer.h>
28 #include <ModuleBase_IWorkshop.h>
29 #include <ModuleBase_IViewWindow.h>
30 #include <ModuleBase_Operation.h>
31 #include <ModuleBase_ISelection.h>
32 #include <ModuleBase_IPropertyPanel.h>
33 #include <ModuleBase_Operation.h>
34
35 #include <GeomDataAPI_Point2D.h>
36
37 #include <Events_Loop.h>
38
39 #include <SketchPlugin_Line.h>
40 #include <SketchPlugin_Sketch.h>
41 #include <SketchPlugin_Point.h>
42 #include <SketchPlugin_Arc.h>
43 #include <SketchPlugin_Circle.h>
44 #include <SketchPlugin_ConstraintLength.h>
45 #include <SketchPlugin_ConstraintDistance.h>
46 #include <SketchPlugin_ConstraintParallel.h>
47 #include <SketchPlugin_ConstraintPerpendicular.h>
48 #include <SketchPlugin_ConstraintRadius.h>
49 #include <SketchPlugin_ConstraintRigid.h>
50
51 #include <SelectMgr_IndexedMapOfOwner.hxx>
52 #include <StdSelect_BRepOwner.hxx>
53
54 //#include <AIS_DimensionSelectionMode.hxx>
55 //#include <AIS_Shape.hxx>
56
57 #include <ModelAPI_Events.h>
58
59 #include <QMouseEvent>
60 #include <QApplication>
61
62
63 /// Returns list of unique objects by sum of objects from List1 and List2
64 /*QList<ModuleBase_ViewerPrs> getSumList(const QList<ModuleBase_ViewerPrs>& theList1,
65                                        const QList<ModuleBase_ViewerPrs>& theList2)
66 {
67   QList<ModuleBase_ViewerPrs> aRes;
68   foreach (ModuleBase_ViewerPrs aPrs, theList1) {
69     if (!aRes.contains(aPrs))
70       aRes.append(aPrs);
71   }
72   foreach (ModuleBase_ViewerPrs aPrs, theList2) {
73     if (!aRes.contains(aPrs))
74       aRes.append(aPrs);
75   }
76   return aRes;
77 }*/
78
79 void fillFeature2Attribute(const QList<ModuleBase_ViewerPrs>& theList,
80                            QMap<FeaturePtr, QList<AttributePtr> >& theFeature2AttributeMap,
81                            const FeaturePtr theSketch)
82 {
83   QList<ModuleBase_ViewerPrs> aRes;
84
85   QList<ModuleBase_ViewerPrs>::const_iterator anIt = theList.begin(),
86                                               aLast = theList.end();
87   for (; anIt != aLast; anIt++)
88   {
89     ModuleBase_ViewerPrs aPrs = *anIt;
90     FeaturePtr aFeature = ModelAPI_Feature::feature(aPrs.object());
91     if (aFeature.get() == NULL)
92       continue;
93
94     QList<AttributePtr> anAttributes;
95     if (theFeature2AttributeMap.contains(aFeature)) {
96       anAttributes = theFeature2AttributeMap[aFeature];
97     }
98     AttributePtr anAttr;
99     TopoDS_Shape aShape = aPrs.shape();
100     if (!aShape.IsNull()) {
101       if (aShape.ShapeType() == TopAbs_VERTEX) {
102         anAttr = PartSet_Tools::findAttributeBy2dPoint(aFeature, aShape, theSketch);
103         if (anAttr.get() != NULL && !anAttributes.contains(anAttr))
104           anAttributes.push_back(anAttr);
105       }
106     }
107     theFeature2AttributeMap[aFeature] = anAttributes;
108   }
109 }
110
111
112
113
114 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
115   : QObject(theModule), myModule(theModule), myIsDragging(false), myDragDone(false),
116     myIsPropertyPanelValueChanged(false), myIsMouseOverWindow(false),
117     myIsMouseOverViewProcessed(true), myPreviousUpdateViewerEnabled(true)
118 {
119   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
120   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
121
122   myPreviousSelectionEnabled = true;//aViewer->isSelectionEnabled();
123
124   connect(aViewer, SIGNAL(mousePress(ModuleBase_IViewWindow*, QMouseEvent*)),
125           this, SLOT(onMousePressed(ModuleBase_IViewWindow*, QMouseEvent*)));
126
127   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)),
128           this, SLOT(onMouseReleased(ModuleBase_IViewWindow*, QMouseEvent*)));
129
130   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
131           this, SLOT(onMouseMoved(ModuleBase_IViewWindow*, QMouseEvent*)));
132
133   connect(aViewer, SIGNAL(mouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)),
134           this, SLOT(onMouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)));
135
136   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
137   XGUI_Workshop* aWorkshop = aConnector->workshop();
138   connect(aWorkshop, SIGNAL(applicationStarted()), this, SLOT(onApplicationStarted()));
139 }
140
141 PartSet_SketcherMgr::~PartSet_SketcherMgr()
142 {
143   if (!myPlaneFilter.IsNull())
144     myPlaneFilter.Nullify();
145 }
146
147 void PartSet_SketcherMgr::onEnterViewPort()
148 {
149   if (!isNestedCreateOperation(getCurrentOperation()))
150     return;
151   // 1. if the mouse over window, update the next flag. Do not perform update visibility of
152   // created feature because it should be done in onMouseMove(). Some widgets watch
153   // the mouse move and use the cursor position to update own values. If the presentaion is
154   // redisplayed before this update, the feature presentation jumps from reset value to current.
155   myIsMouseOverWindow = true;
156   myIsPropertyPanelValueChanged = false;
157 }
158
159 void PartSet_SketcherMgr::onLeaveViewPort()
160 {
161   if (!isNestedCreateOperation(getCurrentOperation()))
162     return;
163
164   myIsMouseOverViewProcessed = false;
165   myIsMouseOverWindow = false;
166
167   // 2. if the mouse IS NOT over window, reset the active widget value and hide the presentation
168   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
169   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
170   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
171   // disable the viewer update in order to avoid visualization of redisplayed feature in viewer
172   // obtained after reset value
173   bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
174   ModuleBase_Operation* aOperation = getCurrentOperation();
175   ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
176   ModuleBase_ModelWidget* aActiveWgt = aPanel->activeWidget();
177   if (aActiveWgt) {
178     aActiveWgt->reset();
179   }
180   aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
181
182   // hides the presentation of the current operation feature
183   myIsPropertyPanelValueChanged = false;
184   // the feature is to be erased here, but it is correct to call canDisplayObject because
185   // there can be additional check (e.g. editor widget in distance constraint)
186   visualizeFeature(aOperation, canDisplayObject());
187 }
188
189 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
190 {
191   if (isNestedCreateOperation(getCurrentOperation()))
192     return;
193   storeSelection();
194 }
195
196 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
197 {
198   if (isNestedCreateOperation(getCurrentOperation()))
199     return;
200   restoreSelection();
201 }
202
203 void PartSet_SketcherMgr::onValuesChangedInPropertyPanel()
204 {
205   if (!isNestedCreateOperation(getCurrentOperation()))
206     return;
207
208   // visualize the current operation feature
209   myIsPropertyPanelValueChanged = true;
210   ModuleBase_Operation* aOperation = getCurrentOperation();
211   // the feature is to be erased here, but it is correct to call canDisplayObject because
212   // there can be additional check (e.g. editor widget in distance constraint)
213   visualizeFeature(aOperation, canDisplayObject());
214 }
215
216 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
217 {
218   get2dPoint(theWnd, theEvent, myClickedPoint);
219
220   if (!(theEvent->buttons() & Qt::LeftButton))
221     return;
222
223   // Clear dragging mode
224   myIsDragging = false;
225
226   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
227   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
228   if (!aViewer->canDragByMouse())
229     return;
230
231   ModuleBase_Operation* aOperation = getCurrentOperation();
232   if (aOperation && aOperation->isEditOperation()) {
233     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
234     ModuleBase_ModelWidget* aActiveWgt = aPanel->activeWidget();
235     // If the current widget is a selector, do do nothing, it processes the mouse press
236     if(aActiveWgt && aActiveWgt->isViewerSelector()) {
237       return;
238     }
239   }
240
241   // Use only for sketch operations
242   if (aOperation && myCurrentSketch) {
243     if (!PartSet_Tools::sketchPlane(myCurrentSketch))
244       return;
245
246     bool isSketcher = isSketchOperation(aOperation);
247     bool isSketchOpe = isNestedSketchOperation(aOperation);
248
249     // Avoid non-sketch operations
250     if ((!isSketchOpe) && (!isSketcher))
251       return;
252
253     bool isEditing = aOperation->isEditOperation();
254
255     // Ignore creation sketch operation
256     if ((!isSketcher) && (!isEditing))
257       return;
258
259     // MoveTo in order to highlight current object
260     aViewer->AISContext()->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
261
262     // Remember highlighted objects for editing
263     ModuleBase_ISelection* aSelect = aWorkshop->selection();
264     QList<ModuleBase_ViewerPrs> aHighlighted = aSelect->getHighlighted();
265     QList<ModuleBase_ViewerPrs> aSelected = aSelect->getSelected();
266     myFeature2AttributeMap.clear();
267
268     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
269     if (aHasShift) {
270       fillFeature2Attribute(aHighlighted, myFeature2AttributeMap, myCurrentSketch);
271       fillFeature2Attribute(aSelected, myFeature2AttributeMap, myCurrentSketch);
272     }
273     else {
274       fillFeature2Attribute(aHighlighted, myFeature2AttributeMap, myCurrentSketch);
275     }
276
277     if (myFeature2AttributeMap.empty()) {
278       if (isSketchOpe && (!isSketcher))
279         // commit previous operation
280         if (!aOperation->commit())
281           aOperation->abort();
282       return;
283     }
284
285     if (isSketcher) {
286       myIsDragging = true;
287       get2dPoint(theWnd, theEvent, myCurrentPoint);
288       myDragDone = false;
289       launchEditing();
290
291     } else if (isSketchOpe && isEditing) {
292       // If selected another object commit current result
293       aOperation->commit();
294
295       myIsDragging = true;
296       get2dPoint(theWnd, theEvent, myCurrentPoint);
297       myDragDone = false;
298
299       // This is necessary in order to finalize previous operation
300       QApplication::processEvents();
301       launchEditing();
302     }
303   }
304 }
305
306 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
307 {
308   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
309   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
310   if (!aViewer->canDragByMouse())
311     return;
312   ModuleBase_Operation* aOp = getCurrentOperation();
313   if (aOp) {
314     if (isNestedSketchOperation(aOp)) {
315       get2dPoint(theWnd, theEvent, myClickedPoint);
316
317       // Only for sketcher operations
318       if (myIsDragging) {
319         if (myDragDone) {
320           //aOp->commit();
321           myFeature2AttributeMap.clear();
322
323           // Reselect edited object
324           /*aViewer->AISContext()->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
325           if (theEvent->modifiers() & Qt::ShiftModifier)
326             aViewer->AISContext()->ShiftSelect();
327           else
328             aViewer->AISContext()->Select();
329             */
330         }
331       }
332     }
333   }
334   aWorkshop->viewer()->enableSelection(myPreviousSelectionEnabled);
335   myIsDragging = false;
336 }
337
338 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
339 {
340   if (isNestedCreateOperation(getCurrentOperation()) && !myIsMouseOverViewProcessed) {
341     myIsMouseOverViewProcessed = true;
342     // 1. perform the widget mouse move functionality and display the presentation
343     ModuleBase_Operation* aOperation = getCurrentOperation();
344     ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
345     ModuleBase_ModelWidget* anActiveWdg = aPanel->activeWidget();
346     // the mouse move should be processed in the widget, if it can in order to visualize correct
347     // presentation. These widgets correct the feature attribute according to the mouse position
348     PartSet_WidgetPoint2D* aPoint2DWdg = dynamic_cast<PartSet_WidgetPoint2D*>(anActiveWdg);
349     if (aPoint2DWdg) {
350       aPoint2DWdg->onMouseMove(theWnd, theEvent);
351     }
352     PartSet_WidgetPoint2dDistance* aDistanceWdg = dynamic_cast<PartSet_WidgetPoint2dDistance*>
353                                                                 (anActiveWdg);
354     if (aDistanceWdg) {
355       aDistanceWdg->onMouseMove(theWnd, theEvent);
356     }
357     // the feature is to be erased here, but it is correct to call canDisplayObject because
358     // there can be additional check (e.g. editor widget in distance constraint)
359     visualizeFeature(aOperation, canDisplayObject());
360   }
361
362   myClickedPoint.clear();
363
364   if (myIsDragging) {
365     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
366     // 1. it is necessary to save current selection in order to restore it after the features moving
367     FeatureToSelectionMap aCurrentSelection;
368     getCurrentSelection(myFeature2AttributeMap, myCurrentSketch, aWorkshop, aCurrentSelection);
369
370     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
371     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
372     // deselected). This flag should be restored in the slot, processed the mouse release signal.
373     ModuleBase_IViewer* aViewer = myModule->workshop()->viewer();
374     aViewer->enableSelection(false);
375
376     ModuleBase_Operation* aOperation = getCurrentOperation();
377     if (!aOperation)
378       return;
379     if (isSketchOperation(aOperation))
380       return; // No edit operation activated
381
382     Handle(V3d_View) aView = theWnd->v3dView();
383     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
384     double aX, aY;
385     PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, aY);
386     double dX =  aX - myCurrentPoint.myCurX;
387     double dY =  aY - myCurrentPoint.myCurY;
388
389     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
390     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
391     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
392     // viewer happens by deselect/select the modified objects. The flag should be restored after
393     // the selection processing. The update viewer should be also called.
394     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
395
396     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
397     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
398
399     FeatureToAttributesMap::const_iterator anIt = myFeature2AttributeMap.begin(),
400                                            aLast = myFeature2AttributeMap.end();
401     // 4. the features and attributes modification(move)
402     for (; anIt != aLast; anIt++) {
403       FeaturePtr aFeature = anIt.key();
404
405       AttributeList anAttributes = anIt.value();
406       // Process selection by attribute: the priority to the attribute
407       if (!anAttributes.empty()) {
408         AttributeList::const_iterator anAttIt = anAttributes.begin(), anAttLast = anAttributes.end();
409         for (; anAttIt != anAttLast; anAttIt++) {
410           AttributePtr anAttr = *anAttIt;
411           if (anAttr.get() == NULL)
412             continue;
413           std::string aAttrId = anAttr->id();
414           DataPtr aData = aFeature->data();
415           if (aData.get() != NULL) {
416             std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
417               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
418             if (aPoint.get() != NULL) {
419               bool isImmutable = aPoint->setImmutable(true);
420               aPoint->move(dX, dY);
421               ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
422               aPoint->setImmutable(isImmutable);
423             }
424           }
425         }
426       } else {
427         // Process selection by feature
428         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
429           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
430         if (aSketchFeature) {
431           aSketchFeature->move(dX, dY);
432           ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
433         }
434       }
435     }
436     Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
437     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
438
439     // 5. it is necessary to save current selection in order to restore it after the features moving
440     FeatureToSelectionMap::const_iterator aSIt = aCurrentSelection.begin(),
441                                           aSLast = aCurrentSelection.end();
442     SelectMgr_IndexedMapOfOwner anOwnersToSelect;
443     for (; aSIt != aSLast; aSIt++) {
444       anOwnersToSelect.Clear();
445       getSelectionOwners(aSIt->first, myCurrentSketch, aWorkshop, aCurrentSelection,
446                          anOwnersToSelect);
447       aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
448     }
449
450     // 6. restore the update viewer flag and call this update
451     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
452     aDisplayer->updateViewer();
453     myDragDone = true;
454     myCurrentPoint.setValue(aX, aY);
455   }
456 }
457
458 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
459 {
460   ModuleBase_Operation* aOperation = getCurrentOperation();
461   if (aOperation && aOperation->isEditOperation()) {
462     std::string aId = aOperation->id().toStdString();
463     if (isDistanceOperation(aOperation))
464     {
465       // Activate dimension value editing on double click
466       ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
467       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
468       // Find corresponded widget to activate value editing
469       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
470         if (aWgt->attributeID() == "ConstraintValue") {
471           aWgt->focusTo();
472           return;
473         }
474       }
475     }
476   }
477 }
478
479 void PartSet_SketcherMgr::onApplicationStarted()
480 {
481   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
482   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
483   XGUI_Workshop* aWorkshop = aConnector->workshop();
484   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
485   if (aPropertyPanel) {
486     connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
487             this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
488   }
489
490   XGUI_ViewerProxy* aViewerProxy = aWorkshop->viewer();
491   connect(aViewerProxy, SIGNAL(enterViewPort()), this, SLOT(onEnterViewPort()));
492   connect(aViewerProxy, SIGNAL(leaveViewPort()), this, SLOT(onLeaveViewPort()));
493 }
494
495 void PartSet_SketcherMgr::onBeforeWidgetActivated(ModuleBase_ModelWidget* theWidget)
496 {
497   if (!myClickedPoint.myIsInitialized)
498     return;
499
500   ModuleBase_Operation* aOperation = getCurrentOperation();
501   // the distance constraint feature should not use the clickedd point
502   // this is workaround in order to don't throw down the flyout point value,
503   // set by execute() method of these type of features
504   if (isDistanceOperation(aOperation))
505     return;
506
507   PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(theWidget);
508   if (aPnt2dWgt) {
509     aPnt2dWgt->setPoint(myClickedPoint.myCurX, myClickedPoint.myCurY);
510   }
511 }
512
513 void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent, 
514                                      Point& thePoint)
515 {
516   Handle(V3d_View) aView = theWnd->v3dView();
517   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
518   double aX, anY;
519   PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, anY);
520   thePoint.setValue(aX, anY);
521 }
522
523 void PartSet_SketcherMgr::launchEditing()
524 {
525   // there should be activate the vertex selection mode because the edit can happens by the selected
526   // point
527   QIntList aModes;
528   aModes << TopAbs_VERTEX << TopAbs_EDGE;
529   // TODO: #391 - to be uncommented
530   /*aModes.append(AIS_DSM_Text);
531   aModes.append(AIS_DSM_Line);
532   aModes.append(AIS_Shape::SelectionMode((TopAbs_ShapeEnum) TopAbs_VERTEX));
533   aModes.append(AIS_Shape::SelectionMode((TopAbs_ShapeEnum) TopAbs_EDGE));*/
534
535   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
536   aConnector->activateSubShapesSelection(aModes);
537
538   if (!myFeature2AttributeMap.empty()) {
539     FeaturePtr aFeature = myFeature2AttributeMap.begin().key();
540     std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
541               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
542     if (aSPFeature) {
543       myModule->editFeature(aSPFeature);
544     }
545   }
546  
547 }
548
549
550 QStringList PartSet_SketcherMgr::sketchOperationIdList()
551 {
552   static QStringList aIds;
553   if (aIds.size() == 0) {
554     aIds << SketchPlugin_Line::ID().c_str();
555     aIds << SketchPlugin_Point::ID().c_str();
556     aIds << SketchPlugin_Arc::ID().c_str();
557     aIds << SketchPlugin_Circle::ID().c_str();
558     aIds << SketchPlugin_ConstraintLength::ID().c_str();
559     aIds << SketchPlugin_ConstraintDistance::ID().c_str();
560     aIds << SketchPlugin_ConstraintRigid::ID().c_str();
561     aIds << SketchPlugin_ConstraintRadius::ID().c_str();
562     aIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
563     aIds << SketchPlugin_ConstraintParallel::ID().c_str();
564   }
565   return aIds;
566 }
567
568 bool PartSet_SketcherMgr::isSketchOperation(ModuleBase_Operation* theOperation)
569 {
570   return theOperation && theOperation->id().toStdString() == SketchPlugin_Sketch::ID();
571 }
572
573 bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation)
574 {
575   return theOperation &&
576          PartSet_SketcherMgr::sketchOperationIdList().contains(theOperation->id());
577 }
578
579 bool PartSet_SketcherMgr::isDistanceOperation(ModuleBase_Operation* theOperation)
580 {
581   std::string aId = theOperation ? theOperation->id().toStdString() : "";
582
583   return (aId == SketchPlugin_ConstraintLength::ID()) ||
584          (aId == SketchPlugin_ConstraintDistance::ID()) ||
585          (aId == SketchPlugin_ConstraintRadius::ID());
586 }
587
588 void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
589 {
590   // Display all sketcher sub-Objects
591   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theOperation->feature());
592   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
593   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
594
595   // Hide sketcher result
596   std::list<ResultPtr> aResults = myCurrentSketch->results();
597   std::list<ResultPtr>::const_iterator aIt;
598   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
599     aDisplayer->erase((*aIt), false);
600   }
601   aDisplayer->erase(myCurrentSketch, false);
602
603   // Display sketcher objects
604   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
605     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
606     std::list<ResultPtr> aResults = aFeature->results();
607     std::list<ResultPtr>::const_iterator aIt;
608     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
609       aDisplayer->display((*aIt), false);
610     }
611     aDisplayer->display(aFeature, false);
612   }
613
614   if (myPlaneFilter.IsNull()) 
615     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
616
617   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
618   if (theOperation->isEditOperation()) {
619     // If it is editing of sketch then it means that plane is already defined
620     std::shared_ptr<GeomAPI_Pln> aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
621     myPlaneFilter->setPlane(aPln->impl<gp_Pln>());
622   }
623   aDisplayer->updateViewer();
624 }
625
626 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
627 {
628   myIsMouseOverWindow = false;
629
630   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
631   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
632
633   DataPtr aData = myCurrentSketch->data();
634   if ((!aData) || (!aData->isValid())) {
635     // The sketch was aborted
636     myCurrentSketch = CompositeFeaturePtr();
637     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
638
639     // Erase all sketcher objects
640     QStringList aSketchIds = sketchOperationIdList();
641     QObjectPtrList aObjects = aDisplayer->displayedObjects();
642     foreach (ObjectPtr aObj, aObjects) {
643       DataPtr aObjData = aObj->data();
644       if ((!aObjData) || (!aObjData->isValid()))
645         aDisplayer->erase(aObj);
646     }
647     return; 
648   }
649   // Hide all sketcher sub-Objects
650   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
651     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
652     std::list<ResultPtr> aResults = aFeature->results();
653     std::list<ResultPtr>::const_iterator aIt;
654     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
655       aDisplayer->erase((*aIt), false);
656     }
657     aDisplayer->erase(aFeature, false);
658   }
659   // Display sketcher result
660   std::list<ResultPtr> aResults = myCurrentSketch->results();
661   std::list<ResultPtr>::const_iterator aIt;
662   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
663     aDisplayer->display((*aIt), false);
664   }
665   aDisplayer->display(myCurrentSketch);
666     
667   myCurrentSketch = CompositeFeaturePtr();
668   myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
669   aDisplayer->updateViewer();
670 }
671
672 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* )
673 {
674   connectToPropertyPanel(true);
675 }
676
677 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
678 {
679   connectToPropertyPanel(false);
680   myIsPropertyPanelValueChanged = false;
681   myIsMouseOverViewProcessed = true;
682 }
683
684 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
685 {
686   if (isNestedCreateOperation(theOperation))
687     visualizeFeature(theOperation, true);
688 }
689
690 bool PartSet_SketcherMgr::canUndo() const
691 {
692   return isNestedCreateOperation(getCurrentOperation());
693 }
694
695 bool PartSet_SketcherMgr::canRedo() const
696 {
697   return isNestedCreateOperation(getCurrentOperation());
698 }
699
700 bool PartSet_SketcherMgr::canDisplayObject() const
701 {
702   bool aCanDisplay = true;
703   if (!isNestedCreateOperation(getCurrentOperation()))
704     return aCanDisplay;
705
706   ModuleBase_Operation* aOperation = getCurrentOperation();
707   ModuleBase_IPropertyPanel* aPanel = aOperation->propertyPanel();
708   ModuleBase_ModelWidget* anActiveWdg = aPanel ? aPanel->activeWidget() : 0;
709   // the active widget editor should not influence here. The presentation should be visible always
710   // when this widget is active.
711   if (anActiveWdg) {
712     ModuleBase_WidgetEditor* anEditorWdg = dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWdg);
713     if (anEditorWdg) {
714       return aCanDisplay;
715     }
716   }
717
718   // during a nested create operation, the feature is redisplayed only if the mouse over view
719   // of there was a value modified in the property panel after the mouse left the view
720   aCanDisplay = myIsPropertyPanelValueChanged || myIsMouseOverWindow;
721   return aCanDisplay;
722 }
723
724 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
725 {
726   myPlaneFilter->setPlane(thePln->impl<gp_Pln>());
727 }
728
729 void PartSet_SketcherMgr::getCurrentSelection(const FeatureToAttributesMap& theFeatureToAttributes,
730                                               const FeaturePtr& theSketch,
731                                               ModuleBase_IWorkshop* theWorkshop,
732                                               FeatureToSelectionMap& theSelection)
733 {
734   FeatureToAttributesMap::const_iterator anIt = theFeatureToAttributes.begin(),
735                                          aLast = theFeatureToAttributes.end();
736   for (; anIt != aLast; anIt++) {
737     FeaturePtr aFeature = anIt.key();
738     getCurrentSelection(aFeature, theSketch, theWorkshop, theSelection);
739   }
740 }
741
742 void PartSet_SketcherMgr::getCurrentSelection(const FeaturePtr& theFeature,
743                                               const FeaturePtr& theSketch,
744                                               ModuleBase_IWorkshop* theWorkshop,
745                                               FeatureToSelectionMap& theSelection)
746 {
747   if (theFeature.get() == NULL)
748     return;
749
750   std::set<AttributePtr> aSelectedAttributes;
751   std::set<ResultPtr> aSelectedResults;
752
753   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
754   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
755   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
756   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
757
758   std::list<ResultPtr> aResults = theFeature->results();
759   std::list<ResultPtr>::const_iterator aIt;
760   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
761   {
762     ResultPtr aResult = *aIt;
763     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
764     if (aAISObj.get() == NULL)
765       continue;
766     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
767     for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
768     {
769       Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(
770                                                                       aContext->SelectedOwner());
771       if (aBRepOwner.IsNull())
772         continue;
773       Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(
774                                                                         aBRepOwner->Selectable());
775       if (anIO != anAISIO)
776         continue;
777
778       if (aBRepOwner->HasShape()) {
779         const TopoDS_Shape& aShape = aBRepOwner->Shape();
780         TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
781         if (aShapeType == TopAbs_VERTEX) {
782           AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature,
783                                                                         aShape, theSketch);
784           if (aPntAttr.get() != NULL)
785             aSelectedAttributes.insert(aPntAttr);
786         }
787         else if (aShapeType == TopAbs_EDGE &&
788                  aSelectedResults.find(aResult) == aSelectedResults.end()) {
789           aSelectedResults.insert(aResult);
790         }
791       }
792     }
793   }
794   theSelection[theFeature] = std::make_pair(aSelectedAttributes, aSelectedResults);
795 }
796
797 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
798                                              const FeaturePtr& theSketch,
799                                              ModuleBase_IWorkshop* theWorkshop,
800                                              const FeatureToSelectionMap& theSelection,
801                                              SelectMgr_IndexedMapOfOwner& anOwnersToSelect)
802 {
803   if (theFeature.get() == NULL)
804     return;
805
806   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
807   std::set<AttributePtr> aSelectedAttributes = anIt->second.first;
808   std::set<ResultPtr> aSelectedResults = anIt->second.second;
809
810   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
811   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
812   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
813   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
814
815   std::list<ResultPtr> aResults = theFeature->results();
816   std::list<ResultPtr>::const_iterator aIt;
817   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
818   {
819     ResultPtr aResult = *aIt;
820     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
821     if (aAISObj.get() == NULL)
822       continue; 
823     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
824
825     SelectMgr_IndexedMapOfOwner aSelectedOwners;  
826     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
827     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
828       Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
829       if ( anOwner.IsNull() || !anOwner->HasShape() )
830         continue;
831       const TopoDS_Shape& aShape = anOwner->Shape();
832       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
833       if (aShapeType == TopAbs_VERTEX) {
834         AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
835         if (aPntAttr.get() != NULL &&
836             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end()) {
837           anOwnersToSelect.Add(anOwner);
838         }
839       }
840       else if (aShapeType == TopAbs_EDGE) {
841         bool aFound = aSelectedResults.find(aResult) != aSelectedResults.end();
842         if (aSelectedResults.find(aResult) != aSelectedResults.end() &&
843             anOwnersToSelect.FindIndex(anOwner) <= 0)
844           anOwnersToSelect.Add(anOwner);
845       }
846     }
847   }
848 }
849
850 void PartSet_SketcherMgr::connectToPropertyPanel(const bool isToConnect)
851 {
852   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
853   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
854   XGUI_Workshop* aWorkshop = aConnector->workshop();
855   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
856   if (aPropertyPanel) {
857     const QList<ModuleBase_ModelWidget*>& aWidgets = aPropertyPanel->modelWidgets();
858     foreach (ModuleBase_ModelWidget* aWidget, aWidgets) {
859       if (isToConnect) {
860         connect(aWidget, SIGNAL(beforeValuesChanged()),
861                 this, SLOT(onBeforeValuesChangedInPropertyPanel()));
862         connect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChangedInPropertyPanel()));
863         connect(aWidget, SIGNAL(afterValuesChanged()),
864                 this, SLOT(onAfterValuesChangedInPropertyPanel()));
865       }
866       else {
867         disconnect(aWidget, SIGNAL(beforeValuesChanged()),
868                    this, SLOT(onBeforeValuesChangedInPropertyPanel()));
869         disconnect(aWidget, SIGNAL(valuesChanged()), this, SLOT(onValuesChangedInPropertyPanel()));
870         disconnect(aWidget, SIGNAL(afterValuesChanged()),
871                    this, SLOT(onAfterValuesChangedInPropertyPanel()));
872       }
873     }
874   }
875 }
876
877 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
878 {
879   return myModule->workshop()->currentOperation();
880 }
881
882 bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation) const
883 {
884   return theOperation && !theOperation->isEditOperation() && isNestedSketchOperation(theOperation);
885 }
886
887 void PartSet_SketcherMgr::visualizeFeature(ModuleBase_Operation* theOperation,
888                                            const bool isToDisplay)
889 {
890   if (!theOperation || theOperation->isEditOperation())
891     return;
892
893   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
894   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
895   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
896
897   // 1. change visibility of the object itself, here the presentable object is processed,
898   // e.g. constraints features
899   FeaturePtr aFeature = theOperation->feature();
900   std::list<ResultPtr> aResults = aFeature->results();
901   if (isToDisplay)
902     aDisplayer->display(aFeature, false);
903   else
904     aDisplayer->erase(aFeature, false);
905
906   // change visibility of the object results, e.g. non-constraint features
907   std::list<ResultPtr>::const_iterator aIt;
908   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
909     if (isToDisplay) {
910       aDisplayer->display(*aIt, false);
911     }
912     else {
913       aDisplayer->erase(*aIt, false);
914     }
915   }
916   aDisplayer->updateViewer();
917 }
918
919 void PartSet_SketcherMgr::storeSelection()
920 {
921   //qDebug("  storeSelection");
922   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
923   // 1. it is necessary to save current selection in order to restore it after the features moving
924   //FeatureToSelectionMap aCurrentSelection;
925   myCurrentSelection.clear();
926   getCurrentSelection(myFeature2AttributeMap, myCurrentSketch, aWorkshop, myCurrentSelection);
927
928   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
929   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
930   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
931   // viewer happens by deselect/select the modified objects. The flag should be restored after
932   // the selection processing. The update viewer should be also called.
933   myPreviousUpdateViewerEnabled = aDisplayer->enableUpdateViewer(false);
934 }
935
936 void PartSet_SketcherMgr::restoreSelection()
937 {
938   //qDebug("restoreSelection");
939   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
940   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
941   // 5. it is necessary to save current selection in order to restore it after the features moving
942   FeatureToSelectionMap::const_iterator aSIt = myCurrentSelection.begin(),
943                                         aSLast = myCurrentSelection.end();
944   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
945   for (; aSIt != aSLast; aSIt++) {
946     anOwnersToSelect.Clear();
947     getSelectionOwners(aSIt->first, myCurrentSketch, aWorkshop, myCurrentSelection,
948                         anOwnersToSelect);
949     aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
950   }
951   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
952   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
953   // viewer happens by deselect/select the modified objects. The flag should be restored after
954   // the selection processing. The update viewer should be also called.
955   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
956   //if (myPreviousUpdateViewerEnabled)
957     aDisplayer->updateViewer();
958 }