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