]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_SketcherMgr.cpp
Salome HOME
Bug: sketch, closed controur, group, selection of edge. The result is that all edges...
[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_SketcherReetntrantMgr.h"
9 #include "PartSet_Module.h"
10 #include "PartSet_WidgetPoint2d.h"
11 #include "PartSet_WidgetPoint2dDistance.h"
12 #include "PartSet_Tools.h"
13 #include "PartSet_WidgetSketchLabel.h"
14 #include "PartSet_WidgetEditor.h"
15
16 #include <XGUI_ModuleConnector.h>
17 #include <XGUI_Displayer.h>
18 #include <XGUI_Workshop.h>
19 #include <XGUI_ContextMenuMgr.h>
20 #include <XGUI_Selection.h>
21 #include <XGUI_SelectionMgr.h>
22 #include <XGUI_ModuleConnector.h>
23 #include <XGUI_PropertyPanel.h>
24 #include <XGUI_ViewerProxy.h>
25 #include <XGUI_OperationMgr.h>
26
27 #include <ModuleBase_IPropertyPanel.h>
28 #include <ModuleBase_ISelection.h>
29 #include <ModuleBase_IViewer.h>
30 #include <ModuleBase_IWorkshop.h>
31 #include <ModuleBase_IViewWindow.h>
32 #include <ModuleBase_ModelWidget.h>
33 #include <ModuleBase_Operation.h>
34 #include <ModuleBase_OperationFeature.h>
35 #include <ModuleBase_Operation.h>
36 #include <ModuleBase_WidgetEditor.h>
37
38 #include <GeomDataAPI_Point2D.h>
39
40 #include <Events_Loop.h>
41
42 #include <SketchPlugin_Line.h>
43 #include <SketchPlugin_Sketch.h>
44 #include <SketchPlugin_Point.h>
45 #include <SketchPlugin_Arc.h>
46 #include <SketchPlugin_Circle.h>
47 #include <SketchPlugin_ConstraintLength.h>
48 #include <SketchPlugin_ConstraintDistance.h>
49 #include <SketchPlugin_ConstraintParallel.h>
50 #include <SketchPlugin_ConstraintPerpendicular.h>
51 #include <SketchPlugin_ConstraintRadius.h>
52 #include <SketchPlugin_ConstraintRigid.h>
53 #include <SketchPlugin_ConstraintHorizontal.h>
54 #include <SketchPlugin_ConstraintVertical.h>
55 #include <SketchPlugin_ConstraintEqual.h>
56 #include <SketchPlugin_ConstraintTangent.h>
57 #include <SketchPlugin_ConstraintCoincidence.h>
58 #include <SketchPlugin_ConstraintFillet.h>
59 #include <SketchPlugin_ConstraintMirror.h>
60 #include <SketchPlugin_ConstraintAngle.h>
61 #include <SketchPlugin_MultiRotation.h>
62 #include <SketchPlugin_MultiTranslation.h>
63
64 #include <SketcherPrs_Tools.h>
65
66 #include <SelectMgr_IndexedMapOfOwner.hxx>
67 #include <StdSelect_BRepOwner.hxx>
68
69 //#include <AIS_DimensionSelectionMode.hxx>
70 #include <AIS_Shape.hxx>
71
72 #include <ModelAPI_Events.h>
73 #include <ModelAPI_Session.h>
74 #include <ModelAPI_AttributeString.h>
75
76 #include <QMouseEvent>
77 #include <QApplication>
78
79 //#define DEBUG_DO_NOT_BY_ENTER
80
81 /// Returns list of unique objects by sum of objects from List1 and List2
82 /*QList<ModuleBase_ViewerPrs> getSumList(const QList<ModuleBase_ViewerPrs>& theList1,
83                                        const QList<ModuleBase_ViewerPrs>& theList2)
84 {
85   QList<ModuleBase_ViewerPrs> aRes;
86   foreach (ModuleBase_ViewerPrs aPrs, theList1) {
87     if (!aRes.contains(aPrs))
88       aRes.append(aPrs);
89   }
90   foreach (ModuleBase_ViewerPrs aPrs, theList2) {
91     if (!aRes.contains(aPrs))
92       aRes.append(aPrs);
93   }
94   return aRes;
95 }*/
96
97 // Fills the list of features the list of selected presentations.
98 // \param theList a list of selected presentations
99 // \param theSketch a sketch to project a vertex shape of a presentation to the plane
100 // and find the corresponded attribute
101 // \param theFeatureList  an output list of features
102 void fillFeatureList(const QList<ModuleBase_ViewerPrs>& theList,
103                      const FeaturePtr theSketch,
104                      QList<FeaturePtr>& theFeatureList)
105 {
106   QList<ModuleBase_ViewerPrs> aRes;
107
108   QList<ModuleBase_ViewerPrs>::const_iterator anIt = theList.begin(),
109                                               aLast = theList.end();
110   for (; anIt != aLast; anIt++)
111   {
112     ModuleBase_ViewerPrs aPrs = *anIt;
113     FeaturePtr aFeature = ModelAPI_Feature::feature(aPrs.object());
114     if (aFeature.get()  && !theFeatureList.contains(aFeature))
115       theFeatureList.append(aFeature);
116   }
117 }
118
119 /// Fills attribute and result lists by the selected owner. In case if the attribute is found,
120 /// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge, put the function
121 /// result as is to the list of results.
122 /// \param theOwner a viewer selected owner
123 /// \param theFeature a feature, where the attribute is searched
124 /// \param theSketch a current sketch
125 /// \param theSelectedAttribute an output list of attributes
126 /// \param theSelectedResults an output list of edge results
127 void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
128                             const FeaturePtr& theFeature, const FeaturePtr& theSketch,
129                             const ResultPtr& theResult,
130                             std::set<AttributePtr>& aSelectedAttributes,
131                             std::set<ResultPtr>& aSelectedResults)
132 {
133   Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(theOwner);
134   if (aBRepOwner.IsNull())
135     return;
136   Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(
137                                                                     aBRepOwner->Selectable());
138   if (aBRepOwner->HasShape()) {
139     const TopoDS_Shape& aShape = aBRepOwner->Shape();
140     TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
141     if (aShapeType == TopAbs_VERTEX) {
142       AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature,
143                                                                     aShape, theSketch);
144       if (aPntAttr.get() != NULL)
145         aSelectedAttributes.insert(aPntAttr);
146     }
147     else if (aShapeType == TopAbs_EDGE &&
148              aSelectedResults.find(theResult) == aSelectedResults.end()) {
149       aSelectedResults.insert(theResult);
150     }
151   }
152 }
153
154 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
155   : QObject(theModule), myModule(theModule), myIsDragging(false), myDragDone(false),
156     myIsMouseOverWindow(false),
157     myIsMouseOverViewProcessed(true), myPreviousUpdateViewerEnabled(true),
158     myIsPopupMenuActive(false), myIsConstraintsShown(true)
159 {
160   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
161   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
162
163   myPreviousDrawModeEnabled = true;//aViewer->isSelectionEnabled();
164
165   connect(aViewer, SIGNAL(mousePress(ModuleBase_IViewWindow*, QMouseEvent*)),
166           this, SLOT(onMousePressed(ModuleBase_IViewWindow*, QMouseEvent*)));
167
168   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)),
169           this, SLOT(onMouseReleased(ModuleBase_IViewWindow*, QMouseEvent*)));
170
171   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
172           this, SLOT(onMouseMoved(ModuleBase_IViewWindow*, QMouseEvent*)));
173
174   connect(aViewer, SIGNAL(mouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)),
175           this, SLOT(onMouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)));
176
177   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
178   XGUI_Workshop* aWorkshop = aConnector->workshop();
179   connect(aWorkshop, SIGNAL(applicationStarted()), this, SLOT(onApplicationStarted()));
180 }
181
182 PartSet_SketcherMgr::~PartSet_SketcherMgr()
183 {
184   if (!myPlaneFilter.IsNull())
185     myPlaneFilter.Nullify();
186 }
187
188 void PartSet_SketcherMgr::onEnterViewPort()
189 {
190   // 1. if the mouse over window, update the next flag. Do not perform update visibility of
191   // created feature because it should be done in onMouseMove(). Some widgets watch
192   // the mouse move and use the cursor position to update own values. If the presentaion is
193   // redisplayed before this update, the feature presentation jumps from reset value to current.
194   myIsMouseOverWindow = true;
195
196   #ifdef DEBUG_DO_NOT_BY_ENTER
197   return;
198   #endif
199
200   if (canChangeCursor(getCurrentOperation()))
201     QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
202
203   if (!isNestedCreateOperation(getCurrentOperation()))
204     return;
205
206   operationMgr()->onValidateOperation();
207
208   // we need change displayed state of the current operation feature
209   // if the feature is presentable, e.g. distance construction. It has no results, so workshop does
210   // not accept a signal about the result created. Nothing is shown until mouse is moved out/in view
211   // port. If the isDisplayed flag is true, the presentable feature is displayed as soon as the
212   // presentation becomes valid and redisplay happens
213   //ModuleBase_Operation* aOperation = getCurrentOperation();
214   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
215                                                                            (getCurrentOperation());
216   if (aFOperation) {
217     FeaturePtr aFeature = aFOperation->feature();
218     if (aFeature.get() && aFeature->data()->isValid()) {
219       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature), false);
220     }
221   }
222 }
223
224 void PartSet_SketcherMgr::onLeaveViewPort()
225 {
226   myIsMouseOverViewProcessed = false;
227   myIsMouseOverWindow = false;
228   // it is important to validate operation here only if sketch entity create operation is active
229   // because at this operation we reacts to the mouse leave/enter view port
230   //operationMgr()->onValidateOperation();
231
232   #ifdef DEBUG_DO_NOT_BY_ENTER
233   return;
234   #endif
235
236   if (canChangeCursor(getCurrentOperation()))
237     QApplication::restoreOverrideCursor();
238
239   if (!isNestedCreateOperation(getCurrentOperation()))
240     return;
241
242   // the method should be performed if the popup menu is called,
243   // the reset of the current widget should not happen
244   if (myIsPopupMenuActive)
245     return;
246
247   operationMgr()->onValidateOperation();
248
249   // 2. if the mouse IS NOT over window, reset the active widget value and hide the presentation
250   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
251   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
252   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
253   // disable the viewer update in order to avoid visualization of redisplayed feature in viewer
254   // obtained after reset value
255   bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
256   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
257   if (anActiveWidget)
258     anActiveWidget->reset();
259   aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
260
261   // hides the presentation of the current operation feature
262   // the feature is to be erased here, but it is correct to call canDisplayObject because
263   // there can be additional check (e.g. editor widget in distance constraint)
264   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
265                                                                            (getCurrentOperation());
266   if (aFOperation) {
267     FeaturePtr aFeature = aFOperation->feature();
268     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
269   }
270 }
271
272 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
273 {
274   if (!isNestedEditOperation(getCurrentOperation()) ||
275       myModule->sketchReentranceMgr()->isInternalEditActive())
276     return;
277   // it is necessary to save current selection in order to restore it after the values are modifed
278   storeSelection();
279
280   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
281   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
282   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
283   myPreviousUpdateViewerEnabled = aDisplayer->enableUpdateViewer(false);
284 }
285
286 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
287 {
288   if (!isNestedEditOperation(getCurrentOperation()) ||
289       myModule->sketchReentranceMgr()->isInternalEditActive())
290     return;
291   // it is necessary to restore current selection in order to restore it after the values are modified
292   restoreSelection();
293   myCurrentSelection.clear();
294
295   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
296   // viewer happens by deselect/select the modified objects. The flag should be restored after
297   // the selection processing. The update viewer should be also called.
298   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
299   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
300   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
301   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
302   aDisplayer->updateViewer();
303 }
304
305 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
306 {
307   if (myModule->sketchReentranceMgr()->processMousePressed(theWnd, theEvent))
308     return;
309
310   get2dPoint(theWnd, theEvent, myClickedPoint);
311
312   if (!(theEvent->buttons() & Qt::LeftButton))
313     return;
314
315   // Clear dragging mode
316   myIsDragging = false;
317
318   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
319   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
320   if (!aViewer->canDragByMouse())
321     return;
322
323   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
324                                                                (getCurrentOperation());
325   if (!aFOperation)
326     return;
327
328   if (aFOperation->isEditOperation()) {
329     // If the current widget is a selector, do nothing, it processes the mouse press
330     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
331     if(anActiveWidget && anActiveWidget->isViewerSelector()) {
332       return;
333     }
334   }
335
336   // Use only for sketch operations
337   if (myCurrentSketch) {
338     if (!PartSet_Tools::sketchPlane(myCurrentSketch))
339       return;
340
341     bool isSketcher = isSketchOperation(aFOperation);
342     bool isSketchOpe = isNestedSketchOperation(aFOperation);
343
344     // Avoid non-sketch operations
345     if ((!isSketchOpe) && (!isSketcher))
346       return;
347
348     bool isEditing = aFOperation->isEditOperation();
349
350     // Ignore creation sketch operation
351     if ((!isSketcher) && (!isEditing))
352       return;
353
354     Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
355     if (!aContext.IsNull()) {
356       // MoveTo in order to highlight current object
357       aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
358     }
359     // Remember highlighted objects for editing
360     ModuleBase_ISelection* aSelect = aWorkshop->selection();
361
362     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
363     storeSelection(!aHasShift);
364
365     if (myCurrentSelection.empty()) {
366       if (isSketchOpe && (!isSketcher))
367         // commit previous operation
368         if (!aFOperation->commit())
369           aFOperation->abort();
370       return;
371     }
372     // Init flyout point for radius rotation
373     FeaturePtr aFeature = myCurrentSelection.begin().key();
374
375     if (isSketcher) {
376       myIsDragging = true;
377       get2dPoint(theWnd, theEvent, myCurrentPoint);
378       myDragDone = false;
379       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
380       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
381       launchEditing();
382       if (aFeature.get() != NULL) {
383         std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
384                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
385       if (aSPFeature.get() && aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID()) {
386           DataPtr aData = aSPFeature->data();
387           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
388           std::shared_ptr<GeomDataAPI_Point2D> aFPAttr = 
389             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
390           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
391         }
392       }
393     } else if (isSketchOpe && isEditing) {
394       // If selected another object commit current result
395       aFOperation->commit();
396
397       myIsDragging = true;
398       get2dPoint(theWnd, theEvent, myCurrentPoint);
399       myDragDone = false;
400       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
401       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
402
403       // This is necessary in order to finalize previous operation
404       QApplication::processEvents();
405       launchEditing();
406     }
407   }
408 }
409
410 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
411 {
412   if (myModule->sketchReentranceMgr()->processMouseReleased(theWnd, theEvent))
413     return;
414
415   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
416   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
417   if (!aViewer->canDragByMouse())
418     return;
419   ModuleBase_Operation* aOp = getCurrentOperation();
420   if (aOp) {
421     if (isNestedSketchOperation(aOp)) {
422       get2dPoint(theWnd, theEvent, myClickedPoint);
423
424       // Only for sketcher operations
425       if (myIsDragging) {
426         if (myDragDone) {
427           //aOp->commit();
428           myCurrentSelection.clear();
429           /*Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
430           if (!aContext.IsNull()) {
431           // Reselect edited object
432           aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
433           if (theEvent->modifiers() & Qt::ShiftModifier)
434             aContext->ShiftSelect();
435           else
436             aContext->Select();
437           */
438         }
439       }
440     }
441   }
442       // TODO: Has to be uncommented when SALOME patch on draw mode become avialable
443   aWorkshop->viewer()->enableDrawMode(myPreviousDrawModeEnabled);
444   //aWorkshop->viewer()->enableSelection(myPreviousDrawModeEnabled);
445   myIsDragging = false;
446 }
447
448 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
449 {
450   if (myModule->sketchReentranceMgr()->processMouseMoved(theWnd, theEvent))
451     return;
452
453   if (isNestedCreateOperation(getCurrentOperation()) && !myIsMouseOverViewProcessed) {
454     myIsMouseOverViewProcessed = true;
455     // 1. perform the widget mouse move functionality and display the presentation
456     // the mouse move should be processed in the widget, if it can in order to visualize correct
457     // presentation. These widgets correct the feature attribute according to the mouse position
458     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
459     PartSet_WidgetPoint2D* aPoint2DWdg = dynamic_cast<PartSet_WidgetPoint2D*>(anActiveWidget);
460     if (aPoint2DWdg) {
461       aPoint2DWdg->onMouseMove(theWnd, theEvent);
462     }
463     PartSet_WidgetPoint2dDistance* aDistanceWdg = dynamic_cast<PartSet_WidgetPoint2dDistance*>
464                                                                 (anActiveWidget);
465     if (aDistanceWdg) {
466       aDistanceWdg->onMouseMove(theWnd, theEvent);
467     }
468     // the feature is to be erased here, but it is correct to call canDisplayObject because
469     // there can be additional check (e.g. editor widget in distance constraint)
470     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
471                                                                              (getCurrentOperation());
472     if (aFOperation) {
473       FeaturePtr aFeature = aFOperation->feature();
474       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
475     }
476   }
477
478   myClickedPoint.clear();
479
480   if (myIsDragging) {
481     // 1. the current selection is saved in the mouse press method in order to restore it after moving
482     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
483     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
484     // deselected). This flag should be restored in the slot, processed the mouse release signal.
485
486     // TODO: Has to be commented out when SALOME patch on draw mode become avialable
487     //ModuleBase_IViewer* aViewer = myModule->workshop()->viewer();
488     //aViewer->enableSelection(false);
489
490     ModuleBase_Operation* aCurrentOperation = getCurrentOperation();
491     if (!aCurrentOperation)
492       return;
493     if (isSketchOperation(aCurrentOperation))
494       return; // No edit operation activated
495
496     Handle(V3d_View) aView = theWnd->v3dView();
497     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
498     double aX, aY;
499     PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, aY);
500     double dX =  aX - myCurrentPoint.myCurX;
501     double dY =  aY - myCurrentPoint.myCurY;
502
503     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
504     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
505     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
506     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
507     // viewer happens by deselect/select the modified objects. The flag should be restored after
508     // the selection processing. The update viewer should be also called.
509     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
510
511     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
512     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
513     FeatureToSelectionMap::const_iterator anIt = myCurrentSelection.begin(),
514                                           aLast = myCurrentSelection.end();
515     // 4. the features and attributes modification(move)
516     bool isModified = false;
517     for (; anIt != aLast; anIt++) {
518       FeaturePtr aFeature = anIt.key();
519
520       std::set<AttributePtr> anAttributes = anIt.value().first;
521       // Process selection by attribute: the priority to the attribute
522       if (!anAttributes.empty()) {
523         std::set<AttributePtr>::const_iterator anAttIt = anAttributes.begin(),
524                                                anAttLast = anAttributes.end();
525         for (; anAttIt != anAttLast; anAttIt++) {
526           AttributePtr anAttr = *anAttIt;
527           if (anAttr.get() == NULL)
528             continue;
529           std::string aAttrId = anAttr->id();
530           DataPtr aData = aFeature->data();
531           if (aData->isValid()) {
532             std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
533               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
534             if (aPoint.get() != NULL) {
535               bool isImmutable = aPoint->setImmutable(true);
536               aPoint->move(dX, dY);
537               isModified = true;
538               ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
539               aPoint->setImmutable(isImmutable);
540             }
541           }
542         }
543       } else {
544         // Process selection by feature
545         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
546           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
547         if (aSketchFeature) {
548           aSketchFeature->move(dX, dY);
549           isModified = true;
550           ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
551         }
552       }
553     }
554     // the modified state of the current operation should be updated if there are features, which
555     // were changed here
556     if (isModified) {
557       aCurrentOperation->onValuesChanged();
558     }
559     Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
560     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
561
562     // 5. it is necessary to save current selection in order to restore it after the features moving
563     restoreSelection();
564     // 6. restore the update viewer flag and call this update
565     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
566     aDisplayer->updateViewer();
567
568     myDragDone = true;
569     myCurrentPoint.setValue(aX, aY);
570   }
571 }
572
573 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
574 {
575   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
576                                                                (getCurrentOperation());
577   if (aFOperation && aFOperation->isEditOperation()) {
578     std::string aId = aFOperation->id().toStdString();
579     if (isDistanceOperation(aFOperation))
580     {
581       // Activate dimension value editing on double click
582       ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
583       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
584       // Find corresponded widget to activate value editing
585       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
586         if (aWgt->attributeID() == "ConstraintValue") {
587           PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
588           if (anEditor)
589             anEditor->showPopupEditor();
590           return;
591         }
592       }
593     }
594   }
595 }
596
597 void PartSet_SketcherMgr::onApplicationStarted()
598 {
599   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
600   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
601   XGUI_Workshop* aWorkshop = aConnector->workshop();
602   PartSet_SketcherReetntrantMgr* aReentranceMgr = myModule->sketchReentranceMgr();
603
604   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
605   if (aPropertyPanel) {
606     connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
607             this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
608
609     connect(aPropertyPanel, SIGNAL(noMoreWidgets(const std::string&)),
610             aReentranceMgr, SLOT(onNoMoreWidgets(const std::string&)));
611     connect(aPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
612             aReentranceMgr, SLOT(onWidgetActivated()));
613   }
614
615   XGUI_ViewerProxy* aViewerProxy = aWorkshop->viewer();
616   connect(aViewerProxy, SIGNAL(enterViewPort()), this, SLOT(onEnterViewPort()));
617   connect(aViewerProxy, SIGNAL(leaveViewPort()), this, SLOT(onLeaveViewPort()));
618
619   XGUI_ContextMenuMgr* aContextMenuMgr = aWorkshop->contextMenuMgr();
620   connect(aContextMenuMgr, SIGNAL(beforeContextMenu()), this, SLOT(onBeforeContextMenu()));
621   connect(aContextMenuMgr, SIGNAL(afterContextMenu()), this, SLOT(onAfterContextMenu()));
622 }
623
624 void PartSet_SketcherMgr::onBeforeWidgetActivated(ModuleBase_ModelWidget* theWidget)
625 {
626   if (!myClickedPoint.myIsInitialized)
627     return;
628
629   ModuleBase_Operation* aOperation = getCurrentOperation();
630   // the distance constraint feature should not use the clickedd point
631   // this is workaround in order to don't throw down the flyout point value,
632   // set by execute() method of these type of features
633   if (isDistanceOperation(aOperation))
634     return;
635
636   PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(theWidget);
637   if (aPnt2dWgt) {
638     aPnt2dWgt->setPoint(myClickedPoint.myCurX, myClickedPoint.myCurY);
639   }
640 }
641
642 void PartSet_SketcherMgr::onBeforeContextMenu()
643 {
644   myIsPopupMenuActive = true;
645 }
646
647 void PartSet_SketcherMgr::onAfterContextMenu()
648 {
649   myIsPopupMenuActive = false;
650 }
651
652 void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent, 
653                                      Point& thePoint)
654 {
655   Handle(V3d_View) aView = theWnd->v3dView();
656   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
657   double aX, anY;
658   PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, anY);
659   thePoint.setValue(aX, anY);
660 }
661
662 void PartSet_SketcherMgr::launchEditing()
663 {
664   if (!myCurrentSelection.empty()) {
665     FeaturePtr aFeature = myCurrentSelection.begin().key();
666     std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
667               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
668     if (aSPFeature) {
669       myModule->editFeature(aSPFeature);
670     }
671   }
672 }
673
674 bool PartSet_SketcherMgr::sketchSolverError()
675 {
676   bool anError = false;
677   CompositeFeaturePtr aSketch = activeSketch();
678   if (aSketch.get()) {
679     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
680     anError = !aAttributeString->value().empty();
681   }
682   return anError;
683 }
684
685 QString PartSet_SketcherMgr::getFeatureError(const FeaturePtr& theFeature)
686 {
687   QString anError = "";
688   if (!theFeature.get() || !theFeature->data()->isValid())
689     return anError;
690
691   CompositeFeaturePtr aSketch = activeSketch();
692   if (aSketch.get() && aSketch == theFeature) {
693     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
694     anError = aAttributeString->value().c_str();
695   }
696   return anError;
697 }
698
699 void PartSet_SketcherMgr::clearClickedFlags()
700 {
701   return;
702   myClickedPoint.clear();
703   myCurrentPoint.clear();
704 }
705
706 const QStringList& PartSet_SketcherMgr::sketchOperationIdList()
707 {
708   static QStringList aIds;
709   if (aIds.size() == 0) {
710     aIds << SketchPlugin_Line::ID().c_str();
711     aIds << SketchPlugin_Point::ID().c_str();
712     aIds << SketchPlugin_Arc::ID().c_str();
713     aIds << SketchPlugin_Circle::ID().c_str();
714     aIds << SketchPlugin_ConstraintFillet::ID().c_str();
715     aIds.append(constraintsIdList());
716   }
717   return aIds;
718 }
719
720 const QStringList& PartSet_SketcherMgr::constraintsIdList()
721 {
722   static QStringList aIds;
723   if (aIds.size() == 0) {
724     aIds << SketchPlugin_ConstraintLength::ID().c_str();
725     aIds << SketchPlugin_ConstraintDistance::ID().c_str();
726     aIds << SketchPlugin_ConstraintRigid::ID().c_str();
727     aIds << SketchPlugin_ConstraintRadius::ID().c_str();
728     aIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
729     aIds << SketchPlugin_ConstraintParallel::ID().c_str();
730     aIds << SketchPlugin_ConstraintHorizontal::ID().c_str();
731     aIds << SketchPlugin_ConstraintVertical::ID().c_str();
732     aIds << SketchPlugin_ConstraintEqual::ID().c_str();
733     aIds << SketchPlugin_ConstraintTangent::ID().c_str();
734     aIds << SketchPlugin_ConstraintCoincidence::ID().c_str();
735     aIds << SketchPlugin_ConstraintMirror::ID().c_str();
736     aIds << SketchPlugin_ConstraintAngle::ID().c_str();
737     aIds << SketchPlugin_MultiRotation::ID().c_str();
738     aIds << SketchPlugin_MultiTranslation::ID().c_str();
739   }
740   return aIds;
741 }
742
743 void PartSet_SketcherMgr::sketchSelectionModes(QIntList& theModes)
744 {
745   theModes.clear();
746
747   theModes.append(SketcherPrs_Tools::Sel_Dimension_Text);
748   theModes.append(SketcherPrs_Tools::Sel_Dimension_Line);
749   theModes.append(SketcherPrs_Tools::Sel_Constraint);
750   theModes.append(TopAbs_VERTEX);
751   theModes.append(TopAbs_EDGE);
752 }
753
754 bool PartSet_SketcherMgr::isSketchOperation(ModuleBase_Operation* theOperation)
755 {
756   return theOperation && theOperation->id().toStdString() == SketchPlugin_Sketch::ID();
757 }
758
759 bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation)
760 {
761   return theOperation &&
762          PartSet_SketcherMgr::sketchOperationIdList().contains(theOperation->id());
763 }
764
765 bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation)
766 {
767   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
768                                                                (theOperation);
769   return aFOperation && !aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
770 }
771
772 bool PartSet_SketcherMgr::isNestedEditOperation(ModuleBase_Operation* theOperation)
773 {
774   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
775                                                                (theOperation);
776   return aFOperation && aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
777 }
778
779 bool PartSet_SketcherMgr::isEntity(const std::string& theId)
780 {
781   return (theId == SketchPlugin_Line::ID()) ||
782          (theId == SketchPlugin_Point::ID()) ||
783          (theId == SketchPlugin_Arc::ID()) ||
784          (theId == SketchPlugin_Circle::ID());
785 }
786
787 bool PartSet_SketcherMgr::isDistanceOperation(ModuleBase_Operation* theOperation)
788 {
789   std::string aId = theOperation ? theOperation->id().toStdString() : "";
790
791   return (aId == SketchPlugin_ConstraintLength::ID()) ||
792          (aId == SketchPlugin_ConstraintDistance::ID()) ||
793          (aId == SketchPlugin_ConstraintRadius::ID()) ||
794          (aId == SketchPlugin_ConstraintAngle::ID());
795 }
796
797 void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
798 {
799   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
800                                                                (getCurrentOperation());
801   if (!aFOperation)
802     return;
803
804   myModule->onViewTransformed();
805
806   // Display all sketcher sub-Objects
807   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFOperation->feature());
808   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
809   aConnector->workshop()->displayer()->activateTrihedron(true);
810
811   // Hide sketcher result
812   std::list<ResultPtr> aResults = myCurrentSketch->results();
813   std::list<ResultPtr>::const_iterator aIt;
814   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
815     (*aIt)->setDisplayed(false);
816   }
817   myCurrentSketch->setDisplayed(false);
818
819   // Display sketcher objects
820   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
821     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
822     std::list<ResultPtr> aResults = aFeature->results();
823     std::list<ResultPtr>::const_iterator aIt;
824     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
825       (*aIt)->setDisplayed(true);
826     }
827     aFeature->setDisplayed(true);
828   }
829
830   if (myPlaneFilter.IsNull()) 
831     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
832
833   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
834
835   bool aHasPlane = false;
836   std::shared_ptr<GeomAPI_Pln> aPln;
837   if (aFOperation->isEditOperation()) {
838     // If it is editing of sketch then it means that plane is already defined
839     aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
840     if (aPln.get())
841       aHasPlane = true;
842   }
843   myPlaneFilter->setPlane(aPln);
844
845   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
846   // all sketch objects should be activated in the sketch selection modes by edit operation start
847   // in case of creation operation, there is an active widget, which activates own selection mode
848   if (aFOperation->isEditOperation() && aHasPlane)
849     aConnector->activateModuleSelectionModes();
850 }
851
852 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
853 {
854   myIsMouseOverWindow = false;
855   myIsConstraintsShown = true;
856
857   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
858
859   DataPtr aData = myCurrentSketch->data();
860   if (!aData->isValid()) {
861     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
862     // The sketch was aborted
863     myCurrentSketch = CompositeFeaturePtr();
864     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
865
866     // Erase all sketcher objects
867     QStringList aSketchIds = sketchOperationIdList();
868     QObjectPtrList aObjects = aDisplayer->displayedObjects();
869     foreach (ObjectPtr aObj, aObjects) {
870       DataPtr aObjData = aObj->data();
871       if (!aObjData->isValid())
872         aObj->setDisplayed(false);
873     }
874   }
875   else {
876     // Hide all sketcher sub-Objects
877     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
878       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
879       std::list<ResultPtr> aResults = aFeature->results();
880       std::list<ResultPtr>::const_iterator aIt;
881       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
882         (*aIt)->setDisplayed(false);
883       }
884       aFeature->setDisplayed(false);
885     }
886     // Display sketcher result
887     std::list<ResultPtr> aResults = myCurrentSketch->results();
888     std::list<ResultPtr>::const_iterator aIt;
889     Events_Loop* aLoop = Events_Loop::loop();
890     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
891
892     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
893                                                                            (theOperation);
894     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
895       if (!aFOperation->isDisplayedOnStart(*aIt)) {
896         (*aIt)->setDisplayed(true);
897         // this display event is needed because sketch already may have "displayed" state,
898         // but not displayed while it is still active (issue 613, abort of existing sketch)
899         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
900       }
901     }
902     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
903       myCurrentSketch->setDisplayed(true);
904     
905     myCurrentSketch = CompositeFeaturePtr();
906     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
907
908     Events_Loop::loop()->flush(aDispEvent);
909   }
910   // restore the module selection modes, which were changed on startSketch
911   aConnector->activateModuleSelectionModes();
912   aConnector->workshop()->displayer()->activateTrihedron(false);
913 }
914
915 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
916 {
917   if (canChangeCursor(theOperation) && myIsMouseOverWindow)
918     QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
919 }
920
921 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
922 {
923   myIsMouseOverViewProcessed = true;
924   operationMgr()->onValidateOperation();
925   if (canChangeCursor(theOperation))
926     QApplication::restoreOverrideCursor();
927 }
928
929 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
930 {
931   if (isNestedCreateOperation(theOperation)) {
932     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
933                                                                              (theOperation);
934     if (aFOperation) {
935       FeaturePtr aFeature = aFOperation->feature();
936       // it is necessary to check the the feature data validity because
937       // some kind of features are removed by an operation commit(the macro state of a feature)
938       if (aFeature.get() && aFeature->data()->isValid()) {
939         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
940       }
941     }
942   }
943 }
944
945 bool PartSet_SketcherMgr::canUndo() const
946 {
947   return isNestedCreateOperation(getCurrentOperation());
948 }
949
950 bool PartSet_SketcherMgr::canRedo() const
951 {
952   return isNestedCreateOperation(getCurrentOperation());
953 }
954
955 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
956 {
957   bool aCanErase = true;
958   // when the sketch operation is active, results of sketch sub-feature can not be hidden
959   if (myCurrentSketch.get()) {
960     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
961     if (aResult.get()) {
962       // Display sketcher objects
963       for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
964
965         FeaturePtr aFeature = myCurrentSketch->subFeature(i);
966         std::list<ResultPtr> aResults = aFeature->results();
967         std::list<ResultPtr>::const_iterator anIt;
968         for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
969           aCanErase = *anIt != aResult;
970         }
971       }
972     }
973   }
974   return aCanErase;
975 }
976
977 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
978 {
979   bool aCanDisplay = true;
980
981   bool aHasActiveSketch = activeSketch().get() != NULL;
982   if (aHasActiveSketch) {
983     // 1. the sketch feature should not be displayed during the sketch active operation
984     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch 
985     // nested features can be visualized
986     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
987     if (aFeature.get() != NULL && aFeature == activeSketch()) {
988       aCanDisplay = false;
989     }
990   }
991   else { // there are no an active sketch
992     // 2. sketch sub-features should not be visualized if the sketch operation is not active
993     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
994     if (aFeature.get() != NULL) {
995       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
996                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
997       if (aSketchFeature.get()) {
998         aCanDisplay = false;
999       }
1000     }
1001   }
1002
1003   // 3. the method should not filter the objects, which are not related to the current operation.
1004   // The object is filtered just if it is a current operation feature or this feature result
1005   bool isObjectFound = false;
1006   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1007                                                                (getCurrentOperation());
1008   if (aFOperation) {
1009     FeaturePtr aFeature = aFOperation->feature();
1010     if (aFeature.get()) {
1011       std::list<ResultPtr> aResults = aFeature->results();
1012       if (theObject == aFeature)
1013         isObjectFound = true;
1014       else {
1015         std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1016         for (; anIt != aLast && !isObjectFound; anIt++) {
1017           isObjectFound = *anIt == theObject;
1018         }
1019       }
1020     }
1021   }
1022   if (!isObjectFound) 
1023     return aCanDisplay;
1024   
1025   // 4. For created nested feature operation do not display the created feature if
1026   // the mouse curstor leaves the OCC window.
1027   // The correction cases, which ignores this condition:
1028   // a. the property panel values modification
1029   // b. the popup menu activated
1030   // c. widget editor control
1031   #ifndef DEBUG_DO_NOT_BY_ENTER
1032   if (aCanDisplay && isNestedCreateOperation(getCurrentOperation())) {
1033     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1034     ModuleBase_WidgetEditor* anEditorWdg = anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1035     // the active widget editor should not influence here. The presentation should be visible always
1036     // when this widget is active.
1037     if (!anEditorWdg && !myIsPopupMenuActive) {
1038       // during a nested create operation, the feature is redisplayed only if the mouse over view
1039       // of there was a value modified in the property panel after the mouse left the view
1040       aCanDisplay = canDisplayCurrentCreatedFeature();
1041     }
1042   }
1043   #endif
1044   return aCanDisplay;
1045 }
1046
1047 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1048 {
1049   bool aCanDisplay = myIsMouseOverWindow;
1050   if (!aCanDisplay) {
1051     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1052     if (anActiveWidget)
1053       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1054   }
1055   return aCanDisplay;
1056 }
1057
1058 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1059 {
1060   return isNestedCreateOperation(theOperation) ||
1061          myModule->sketchReentranceMgr()->isInternalEditActive();
1062 }
1063
1064 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1065 {
1066   bool isFoundObject = false;
1067
1068   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1069   if (anObjectFeature.get()) {
1070     int aSize = myCurrentSketch->numberOfSubs();
1071     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1072       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1073       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1074     }
1075   }
1076   return isFoundObject;
1077 }
1078
1079 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
1080 {
1081   if (myPlaneFilter.IsNull()) 
1082    myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
1083
1084   myPlaneFilter->setPlane(thePln);
1085 }
1086
1087 void PartSet_SketcherMgr::getCurrentSelection(const FeaturePtr& theFeature,
1088                                               const FeaturePtr& theSketch,
1089                                               ModuleBase_IWorkshop* theWorkshop,
1090                                               FeatureToSelectionMap& theSelection)
1091 {
1092   if (theFeature.get() == NULL)
1093     return;
1094
1095   std::set<AttributePtr> aSelectedAttributes;
1096   std::set<ResultPtr> aSelectedResults;
1097
1098   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1099   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
1100   if (!aContext.IsNull()) {
1101     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1102     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1103
1104     std::list<ResultPtr> aResults = theFeature->results();
1105     std::list<ResultPtr>::const_iterator aIt;
1106     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1107     {
1108       ResultPtr aResult = *aIt;
1109       AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1110       if (aAISObj.get() == NULL)
1111         continue;
1112       Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1113       for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
1114       {
1115         Handle(SelectMgr_EntityOwner) anOwner = aContext->SelectedOwner();
1116         if (anOwner->Selectable() != anAISIO)
1117           continue;
1118         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1119                                aSelectedAttributes, aSelectedResults);
1120       }
1121       for (aContext->InitDetected(); aContext->MoreDetected(); aContext->NextDetected()) {
1122         Handle(SelectMgr_EntityOwner) anOwner = aContext->DetectedOwner();
1123         if (anOwner.IsNull())
1124           continue;
1125         if (anOwner->Selectable() != anAISIO)
1126           continue;
1127         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1128                                aSelectedAttributes, aSelectedResults);
1129       }
1130     }
1131   }
1132   theSelection[theFeature] = std::make_pair(aSelectedAttributes, aSelectedResults);
1133 }
1134
1135 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1136                                              const FeaturePtr& theSketch,
1137                                              ModuleBase_IWorkshop* theWorkshop,
1138                                              const FeatureToSelectionMap& theSelection,
1139                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1140 {
1141   if (theFeature.get() == NULL)
1142     return;
1143
1144   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1145   std::set<AttributePtr> aSelectedAttributes = anIt.value().first;
1146   std::set<ResultPtr> aSelectedResults = anIt.value().second;
1147
1148   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1149
1150   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1151   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1152
1153   // 1. found the feature's owners. Check the AIS objects of the constructions
1154   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1155   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1156     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1157
1158     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1159     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1160     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1161       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1162       if (!anOwner.IsNull())
1163         theOwnersToSelect.Add(anOwner);
1164     }
1165   }
1166
1167   // 2. found the feature results's owners
1168   std::list<ResultPtr> aResults = theFeature->results();
1169   std::list<ResultPtr>::const_iterator aIt;
1170   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1171   {
1172     ResultPtr aResult = *aIt;
1173     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1174     if (aAISObj.get() == NULL)
1175       continue; 
1176     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1177
1178     SelectMgr_IndexedMapOfOwner aSelectedOwners;  
1179     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1180     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1181       Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1182       if ( anOwner.IsNull() || !anOwner->HasShape() )
1183         continue;
1184       const TopoDS_Shape& aShape = anOwner->Shape();
1185       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1186       if (aShapeType == TopAbs_VERTEX) {
1187         AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1188         if (aPntAttr.get() != NULL &&
1189             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end()) {
1190           theOwnersToSelect.Add(anOwner);
1191         }
1192       }
1193       else if (aShapeType == TopAbs_EDGE) {
1194         bool aFound = aSelectedResults.find(aResult) != aSelectedResults.end();
1195         if (aSelectedResults.find(aResult) != aSelectedResults.end() &&
1196             theOwnersToSelect.FindIndex(anOwner) <= 0)
1197           theOwnersToSelect.Add(anOwner);
1198       }
1199     }
1200   }
1201 }
1202
1203 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget, const bool isToConnect)
1204 {
1205   if (isToConnect) {
1206     connect(theWidget, SIGNAL(beforeValuesChanged()),
1207             this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1208     connect(theWidget, SIGNAL(afterValuesChanged()),
1209             this, SLOT(onAfterValuesChangedInPropertyPanel()));
1210   }
1211   else {
1212     disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1213                 this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1214     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1215                 this, SLOT(onAfterValuesChangedInPropertyPanel()));
1216   }
1217 }
1218
1219 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1220 {
1221   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1222                                                                            (getCurrentOperation());
1223   if (aFOperation) {
1224     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1225         PartSet_SketcherMgr::isNestedSketchOperation(aFOperation) &&
1226         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1227       FeaturePtr aFeature = aFOperation->feature();
1228       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1229     }
1230   }
1231 }
1232
1233 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1234 {
1235   return myModule->workshop()->currentOperation();
1236 }
1237
1238 //**************************************************************
1239 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1240 {
1241   ModuleBase_ModelWidget* aWidget = 0;
1242   ModuleBase_Operation* anOperation = getCurrentOperation();
1243   if (anOperation) {
1244     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1245     if (aPanel)
1246       aWidget = aPanel->activeWidget();
1247   }
1248   return aWidget;
1249 }
1250
1251 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1252                                            const bool isEditOperation,
1253                                            const bool isToDisplay,
1254                                            const bool isFlushRedisplay)
1255 {
1256   #ifdef DEBUG_DO_NOT_BY_ENTER
1257   return;
1258   #endif
1259
1260   if (isEditOperation || !theFeature.get())
1261     return;
1262
1263   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1264   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1265
1266   // 1. change visibility of the object itself, here the presentable object is processed,
1267   // e.g. constraints features
1268   //FeaturePtr aFeature = aFOperation->feature();
1269   std::list<ResultPtr> aResults = theFeature->results();
1270   if (isToDisplay)
1271     theFeature->setDisplayed(true);
1272   else
1273     theFeature->setDisplayed(false);
1274
1275   // change visibility of the object results, e.g. non-constraint features
1276   std::list<ResultPtr>::const_iterator aIt;
1277   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1278     if (isToDisplay) {
1279       (*aIt)->setDisplayed(true);
1280     }
1281     else {
1282       (*aIt)->setDisplayed(false);
1283     }
1284   }
1285   if (isFlushRedisplay)
1286     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1287 }
1288
1289 void PartSet_SketcherMgr::storeSelection(const bool theHighlightedOnly)
1290 {
1291   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1292   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1293   QList<ModuleBase_ViewerPrs> aHighlighted = aSelect->getHighlighted();
1294
1295   QList<FeaturePtr> aFeatureList;
1296   if (theHighlightedOnly) {
1297     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1298   }
1299   else {
1300     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1301
1302     QList<ModuleBase_ViewerPrs> aSelected = aSelect->getSelected(ModuleBase_ISelection::AllControls);
1303     fillFeatureList(aSelected, myCurrentSketch, aFeatureList);
1304   }
1305
1306   // 1. it is necessary to save current selection in order to restore it after the features moving
1307   myCurrentSelection.clear();
1308   QList<FeaturePtr>::const_iterator anIt = aFeatureList.begin(), aLast = aFeatureList.end();
1309   for (; anIt != aLast; anIt++) {
1310     getCurrentSelection(*anIt, myCurrentSketch, aWorkshop, myCurrentSelection);
1311   }
1312   //qDebug(QString("  storeSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1313 }
1314
1315 void PartSet_SketcherMgr::restoreSelection()
1316 {
1317   //qDebug(QString("restoreSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1318   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1319   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1320   FeatureToSelectionMap::const_iterator aSIt = myCurrentSelection.begin(),
1321                                         aSLast = myCurrentSelection.end();
1322   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1323   for (; aSIt != aSLast; aSIt++) {
1324     anOwnersToSelect.Clear();
1325     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, myCurrentSelection,
1326                         anOwnersToSelect);
1327     aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1328   }
1329 }
1330
1331 void PartSet_SketcherMgr::onShowConstraintsToggle(bool theOn)
1332 {
1333   if (myIsConstraintsShown == theOn)
1334     return;
1335   if (myCurrentSketch.get() == NULL)
1336     return;
1337
1338   myIsConstraintsShown = theOn;
1339
1340   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1341   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1342
1343   const QStringList& aConstrIds = constraintsIdList();
1344   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1345     FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1346     if (aConstrIds.contains(QString(aSubFeature->getKind().c_str()))) {
1347       if (myIsConstraintsShown) 
1348         aSubFeature->setDisplayed(true);
1349       else
1350         aSubFeature->setDisplayed(false);
1351     }
1352   }
1353   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1354 }
1355
1356 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1357 {
1358   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1359   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1360   XGUI_Workshop* aWorkshop = aConnector->workshop();
1361
1362   return aWorkshop->operationMgr();
1363 }
1364