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