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