Salome HOME
7fcebed5a10f52421f9874413936c0f65e1b59a4
[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 #include "PartSet_ResultSketchPrs.h"
16
17 #include <XGUI_ModuleConnector.h>
18 #include <XGUI_Displayer.h>
19 #include <XGUI_Workshop.h>
20 #include <XGUI_ContextMenuMgr.h>
21 #include <XGUI_Selection.h>
22 #include <XGUI_SelectionMgr.h>
23 #include <XGUI_ModuleConnector.h>
24 #include <XGUI_PropertyPanel.h>
25 #include <XGUI_ViewerProxy.h>
26 #include <XGUI_OperationMgr.h>
27 #include <XGUI_Tools.h>
28
29 #include <ModuleBase_IPropertyPanel.h>
30 #include <ModuleBase_ISelection.h>
31 #include <ModuleBase_IViewer.h>
32 #include <ModuleBase_IWorkshop.h>
33 #include <ModuleBase_IViewWindow.h>
34 #include <ModuleBase_ModelWidget.h>
35 #include <ModuleBase_Operation.h>
36 #include <ModuleBase_OperationFeature.h>
37 #include <ModuleBase_Operation.h>
38 #include <ModuleBase_WidgetEditor.h>
39 #include <ModuleBase_ViewerPrs.h>
40 #include <ModuleBase_Tools.h>
41
42 #include <GeomDataAPI_Point2D.h>
43
44 #include <Events_Loop.h>
45
46 #include <SketchPlugin_Line.h>
47 #include <SketchPlugin_Sketch.h>
48 #include <SketchPlugin_Point.h>
49 #include <SketchPlugin_Arc.h>
50 #include <SketchPlugin_Circle.h>
51 #include <SketchPlugin_ConstraintLength.h>
52 #include <SketchPlugin_ConstraintDistance.h>
53 #include <SketchPlugin_ConstraintParallel.h>
54 #include <SketchPlugin_ConstraintPerpendicular.h>
55 #include <SketchPlugin_ConstraintRadius.h>
56 #include <SketchPlugin_ConstraintRigid.h>
57 #include <SketchPlugin_ConstraintHorizontal.h>
58 #include <SketchPlugin_ConstraintVertical.h>
59 #include <SketchPlugin_ConstraintEqual.h>
60 #include <SketchPlugin_ConstraintTangent.h>
61 #include <SketchPlugin_ConstraintCoincidence.h>
62 #include <SketchPlugin_ConstraintFillet.h>
63 #include <SketchPlugin_ConstraintMirror.h>
64 #include <SketchPlugin_ConstraintAngle.h>
65 #include <SketchPlugin_ConstraintCollinear.h>
66 #include <SketchPlugin_ConstraintMiddle.h>
67 #include <SketchPlugin_MultiRotation.h>
68 #include <SketchPlugin_MultiTranslation.h>
69 #include <SketchPlugin_IntersectionPoint.h>
70
71 #include <SketcherPrs_Tools.h>
72
73 #include <SelectMgr_IndexedMapOfOwner.hxx>
74 #include <StdSelect_BRepOwner.hxx>
75
76 //#include <AIS_DimensionSelectionMode.hxx>
77 #include <AIS_Shape.hxx>
78 #include <AIS_Dimension.hxx>
79
80 #include <ModelAPI_Events.h>
81 #include <ModelAPI_Session.h>
82 #include <ModelAPI_AttributeString.h>
83
84 #include <QMouseEvent>
85 #include <QApplication>
86 #include <QCursor>
87 #include <QMessageBox>
88
89 //#define DEBUG_DO_NOT_BY_ENTER
90
91 //#define DEBUG_CURSOR
92
93 /// Returns list of unique objects by sum of objects from List1 and List2
94 /*QList<ModuleBase_ViewerPrsPtr> getSumList(const QList<ModuleBase_ViewerPrsPtr>& theList1,
95                                        const QList<ModuleBase_ViewerPrsPtr>& theList2)
96 {
97   QList<ModuleBase_ViewerPrsPtr> aRes;
98   foreach (ModuleBase_ViewerPrsPtr aPrs, theList1) {
99     if (!aRes.contains(aPrs))
100       aRes.append(aPrs);
101   }
102   foreach (ModuleBase_ViewerPrsPtr aPrs, theList2) {
103     if (!aRes.contains(aPrs))
104       aRes.append(aPrs);
105   }
106   return aRes;
107 }*/
108
109 // Fills the list of features the list of selected presentations.
110 // \param theList a list of selected presentations
111 // \param theSketch a sketch to project a vertex shape of a presentation to the plane
112 // and find the corresponded attribute
113 // \param theFeatureList  an output list of features
114 void fillFeatureList(const QList<ModuleBase_ViewerPrsPtr>& theList,
115                      const FeaturePtr theSketch,
116                      QList<FeaturePtr>& theFeatureList)
117 {
118   QList<ModuleBase_ViewerPrsPtr> aRes;
119
120   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = theList.begin(),
121                                               aLast = theList.end();
122   for (; anIt != aLast; anIt++)
123   {
124     ModuleBase_ViewerPrsPtr aPrs = *anIt;
125     FeaturePtr aFeature = ModelAPI_Feature::feature(aPrs->object());
126     if (aFeature.get()  && !theFeatureList.contains(aFeature))
127       theFeatureList.append(aFeature);
128   }
129 }
130
131 /// Fills attribute and result lists by the selected owner. In case if the attribute is found,
132 /// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge, put the function
133 /// result as is to the list of results.
134 /// \param theOwner a viewer selected owner
135 /// \param theFeature a feature, where the attribute is searched
136 /// \param theSketch a current sketch
137 /// \param theSelectedAttribute an output list of attributes
138 /// \param theSelectedResults an output list of edge results
139 void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
140                             const FeaturePtr& theFeature, const FeaturePtr& theSketch,
141                             const ResultPtr& theResult,
142                             std::set<AttributePtr>& aSelectedAttributes,
143                             std::set<ResultPtr>& aSelectedResults)
144 {
145   Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(theOwner);
146   if (aBRepOwner.IsNull())
147     return;
148   Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(
149                                                                     aBRepOwner->Selectable());
150   if (aBRepOwner->HasShape()) {
151     const TopoDS_Shape& aShape = aBRepOwner->Shape();
152     TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
153     if (aShapeType == TopAbs_VERTEX) {
154       AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature,
155                                                                     aShape, theSketch);
156       if (aPntAttr.get() != NULL)
157         aSelectedAttributes.insert(aPntAttr);
158     }
159     else if (aShapeType == TopAbs_EDGE &&
160              aSelectedResults.find(theResult) == aSelectedResults.end()) {
161       aSelectedResults.insert(theResult);
162     }
163   }
164 }
165
166 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
167   : QObject(theModule), myModule(theModule), myIsDragging(false), myDragDone(false),
168     myIsMouseOverWindow(false),
169     myIsMouseOverViewProcessed(true), myPreviousUpdateViewerEnabled(true),
170     myIsPopupMenuActive(false)
171 {
172   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
173   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
174
175   myPreviousDrawModeEnabled = true;//aViewer->isSelectionEnabled();
176
177   connect(aViewer, SIGNAL(mousePress(ModuleBase_IViewWindow*, QMouseEvent*)),
178           this, SLOT(onMousePressed(ModuleBase_IViewWindow*, QMouseEvent*)));
179
180   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)),
181           this, SLOT(onMouseReleased(ModuleBase_IViewWindow*, QMouseEvent*)));
182
183   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
184           this, SLOT(onMouseMoved(ModuleBase_IViewWindow*, QMouseEvent*)));
185
186   connect(aViewer, SIGNAL(mouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)),
187           this, SLOT(onMouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)));
188
189   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
190   XGUI_Workshop* aWorkshop = aConnector->workshop();
191   connect(aWorkshop, SIGNAL(applicationStarted()), this, SLOT(onApplicationStarted()));
192
193   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
194   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
195   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
196 }
197
198 PartSet_SketcherMgr::~PartSet_SketcherMgr()
199 {
200   if (!myPlaneFilter.IsNull())
201     myPlaneFilter.Nullify();
202 }
203
204 void PartSet_SketcherMgr::onEnterViewPort()
205 {
206   // 1. if the mouse over window, update the next flag. Do not perform update visibility of
207   // created feature because it should be done in onMouseMove(). Some widgets watch
208   // the mouse move and use the cursor position to update own values. If the presentaion is
209   // redisplayed before this update, the feature presentation jumps from reset value to current.
210   myIsMouseOverWindow = true;
211
212   #ifdef DEBUG_DO_NOT_BY_ENTER
213   return;
214   #endif
215
216   if (canChangeCursor(getCurrentOperation())) {
217     QCursor* aCurrentCursor = QApplication::overrideCursor();
218     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
219       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
220 #ifdef DEBUG_CURSOR
221       qDebug("onEnterViewPort() : Qt::CrossCursor");
222 #endif
223     }
224   }
225
226   if (!isNestedCreateOperation(getCurrentOperation()))
227     return;
228
229   operationMgr()->onValidateOperation();
230
231   // we need change displayed state of the current operation feature
232   // if the feature is presentable, e.g. distance construction. It has no results, so workshop does
233   // not accept a signal about the result created. Nothing is shown until mouse is moved out/in view
234   // port. If the isDisplayed flag is true, the presentable feature is displayed as soon as the
235   // presentation becomes valid and redisplay happens
236   //ModuleBase_Operation* aOperation = getCurrentOperation();
237   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
238                                                                            (getCurrentOperation());
239   if (aFOperation) {
240     FeaturePtr aFeature = aFOperation->feature();
241     if (aFeature.get() && aFeature->data()->isValid()) {
242       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature), false);
243     }
244   }
245 }
246
247 void PartSet_SketcherMgr::onLeaveViewPort()
248 {
249   myIsMouseOverViewProcessed = false;
250   myIsMouseOverWindow = false;
251
252   #ifdef DEBUG_DO_NOT_BY_ENTER
253   return;
254   #endif
255
256   if (canChangeCursor(getCurrentOperation())) {
257     QApplication::restoreOverrideCursor();
258 #ifdef DEBUG_CURSOR
259     qDebug("onLeaveViewPort() : None");
260 #endif
261   }
262
263   if (!isNestedCreateOperation(getCurrentOperation()))
264     return;
265
266   // the method should be performed if the popup menu is called,
267   // the reset of the current widget should not happen
268   if (myIsPopupMenuActive)
269     return;
270
271   // it is important to validate operation here only if sketch entity create operation is active
272   // because at this operation we reacts to the mouse leave/enter view port
273   operationMgr()->onValidateOperation();
274
275   // 2. if the mouse IS NOT over window, reset the active widget value and hide the presentation
276   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
277   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
278   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
279   // disable the viewer update in order to avoid visualization of redisplayed feature in viewer
280   // obtained after reset value
281   bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
282   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
283   if (anActiveWidget)
284     anActiveWidget->reset();
285
286   // hides the presentation of the current operation feature
287   // the feature is to be erased here, but it is correct to call canDisplayObject because
288   // there can be additional check (e.g. editor widget in distance constraint)
289   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
290                                                                            (getCurrentOperation());
291   if (aFOperation) {
292     FeaturePtr aFeature = aFOperation->feature();
293     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
294   }
295   // we should update viewer after the presentation are hidden in the viewer
296   // otherwise the reset presentation(line) appears in the viewer(by quick move from viewer to PP)
297   aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
298 }
299
300 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
301 {
302   if (!isNestedEditOperation(getCurrentOperation()) ||
303       myModule->sketchReentranceMgr()->isInternalEditActive())
304     return;
305   // it is necessary to save current selection in order to restore it after the values are modifed
306   storeSelection();
307
308   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
309   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
310   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
311   myPreviousUpdateViewerEnabled = aDisplayer->enableUpdateViewer(false);
312 }
313
314 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
315 {
316   if (!isNestedEditOperation(getCurrentOperation()) ||
317       myModule->sketchReentranceMgr()->isInternalEditActive()) {
318     myModule->sketchReentranceMgr()->updateInternalEditActiveState();
319     return;
320   }
321   // it is necessary to restore current selection in order to restore it after the values are modified
322   restoreSelection();
323   myCurrentSelection.clear();
324
325   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
326   // viewer happens by deselect/select the modified objects. The flag should be restored after
327   // the selection processing. The update viewer should be also called.
328   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
329   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
330   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
331   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
332   aDisplayer->updateViewer();
333
334
335 }
336
337 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
338 {
339   if (myModule->sketchReentranceMgr()->processMousePressed(theWnd, theEvent))
340     return;
341
342   //get2dPoint(theWnd, theEvent, myClickedPoint);
343
344   if (!(theEvent->buttons() & Qt::LeftButton))
345     return;
346
347   // Clear dragging mode
348   myIsDragging = false;
349
350   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
351   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
352   if (!aViewer->canDragByMouse())
353     return;
354
355   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
356                                                                (getCurrentOperation());
357   if (!aFOperation)
358     return;
359
360   if (aFOperation->isEditOperation()) {
361     // If the current widget is a selector, do nothing, it processes the mouse press
362     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
363     if(anActiveWidget && anActiveWidget->isViewerSelector()) {
364       return;
365     }
366   }
367
368   // Use only for sketch operations
369   if (myCurrentSketch) {
370     if (!PartSet_Tools::sketchPlane(myCurrentSketch))
371       return;
372
373     bool isSketcher = isSketchOperation(aFOperation);
374     bool isSketchOpe = isNestedSketchOperation(aFOperation);
375
376     // Avoid non-sketch operations
377     if ((!isSketchOpe) && (!isSketcher))
378       return;
379
380     bool isEditing = aFOperation->isEditOperation();
381
382     // Ignore creation sketch operation
383     if ((!isSketcher) && (!isEditing))
384       return;
385
386     Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
387     if (!aContext.IsNull()) {
388       // MoveTo in order to highlight current object
389       aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
390       ModuleBase_Tools::selectionInfo(aContext, "PartSet_SketcherMgr::onMousePressed -- MoveTo");
391     }
392     // Remember highlighted objects for editing
393     ModuleBase_ISelection* aSelect = aWorkshop->selection();
394
395     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
396     storeSelection(!aHasShift);
397
398     if (myCurrentSelection.empty()) {
399       if (isSketchOpe && (!isSketcher))
400         // commit previous operation
401         if (!aFOperation->commit())
402           aFOperation->abort();
403       return;
404     }
405     // Init flyout point for radius rotation
406     FeaturePtr aFeature = myCurrentSelection.begin().key();
407
408     if (isSketcher) {
409       myIsDragging = true;
410       get2dPoint(theWnd, theEvent, myCurrentPoint);
411       myDragDone = false;
412
413       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
414       launchEditing();
415       if (aFeature.get() != NULL) {
416         std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
417                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
418       if (aSPFeature.get() && aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID()) {
419           DataPtr aData = aSPFeature->data();
420           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
421           std::shared_ptr<GeomDataAPI_Point2D> aFPAttr = 
422             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
423           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
424         }
425       }
426     } else if (isSketchOpe && isEditing) {
427       // If selected another object commit current result
428       aFOperation->commit();
429
430       myIsDragging = true;
431       get2dPoint(theWnd, theEvent, myCurrentPoint);
432       myDragDone = false;
433
434       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
435
436       // this is temporary commented in order to avoid the following wrong case:
437       // Distance constraint is under edition, double click on the digit -> nothing happens
438       // because QApplication::processEvents() calls onMouseDoubleClick, which try to show editor
439       // but as the prev edit is commited an new one is not started, editor is not shown.
440       // This is necessary in order to finalize previous operation
441       //QApplication::processEvents();
442       launchEditing();
443     }
444   }
445 }
446
447 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
448 {
449   if (myModule->sketchReentranceMgr()->processMouseReleased(theWnd, theEvent))
450     return;
451
452   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
453   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
454   if (!aViewer->canDragByMouse())
455     return;
456   ModuleBase_Operation* aOp = getCurrentOperation();
457   if (aOp) {
458     if (isNestedSketchOperation(aOp)) {
459       //get2dPoint(theWnd, theEvent, myClickedPoint);
460
461       // Only for sketcher operations
462       if (myIsDragging) {
463         if (myDragDone) {
464           //aOp->commit();
465           myCurrentSelection.clear();
466           /*Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
467           if (!aContext.IsNull()) {
468           // Reselect edited object
469           aContext->MoveTo(theEvent->x(), theEvent->y(), theWnd->v3dView());
470           if (theEvent->modifiers() & Qt::ShiftModifier)
471             aContext->ShiftSelect();
472           else
473             aContext->Select();
474           */
475         }
476       }
477     }
478   }
479
480   aWorkshop->viewer()->enableDrawMode(myPreviousDrawModeEnabled);
481   myIsDragging = false;
482 }
483
484 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
485 {
486   if (myModule->sketchReentranceMgr()->processMouseMoved(theWnd, theEvent))
487     return;
488
489   if (isNestedCreateOperation(getCurrentOperation()) && !myIsMouseOverViewProcessed) {
490     myIsMouseOverViewProcessed = true;
491     // 1. perform the widget mouse move functionality and display the presentation
492     // the mouse move should be processed in the widget, if it can in order to visualize correct
493     // presentation. These widgets correct the feature attribute according to the mouse position
494     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
495     PartSet_WidgetPoint2D* aPoint2DWdg = dynamic_cast<PartSet_WidgetPoint2D*>(anActiveWidget);
496     if (aPoint2DWdg) {
497       aPoint2DWdg->onMouseMove(theWnd, theEvent);
498     }
499     PartSet_WidgetPoint2dDistance* aDistanceWdg = dynamic_cast<PartSet_WidgetPoint2dDistance*>
500                                                                 (anActiveWidget);
501     if (aDistanceWdg) {
502       aDistanceWdg->onMouseMove(theWnd, theEvent);
503     }
504     // the feature is to be erased here, but it is correct to call canDisplayObject because
505     // there can be additional check (e.g. editor widget in distance constraint)
506     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
507                                                                              (getCurrentOperation());
508     if (aFOperation) {
509       FeaturePtr aFeature = aFOperation->feature();
510       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
511     }
512   }
513
514   //myClickedPoint.clear();
515
516   if (myIsDragging) {
517     // 1. the current selection is saved in the mouse press method in order to restore it after moving
518     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
519     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
520     // deselected). This flag should be restored in the slot, processed the mouse release signal.
521
522     ModuleBase_Operation* aCurrentOperation = getCurrentOperation();
523     if (!aCurrentOperation)
524       return;
525     if (isSketchOperation(aCurrentOperation))
526       return; // No edit operation activated
527
528     Handle(V3d_View) aView = theWnd->v3dView();
529     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
530     double aX, aY;
531     PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, aY);
532     double dX =  aX - myCurrentPoint.myCurX;
533     double dY =  aY - myCurrentPoint.myCurY;
534
535     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
536     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
537     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
538     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
539     // viewer happens by deselect/select the modified objects. The flag should be restored after
540     // the selection processing. The update viewer should be also called.
541     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
542
543     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
544     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
545     FeatureToSelectionMap::const_iterator anIt = myCurrentSelection.begin(),
546                                           aLast = myCurrentSelection.end();
547     // 4. the features and attributes modification(move)
548     bool isModified = false;
549     for (; anIt != aLast; anIt++) {
550       FeaturePtr aFeature = anIt.key();
551
552       std::set<AttributePtr> anAttributes = anIt.value().first;
553       // Process selection by attribute: the priority to the attribute
554       if (!anAttributes.empty()) {
555         std::set<AttributePtr>::const_iterator anAttIt = anAttributes.begin(),
556                                                anAttLast = anAttributes.end();
557         for (; anAttIt != anAttLast; anAttIt++) {
558           AttributePtr anAttr = *anAttIt;
559           if (anAttr.get() == NULL)
560             continue;
561           std::string aAttrId = anAttr->id();
562           DataPtr aData = aFeature->data();
563           if (aData->isValid()) {
564             std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
565               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
566             if (aPoint.get() != NULL) {
567               bool isImmutable = aPoint->setImmutable(true);
568               aPoint->move(dX, dY);
569               isModified = true;
570               ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
571               aPoint->setImmutable(isImmutable);
572             }
573           }
574         }
575       } else {
576         // Process selection by feature
577         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
578           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
579         if (aSketchFeature) {
580           aSketchFeature->move(dX, dY);
581           isModified = true;
582           ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
583         }
584       }
585     }
586     // the modified state of the current operation should be updated if there are features, which
587     // were changed here
588     if (isModified) {
589       aCurrentOperation->onValuesChanged();
590     }
591     Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
592     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
593
594     // 5. it is necessary to save current selection in order to restore it after the features moving
595     restoreSelection();
596     // 6. restore the update viewer flag and call this update
597     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
598     aDisplayer->updateViewer();
599
600     myDragDone = true;
601     myCurrentPoint.setValue(aX, aY);
602   }
603 }
604
605 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
606 {
607   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
608                                                                (getCurrentOperation());
609   if (aFOperation && aFOperation->isEditOperation()) {
610     std::string aId = aFOperation->id().toStdString();
611     if (isDistanceOperation(aFOperation))
612     {
613       // Activate dimension value editing on double click
614       ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
615       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
616       // Find corresponded widget to activate value editing
617       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
618         if (aWgt->attributeID() == SketchPlugin_Constraint::VALUE() ||
619             aWgt->attributeID() == SketchPlugin_ConstraintAngle::ANGLE_VALUE_ID()) {
620           PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
621           if (anEditor)
622             anEditor->showPopupEditor();
623           return;
624         }
625       }
626     }
627   }
628 }
629
630 void PartSet_SketcherMgr::onApplicationStarted()
631 {
632   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
633   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
634   XGUI_Workshop* aWorkshop = aConnector->workshop();
635   PartSet_SketcherReetntrantMgr* aReentranceMgr = myModule->sketchReentranceMgr();
636
637   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
638   if (aPropertyPanel) {
639     //connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
640     //        this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
641
642     connect(aPropertyPanel, SIGNAL(noMoreWidgets(const std::string&)),
643             aReentranceMgr, SLOT(onNoMoreWidgets(const std::string&)));
644     connect(aPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
645             aReentranceMgr, SLOT(onWidgetActivated()));
646   }
647
648   XGUI_ViewerProxy* aViewerProxy = aWorkshop->viewer();
649   connect(aViewerProxy, SIGNAL(enterViewPort()), this, SLOT(onEnterViewPort()));
650   connect(aViewerProxy, SIGNAL(leaveViewPort()), this, SLOT(onLeaveViewPort()));
651
652   XGUI_ContextMenuMgr* aContextMenuMgr = aWorkshop->contextMenuMgr();
653   connect(aContextMenuMgr, SIGNAL(beforeContextMenu()), this, SLOT(onBeforeContextMenu()));
654   connect(aContextMenuMgr, SIGNAL(afterContextMenu()), this, SLOT(onAfterContextMenu()));
655 }
656
657 //void PartSet_SketcherMgr::onBeforeWidgetActivated(ModuleBase_ModelWidget* theWidget)
658 //{
659   //if (!myClickedPoint.myIsInitialized)
660   //  return;
661
662   //ModuleBase_Operation* aOperation = getCurrentOperation();
663   // the distance constraint feature should not use the clickedd point
664   // this is workaround in order to don't throw down the flyout point value,
665   // set by execute() method of these type of features
666   //if (isDistanceOperation(aOperation))
667   //  return;
668
669   //PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(theWidget);
670   //if (aPnt2dWgt) {
671   //  aPnt2dWgt->setPoint(myClickedPoint.myCurX, myClickedPoint.myCurY);
672   //}
673 //}
674
675 void PartSet_SketcherMgr::onBeforeContextMenu()
676 {
677   myIsPopupMenuActive = true;
678 }
679
680 void PartSet_SketcherMgr::onAfterContextMenu()
681 {
682   myIsPopupMenuActive = false;
683 }
684
685 void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent, 
686                                      Point& thePoint)
687 {
688   Handle(V3d_View) aView = theWnd->v3dView();
689   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
690   double aX, anY;
691   PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, anY);
692   thePoint.setValue(aX, anY);
693 }
694
695 void PartSet_SketcherMgr::launchEditing()
696 {
697   if (!myCurrentSelection.empty()) {
698     FeaturePtr aFeature = myCurrentSelection.begin().key();
699     std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
700               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
701     if (aSPFeature && (!aSPFeature->isExternal())) {
702       myModule->editFeature(aSPFeature);
703     }
704   }
705 }
706
707 bool PartSet_SketcherMgr::sketchSolverError()
708 {
709   bool anError = false;
710   CompositeFeaturePtr aSketch = activeSketch();
711   if (aSketch.get()) {
712     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
713     anError = !aAttributeString->value().empty();
714   }
715   return anError;
716 }
717
718 QString PartSet_SketcherMgr::getFeatureError(const FeaturePtr& theFeature)
719 {
720   QString anError = "";
721   if (!theFeature.get() || !theFeature->data()->isValid())
722     return anError;
723
724   CompositeFeaturePtr aSketch = activeSketch();
725   if (aSketch.get() && aSketch == theFeature) {
726     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
727     anError = aAttributeString->value().c_str();
728   }
729   return anError;
730 }
731
732 void PartSet_SketcherMgr::clearClickedFlags()
733 {
734   //myClickedPoint.clear();
735   myCurrentPoint.clear();
736 }
737
738 const QStringList& PartSet_SketcherMgr::sketchOperationIdList()
739 {
740   static QStringList aIds;
741   if (aIds.size() == 0) {
742     aIds << SketchPlugin_Line::ID().c_str();
743     aIds << SketchPlugin_Point::ID().c_str();
744     aIds << SketchPlugin_Arc::ID().c_str();
745     aIds << SketchPlugin_Circle::ID().c_str();
746     aIds << SketchPlugin_ConstraintFillet::ID().c_str();
747     aIds << SketchPlugin_IntersectionPoint::ID().c_str();
748     // TODO
749     // SketchRectangle is a python feature, so its ID is passed just as a string
750     aIds << "SketchRectangle";
751     aIds.append(replicationsIdList());
752     aIds.append(constraintsIdList());
753   }
754   return aIds;
755 }
756
757 const QStringList& PartSet_SketcherMgr::replicationsIdList()
758 {
759   static QStringList aReplicationIds;
760   if (aReplicationIds.size() == 0) {
761     aReplicationIds << SketchPlugin_ConstraintMirror::ID().c_str();
762     aReplicationIds << SketchPlugin_MultiRotation::ID().c_str();
763     aReplicationIds << SketchPlugin_MultiTranslation::ID().c_str();
764   }
765   return aReplicationIds;
766 }
767
768 const QStringList& PartSet_SketcherMgr::constraintsIdList()
769 {
770   static QStringList aConstraintIds;
771   if (aConstraintIds.size() == 0) {
772     aConstraintIds << SketchPlugin_ConstraintLength::ID().c_str();
773     aConstraintIds << SketchPlugin_ConstraintDistance::ID().c_str();
774     aConstraintIds << SketchPlugin_ConstraintRigid::ID().c_str();
775     aConstraintIds << SketchPlugin_ConstraintRadius::ID().c_str();
776     aConstraintIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
777     aConstraintIds << SketchPlugin_ConstraintParallel::ID().c_str();
778     aConstraintIds << SketchPlugin_ConstraintHorizontal::ID().c_str();
779     aConstraintIds << SketchPlugin_ConstraintVertical::ID().c_str();
780     aConstraintIds << SketchPlugin_ConstraintEqual::ID().c_str();
781     aConstraintIds << SketchPlugin_ConstraintTangent::ID().c_str();
782     aConstraintIds << SketchPlugin_ConstraintCoincidence::ID().c_str();
783     aConstraintIds << SketchPlugin_ConstraintAngle::ID().c_str();
784     aConstraintIds << SketchPlugin_ConstraintCollinear::ID().c_str();
785     aConstraintIds << SketchPlugin_ConstraintMiddle::ID().c_str();
786   }
787   return aConstraintIds;
788 }
789
790 void PartSet_SketcherMgr::sketchSelectionModes(QIntList& theModes)
791 {
792   theModes.clear();
793
794   theModes.append(SketcherPrs_Tools::Sel_Dimension_Text);
795   theModes.append(SketcherPrs_Tools::Sel_Dimension_Line);
796   theModes.append(SketcherPrs_Tools::Sel_Constraint);
797   theModes.append(TopAbs_VERTEX);
798   theModes.append(TopAbs_EDGE);
799 }
800
801 Handle(AIS_InteractiveObject) PartSet_SketcherMgr::createPresentation(const ResultPtr& theResult)
802 {
803   Handle(AIS_InteractiveObject) aPrs;
804
805   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
806   if (aFeature.get() && aFeature->getKind() == SketchPlugin_Sketch::ID()) {
807     aPrs = new PartSet_ResultSketchPrs(theResult);
808   }
809   return aPrs;
810 }
811
812 bool PartSet_SketcherMgr::isSketchOperation(ModuleBase_Operation* theOperation)
813 {
814   return theOperation && theOperation->id().toStdString() == SketchPlugin_Sketch::ID();
815 }
816
817 bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation)
818 {
819   return theOperation &&
820          PartSet_SketcherMgr::sketchOperationIdList().contains(theOperation->id());
821 }
822
823 bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation)
824 {
825   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
826                                                                (theOperation);
827   return aFOperation && !aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
828 }
829
830 bool PartSet_SketcherMgr::isNestedEditOperation(ModuleBase_Operation* theOperation)
831 {
832   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
833                                                                (theOperation);
834   return aFOperation && aFOperation->isEditOperation() && isNestedSketchOperation(aFOperation);
835 }
836
837 bool PartSet_SketcherMgr::isEntity(const std::string& theId)
838 {
839   return (theId == SketchPlugin_Line::ID()) ||
840          (theId == SketchPlugin_Point::ID()) ||
841          (theId == SketchPlugin_Arc::ID()) ||
842          (theId == SketchPlugin_Circle::ID());
843 }
844
845 bool PartSet_SketcherMgr::isDistanceOperation(ModuleBase_Operation* theOperation)
846 {
847   std::string anId = theOperation ? theOperation->id().toStdString() : "";
848
849   return isDistanceKind(anId);
850 }
851
852 bool PartSet_SketcherMgr::isDistanceKind(std::string& theKind)
853 {
854   return (theKind == SketchPlugin_ConstraintLength::ID()) ||
855          (theKind == SketchPlugin_ConstraintDistance::ID()) ||
856          (theKind == SketchPlugin_ConstraintRadius::ID()) ||
857          (theKind == SketchPlugin_ConstraintAngle::ID());
858 }
859
860 void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
861 {
862   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
863                                                                (getCurrentOperation());
864   if (!aFOperation)
865     return;
866
867   myModule->onViewTransformed();
868
869   // Display all sketcher sub-Objects
870   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFOperation->feature());
871   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
872
873   // Hide sketcher result
874   std::list<ResultPtr> aResults = myCurrentSketch->results();
875   std::list<ResultPtr>::const_iterator aIt;
876   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
877     (*aIt)->setDisplayed(false);
878   }
879   myCurrentSketch->setDisplayed(false);
880
881   // Display sketcher objects
882   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
883     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
884     std::list<ResultPtr> aResults = aFeature->results();
885     std::list<ResultPtr>::const_iterator aIt;
886     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
887       (*aIt)->setDisplayed(true);
888     }
889     aFeature->setDisplayed(true);
890   }
891
892   if(myCirclePointFilter.IsNull()) {
893     myCirclePointFilter = new PartSet_CirclePointFilter(myModule->workshop());
894   }
895
896   myModule->workshop()->viewer()->addSelectionFilter(myCirclePointFilter);
897
898   if (myPlaneFilter.IsNull()) 
899     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
900
901   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
902   bool aHasPlane = false;
903   std::shared_ptr<GeomAPI_Pln> aPln;
904   aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
905   myPlaneFilter->setPlane(aPln);
906
907   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
908   // all displayed objects should be activated in current selection modes according to switched
909   // plane filter
910   if (aPln.get())
911     aConnector->activateModuleSelectionModes();
912 }
913
914 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
915 {
916   myIsMouseOverWindow = false;
917   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
918   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
919   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
920
921   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
922
923   DataPtr aData = myCurrentSketch->data();
924   if (!aData->isValid()) {
925     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
926     // The sketch was aborted
927     myCurrentSketch = CompositeFeaturePtr();
928     // TODO: move this outside of if-else
929     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
930     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
931
932     // Erase all sketcher objects
933     QStringList aSketchIds = sketchOperationIdList();
934     QObjectPtrList aObjects = aDisplayer->displayedObjects();
935     foreach (ObjectPtr aObj, aObjects) {
936       DataPtr aObjData = aObj->data();
937       if (!aObjData->isValid())
938         aObj->setDisplayed(false);
939     }
940   }
941   else {
942     // Hide all sketcher sub-Objects
943     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
944       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
945       std::list<ResultPtr> aResults = aFeature->results();
946       std::list<ResultPtr>::const_iterator aIt;
947       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
948         (*aIt)->setDisplayed(false);
949       }
950       aFeature->setDisplayed(false);
951     }
952     // Display sketcher result
953     std::list<ResultPtr> aResults = myCurrentSketch->results();
954     std::list<ResultPtr>::const_iterator aIt;
955     Events_Loop* aLoop = Events_Loop::loop();
956     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
957
958     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
959                                                                            (theOperation);
960     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
961       if (!aFOperation->isDisplayedOnStart(*aIt)) {
962         (*aIt)->setDisplayed(true);
963         // this display event is needed because sketch already may have "displayed" state,
964         // but not displayed while it is still active (issue 613, abort of existing sketch)
965         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
966       }
967     }
968     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
969       myCurrentSketch->setDisplayed(true);
970     
971     myCurrentSketch = CompositeFeaturePtr();
972
973     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
974     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
975
976     Events_Loop::loop()->flush(aDispEvent);
977   }
978   // restore the module selection modes, which were changed on startSketch
979   aConnector->activateModuleSelectionModes();
980 }
981
982 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
983 {
984   if (canChangeCursor(theOperation) && myIsMouseOverWindow) {
985     QCursor* aCurrentCursor = QApplication::overrideCursor();
986     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
987       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
988 #ifdef DEBUG_CURSOR
989       qDebug("startNestedSketch() : Qt::CrossCursor");
990 #endif
991     }
992   }
993 }
994
995 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
996 {
997   myIsMouseOverViewProcessed = true;
998   operationMgr()->onValidateOperation();
999   if (canChangeCursor(theOperation)) {
1000     QApplication::restoreOverrideCursor();
1001 #ifdef DEBUG_CURSOR
1002     qDebug("stopNestedSketch() : None");
1003 #endif
1004   }
1005 }
1006
1007 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
1008 {
1009   if (isNestedCreateOperation(theOperation)) {
1010     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1011                                                                              (theOperation);
1012     if (aFOperation) {
1013       FeaturePtr aFeature = aFOperation->feature();
1014       // it is necessary to check the the feature data validity because
1015       // some kind of features are removed by an operation commit(the macro state of a feature)
1016       if (aFeature.get() && aFeature->data()->isValid()) {
1017         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
1018       }
1019     }
1020   }
1021 }
1022
1023 void PartSet_SketcherMgr::activatePlaneFilter(const bool& toActivate)
1024 {
1025   if (toActivate)
1026     myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
1027   else
1028     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
1029 }
1030
1031 bool PartSet_SketcherMgr::operationActivatedByPreselection()
1032 {
1033   bool isOperationStopped = false;
1034   ModuleBase_Operation* anOperation = getCurrentOperation();
1035   if(anOperation && PartSet_SketcherMgr::isNestedSketchOperation(anOperation)) {
1036     // Set final definitions if they are necessary
1037     //propertyPanelDefined(aOperation);
1038     /// Commit sketcher operations automatically
1039     /// distance operation are able to show popup editor to modify the distance value
1040     /// after entering the value, the operation should be committed/aborted(by Esc key)
1041     bool aCanCommitOperation = true;
1042     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1043                                                                             (anOperation);
1044     if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation)) {
1045       bool aValueAccepted = setDistanceValueByPreselection(anOperation, myModule->workshop(),
1046                                                            aCanCommitOperation);
1047       if (!aValueAccepted)
1048         return isOperationStopped;
1049     }
1050
1051     if (aCanCommitOperation)
1052       isOperationStopped = anOperation->commit();
1053     else {
1054       anOperation->abort();
1055       isOperationStopped = true;
1056     }
1057   }
1058   return isOperationStopped;
1059 }
1060
1061 bool PartSet_SketcherMgr::canUndo() const
1062 {
1063   return isNestedCreateOperation(getCurrentOperation());
1064 }
1065
1066 bool PartSet_SketcherMgr::canRedo() const
1067 {
1068   return isNestedCreateOperation(getCurrentOperation());
1069 }
1070
1071 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1072 {
1073   bool aCanErase = true;
1074   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1075   if (myCurrentSketch.get()) {
1076     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1077     if (aResult.get()) {
1078       // Display sketcher objects
1079       for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1080
1081         FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1082         std::list<ResultPtr> aResults = aFeature->results();
1083         std::list<ResultPtr>::const_iterator anIt;
1084         for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1085           aCanErase = *anIt != aResult;
1086         }
1087       }
1088     }
1089   }
1090   return aCanErase;
1091 }
1092
1093 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1094 {
1095   bool aCanDisplay = true;
1096
1097   bool aHasActiveSketch = activeSketch().get() != NULL;
1098   if (aHasActiveSketch) {
1099     // 1. the sketch feature should not be displayed during the sketch active operation
1100     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch 
1101     // nested features can be visualized
1102     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1103     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1104       aCanDisplay = false;
1105     }
1106     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1107                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1108     /// some sketch entities should be never shown, e.g. projection feature
1109     if (aSketchFeature.get())
1110       aCanDisplay = aSketchFeature->canBeDisplayed();
1111   }
1112   else { // there are no an active sketch
1113     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1114     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1115     if (aFeature.get() != NULL) {
1116       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1117                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1118       if (aSketchFeature.get()) {
1119         aCanDisplay = false;
1120       }
1121     }
1122   }
1123
1124   // 3. the method should not filter the objects, which are not related to the current operation.
1125   // The object is filtered just if it is a current operation feature or this feature result
1126   if (aCanDisplay) {
1127     bool isObjectFound = false;
1128     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1129                                                                  (getCurrentOperation());
1130     if (aFOperation) {
1131       FeaturePtr aFeature = aFOperation->feature();
1132       if (aFeature.get()) {
1133         std::list<ResultPtr> aResults = aFeature->results();
1134         if (theObject == aFeature)
1135           isObjectFound = true;
1136         else {
1137           std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1138           for (; anIt != aLast && !isObjectFound; anIt++) {
1139             isObjectFound = *anIt == theObject;
1140           }
1141         }
1142       }
1143     }
1144     if (isObjectFound) {
1145       // 4. For created nested feature operation do not display the created feature if
1146       // the mouse curstor leaves the OCC window.
1147       // The correction cases, which ignores this condition:
1148       // a. the property panel values modification
1149       // b. the popup menu activated
1150       // c. widget editor control
1151       #ifndef DEBUG_DO_NOT_BY_ENTER
1152       if (isNestedCreateOperation(getCurrentOperation())) {
1153         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1154         ModuleBase_WidgetEditor* anEditorWdg = anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1155         // the active widget editor should not influence here. The presentation should be visible always
1156         // when this widget is active.
1157         if (!anEditorWdg && !myIsPopupMenuActive) {
1158           // during a nested create operation, the feature is redisplayed only if the mouse over view
1159           // of there was a value modified in the property panel after the mouse left the view
1160           aCanDisplay = canDisplayCurrentCreatedFeature();
1161         }
1162       }
1163       #endif
1164     }
1165   }
1166
1167   // checks the sketcher constraints visibility according to active sketch check box states
1168   if (aCanDisplay) {
1169     bool aProcessed = false;
1170     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1171     if (aFeature.get()) {
1172       bool aConstraintDisplayed = canDisplayConstraint(aFeature, PartSet_Tools::Any, aProcessed);
1173       if (aProcessed)
1174         aCanDisplay = aConstraintDisplayed;
1175     }
1176   }
1177
1178   return aCanDisplay;
1179 }
1180
1181 bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
1182                                              const PartSet_Tools::ConstraintVisibleState& theState,
1183                                              bool& isProcessed) const
1184 {
1185   bool aSwitchedOn = true;
1186
1187   const QStringList& aConstrIds = constraintsIdList();
1188
1189   std::string aKind = theFeature->getKind();
1190   if (aConstrIds.contains(QString(aKind.c_str()))) {
1191     bool isTypedConstraint = false;
1192
1193     switch (theState) {
1194       case PartSet_Tools::Dimensional: {
1195         bool isDistance = isDistanceKind(aKind);
1196         if (isDistance) {
1197           isProcessed = true;
1198           aSwitchedOn = myIsConstraintsShown[theState];
1199         }
1200       }
1201       break;
1202       case PartSet_Tools::Geometrical: {
1203         bool isGeometrical = !isDistanceKind(aKind);
1204         if (isGeometrical) {
1205           isProcessed = true;
1206           aSwitchedOn = myIsConstraintsShown[theState];
1207         }
1208       }
1209       break;
1210       case PartSet_Tools::Any: {
1211         isProcessed = true;
1212         bool isDistance = isDistanceKind(aKind);
1213         if (isDistance)
1214           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Dimensional];
1215         else
1216           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Geometrical];
1217       }
1218       break;
1219     default:
1220       break;
1221     }
1222   }
1223   return aSwitchedOn;
1224 }
1225
1226 /*void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
1227 {
1228   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1229                                                                            (getCurrentOperation());
1230   if (aFOperation && myCurrentSketch.get()) {
1231     // find results of the current operation
1232     // these results should not be proposed to be deleted
1233     FeaturePtr anOperationFeature = aFOperation->feature();
1234     std::list<ResultPtr> anOperationResultList = anOperationFeature->results();
1235     std::set<ResultPtr> anOperationResults;
1236     std::list<ResultPtr>::const_iterator aRIt = anOperationResultList.begin(),
1237                                         aRLast = anOperationResultList.end();
1238     for (; aRIt != aRLast; aRIt++)
1239       anOperationResults.insert(*aRIt);
1240
1241     std::set<FeaturePtr> anObjectsToBeDeleted;
1242     QStringList anObjectsToBeDeletedNames;
1243     std::list<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1244     for (; anIt != aLast; anIt++) {
1245       ObjectPtr anObject = *anIt;
1246       bool aCanErase = true;
1247       // when the sketch operation is active, results of sketch sub-feature can not be hidden
1248       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1249       // the result is found between current feature results
1250       if (anOperationResults.find(aResult) != anOperationResults.end())
1251         continue;
1252
1253       if (aResult.get()) {
1254         // Display sketcher objects
1255         for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1256           FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1257           std::list<ResultPtr> aResults = aFeature->results();
1258           std::list<ResultPtr>::const_iterator anIt;
1259           for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1260             aCanErase = *anIt != aResult;
1261           }
1262         }
1263       }
1264       if (!aCanErase) {
1265         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
1266         if (aFeature.get() && anObjectsToBeDeleted.find(aFeature) == anObjectsToBeDeleted.end()) {
1267           anObjectsToBeDeleted.insert(aFeature);
1268           anObjectsToBeDeletedNames.append(aFeature->name().c_str());
1269         }
1270       }
1271     }
1272     if (!anObjectsToBeDeleted.empty()) {
1273       QString aFeatureNames = anObjectsToBeDeletedNames.join(", ");
1274       QString aMessage = tr("The following features have incorrect presentation and \
1275 will be hidden: %1. Would you like to delete them?")
1276                          .arg(aFeatureNames);
1277       int anAnswer = QMessageBox::question(qApp->activeWindow(), tr("Features hide"),
1278                                            aMessage, QMessageBox::Ok | QMessageBox::Cancel,
1279                                            QMessageBox::Cancel);
1280       if (anAnswer == QMessageBox::Ok) {
1281         QObjectPtrList anObjects;
1282         std::set<FeaturePtr>::const_iterator anIt = anObjectsToBeDeleted.begin(),
1283                                              aLast = anObjectsToBeDeleted.end();
1284         for (; anIt != aLast; anIt++)
1285           anObjects.append(*anIt);
1286         SessionPtr aMgr = ModelAPI_Session::get();
1287         DocumentPtr aDoc = aMgr->activeDocument();
1288         bool aIsOp = aMgr->isOperation();
1289         if (!aIsOp)
1290           aMgr->startOperation();
1291         workshop()->deleteFeatures(anObjects);
1292         //static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
1293         //static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
1294         //Events_Loop::loop()->flush(aDeletedEvent);
1295         //Events_Loop::loop()->flush(aRedispEvent);
1296
1297         if (!aIsOp)
1298           aMgr->finishOperation();
1299       }
1300     }
1301   }
1302 }*/
1303
1304 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1305 {
1306   bool aCanDisplay = myIsMouseOverWindow;
1307   if (!aCanDisplay) {
1308     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1309     if (anActiveWidget)
1310       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1311   }
1312   return aCanDisplay;
1313 }
1314
1315 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1316 {
1317   return isNestedCreateOperation(theOperation) ||
1318          myModule->sketchReentranceMgr()->isInternalEditActive();
1319 }
1320
1321 const QMap<PartSet_Tools::ConstraintVisibleState, bool>& PartSet_SketcherMgr::showConstraintStates()
1322 {
1323   return myIsConstraintsShown;
1324 }
1325
1326 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1327 {
1328   bool isFoundObject = false;
1329
1330   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1331   if (anObjectFeature.get()) {
1332     int aSize = myCurrentSketch->numberOfSubs();
1333     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1334       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1335       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1336     }
1337   }
1338   return isFoundObject;
1339 }
1340
1341 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
1342 {
1343   if (myPlaneFilter.IsNull()) 
1344    myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
1345
1346   myPlaneFilter->setPlane(thePln);
1347 }
1348
1349 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
1350                                                          ModuleBase_IWorkshop* theWorkshop,
1351                                                          bool& theCanCommitOperation)
1352 {
1353   bool isValueAccepted = false;
1354   theCanCommitOperation = false;
1355
1356   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1357                                                                               (theOperation);
1358   FeaturePtr aFeature = aFOperation->feature();
1359   // editor is shown only if all attribute references are filled by preseletion
1360   bool anAllRefAttrInitialized = true;
1361
1362   std::list<AttributePtr> aRefAttrs = aFeature->data()->attributes(
1363                                               ModelAPI_AttributeRefAttr::typeId());
1364   std::list<AttributePtr>::const_iterator anIt = aRefAttrs.begin(), aLast = aRefAttrs.end();
1365   for (; anIt != aLast && anAllRefAttrInitialized; anIt++) {
1366     anAllRefAttrInitialized = (*anIt)->isInitialized();
1367   }
1368   if (anAllRefAttrInitialized) {
1369     // Activate dimension value editing on double click
1370     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
1371     QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
1372     // Find corresponded widget to activate value editing
1373     foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
1374       if (aWgt->attributeID() == "ConstraintValue") {
1375         // the featue should be displayed in order to find the AIS text position,
1376         // the place where the editor will be shown
1377         aFeature->setDisplayed(true);
1378         /// the execute is necessary to perform in the feature compute for flyout position
1379         aFeature->execute();
1380
1381         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1382         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1383
1384         PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
1385         if (anEditor) {
1386           int aX = 0, anY = 0;
1387
1388           XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(theWorkshop);
1389           XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1390           AISObjectPtr anAIS = aDisplayer->getAISObject(aFeature);
1391           Handle(AIS_InteractiveObject) anAISIO;
1392           if (anAIS.get() != NULL) {
1393             anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1394           }
1395           if (anAIS.get() != NULL) {
1396             Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1397
1398             if (!anAISIO.IsNull()) {
1399               Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAISIO);
1400               if (!aDim.IsNull()) {
1401                 gp_Pnt aPosition = aDim->GetTextPosition();
1402
1403                 ModuleBase_IViewer* aViewer = aWorkshop->viewer();
1404                 Handle(V3d_View) aView = aViewer->activeView();
1405                 int aCX, aCY;
1406                 aView->Convert(aPosition.X(), aPosition.Y(), aPosition.Z(), aCX, aCY);
1407
1408                 QWidget* aViewPort = aViewer->activeViewPort();
1409                 QPoint aGlPoint = aViewPort->mapToGlobal(QPoint(aCX, aCY));
1410                 aX = aGlPoint.x();
1411                 anY = aGlPoint.y();
1412               }
1413             }
1414             anEditor->setCursorPosition(aX, anY);
1415             isValueAccepted = anEditor->showPopupEditor(false);
1416             theCanCommitOperation = true;
1417           }
1418         }
1419       }
1420     }
1421   }
1422   return isValueAccepted;
1423 }
1424
1425 void PartSet_SketcherMgr::getCurrentSelection(const FeaturePtr& theFeature,
1426                                               const FeaturePtr& theSketch,
1427                                               ModuleBase_IWorkshop* theWorkshop,
1428                                               FeatureToSelectionMap& theSelection)
1429 {
1430   if (theFeature.get() == NULL)
1431     return;
1432
1433   std::set<AttributePtr> aSelectedAttributes;
1434   std::set<ResultPtr> aSelectedResults;
1435
1436   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1437   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
1438   if (!aContext.IsNull()) {
1439     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1440     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1441
1442     std::list<ResultPtr> aResults = theFeature->results();
1443     std::list<ResultPtr>::const_iterator aIt;
1444     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1445     {
1446       ResultPtr aResult = *aIt;
1447       AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1448       if (aAISObj.get() == NULL)
1449         continue;
1450       Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1451       for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
1452       {
1453         Handle(SelectMgr_EntityOwner) anOwner = aContext->SelectedOwner();
1454         if (anOwner->Selectable() != anAISIO)
1455           continue;
1456         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1457                                aSelectedAttributes, aSelectedResults);
1458       }
1459       for (aContext->InitDetected(); aContext->MoreDetected(); aContext->NextDetected()) {
1460         Handle(SelectMgr_EntityOwner) anOwner = aContext->DetectedOwner();
1461         if (anOwner.IsNull())
1462           continue;
1463         if (anOwner->Selectable() != anAISIO)
1464           continue;
1465         getAttributesOrResults(anOwner, theFeature, theSketch, aResult,
1466                                aSelectedAttributes, aSelectedResults);
1467       }
1468     }
1469   }
1470   theSelection[theFeature] = std::make_pair(aSelectedAttributes, aSelectedResults);
1471 }
1472
1473 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1474                                              const FeaturePtr& theSketch,
1475                                              ModuleBase_IWorkshop* theWorkshop,
1476                                              const FeatureToSelectionMap& theSelection,
1477                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1478 {
1479   if (theFeature.get() == NULL)
1480     return;
1481
1482   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1483   std::set<AttributePtr> aSelectedAttributes = anIt.value().first;
1484   std::set<ResultPtr> aSelectedResults = anIt.value().second;
1485
1486   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1487
1488   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1489   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1490
1491   // 1. found the feature's owners. Check the AIS objects of the constructions
1492   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1493   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1494     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1495
1496     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1497     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1498     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1499       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1500       if (!anOwner.IsNull())
1501         theOwnersToSelect.Add(anOwner);
1502     }
1503   }
1504
1505   // 2. found the feature results's owners
1506   std::list<ResultPtr> aResults = theFeature->results();
1507   std::list<ResultPtr>::const_iterator aIt;
1508   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1509   {
1510     ResultPtr aResult = *aIt;
1511     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1512     if (aAISObj.get() == NULL)
1513       continue; 
1514     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1515
1516     SelectMgr_IndexedMapOfOwner aSelectedOwners;  
1517     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1518     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1519       Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1520       if ( anOwner.IsNull() || !anOwner->HasShape() )
1521         continue;
1522       const TopoDS_Shape& aShape = anOwner->Shape();
1523       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1524       if (aShapeType == TopAbs_VERTEX) {
1525         AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1526         if (aPntAttr.get() != NULL &&
1527             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end()) {
1528           theOwnersToSelect.Add(anOwner);
1529         }
1530       }
1531       else if (aShapeType == TopAbs_EDGE) {
1532         bool aFound = aSelectedResults.find(aResult) != aSelectedResults.end();
1533         if (aSelectedResults.find(aResult) != aSelectedResults.end() &&
1534             theOwnersToSelect.FindIndex(anOwner) <= 0)
1535           theOwnersToSelect.Add(anOwner);
1536       }
1537     }
1538   }
1539 }
1540
1541 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget, const bool isToConnect)
1542 {
1543   if (isToConnect) {
1544     connect(theWidget, SIGNAL(beforeValuesChanged()),
1545             this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1546     connect(theWidget, SIGNAL(afterValuesChanged()),
1547             this, SLOT(onAfterValuesChangedInPropertyPanel()));
1548   }
1549   else {
1550     disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1551                 this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1552     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1553                 this, SLOT(onAfterValuesChangedInPropertyPanel()));
1554   }
1555 }
1556
1557 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1558 {
1559   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1560                                                                            (getCurrentOperation());
1561   if (aFOperation) {
1562     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1563         PartSet_SketcherMgr::isNestedSketchOperation(aFOperation) &&
1564         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1565       FeaturePtr aFeature = aFOperation->feature();
1566       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1567     }
1568   }
1569 }
1570
1571 void PartSet_SketcherMgr::customizePresentation(const ObjectPtr& theObject)
1572 {
1573   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1574                                                                            (getCurrentOperation());
1575   if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1576                       PartSet_SketcherMgr::isNestedSketchOperation(aFOperation)))
1577     SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
1578 }
1579
1580 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1581 {
1582   return myModule->workshop()->currentOperation();
1583 }
1584
1585 //**************************************************************
1586 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1587 {
1588   ModuleBase_ModelWidget* aWidget = 0;
1589   ModuleBase_Operation* anOperation = getCurrentOperation();
1590   if (anOperation) {
1591     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1592     if (aPanel)
1593       aWidget = aPanel->activeWidget();
1594   }
1595   return aWidget;
1596 }
1597
1598 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1599                                            const bool isEditOperation,
1600                                            const bool isToDisplay,
1601                                            const bool isFlushRedisplay)
1602 {
1603   #ifdef DEBUG_DO_NOT_BY_ENTER
1604   return;
1605   #endif
1606
1607   if (isEditOperation || !theFeature.get())
1608     return;
1609
1610   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1611   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1612
1613   // 1. change visibility of the object itself, here the presentable object is processed,
1614   // e.g. constraints features
1615   //FeaturePtr aFeature = aFOperation->feature();
1616   std::list<ResultPtr> aResults = theFeature->results();
1617   if (isToDisplay)
1618     theFeature->setDisplayed(true);
1619   else
1620     theFeature->setDisplayed(false);
1621
1622   // change visibility of the object results, e.g. non-constraint features
1623   std::list<ResultPtr>::const_iterator aIt;
1624   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1625     if (isToDisplay) {
1626       (*aIt)->setDisplayed(true);
1627     }
1628     else {
1629       (*aIt)->setDisplayed(false);
1630     }
1631   }
1632   if (isFlushRedisplay)
1633     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1634 }
1635
1636 void PartSet_SketcherMgr::storeSelection(const bool theHighlightedOnly)
1637 {
1638   if (!myCurrentSketch.get())
1639     return;
1640
1641   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1642   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1643   QList<ModuleBase_ViewerPrsPtr> aHighlighted = aSelect->getHighlighted();
1644
1645   QList<FeaturePtr> aFeatureList;
1646   if (theHighlightedOnly) {
1647     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1648   }
1649   else {
1650     fillFeatureList(aHighlighted, myCurrentSketch, aFeatureList);
1651
1652     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(ModuleBase_ISelection::AllControls);
1653     fillFeatureList(aSelected, myCurrentSketch, aFeatureList);
1654   }
1655
1656   // 1. it is necessary to save current selection in order to restore it after the features moving
1657   myCurrentSelection.clear();
1658   QList<FeaturePtr>::const_iterator anIt = aFeatureList.begin(), aLast = aFeatureList.end();
1659   for (; anIt != aLast; anIt++) {
1660     getCurrentSelection(*anIt, myCurrentSketch, aWorkshop, myCurrentSelection);
1661   }
1662   //qDebug(QString("  storeSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1663 }
1664
1665 void PartSet_SketcherMgr::restoreSelection()
1666 {
1667   if (!myCurrentSketch.get())
1668     return;
1669
1670   //qDebug(QString("restoreSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1671   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1672   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1673   FeatureToSelectionMap::const_iterator aSIt = myCurrentSelection.begin(),
1674                                         aSLast = myCurrentSelection.end();
1675   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1676   for (; aSIt != aSLast; aSIt++) {
1677     anOwnersToSelect.Clear();
1678     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, myCurrentSelection,
1679                         anOwnersToSelect);
1680     aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1681   }
1682 }
1683
1684 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
1685 {
1686   PartSet_Tools::ConstraintVisibleState aType = (PartSet_Tools::ConstraintVisibleState)theType;
1687
1688   updateBySketchParameters(aType, theState);
1689 }
1690
1691 void PartSet_SketcherMgr::updateBySketchParameters(
1692                                    const PartSet_Tools::ConstraintVisibleState& theType,
1693                                    bool theState)
1694 {
1695   if (myCurrentSketch.get() == NULL)
1696     return;
1697
1698   bool aPrevState = myIsConstraintsShown[theType];
1699   myIsConstraintsShown[theType] = theState;
1700
1701   switch (theType) {
1702     case PartSet_Tools::Geometrical:
1703     case PartSet_Tools::Dimensional: {
1704       if (aPrevState != theState) {
1705         ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1706         XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1707         for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1708           FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1709           bool aProcessed = false;
1710           bool aConstraintDisplayed = canDisplayConstraint(aSubFeature, theType, aProcessed);
1711           if (aProcessed)
1712             aSubFeature->setDisplayed(aConstraintDisplayed);
1713         }
1714         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1715       }
1716     }
1717     break;
1718     case PartSet_Tools::Expressions: {
1719       if (aPrevState != theState) {
1720         /// call all sketch features redisplay, the expression state will be corrected in customize
1721         /// of distance presentation
1722         Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1723         PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
1724       }
1725     }
1726     break;
1727   }
1728 }
1729
1730 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
1731 {
1732   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1733   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1734   return aConnector->workshop();
1735 }
1736
1737 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1738 {
1739   return workshop()->operationMgr();
1740 }
1741