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