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