]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_SketcherMgr.cpp
Salome HOME
Get rid of compilation warnings. Part I.
[modules/shaper.git] / src / PartSet / PartSet_SketcherMgr.cpp
1 // Copyright (C) 2014-2020  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 email : webmaster.salome@opencascade.com
18 //
19
20 #include "PartSet_SketcherMgr.h"
21
22 #include "PartSet_Filters.h"
23 #include "PartSet_SketcherReentrantMgr.h"
24 #include "PartSet_Module.h"
25 #include "PartSet_MouseProcessor.h"
26 #include "PartSet_Tools.h"
27 #include "PartSet_WidgetSketchLabel.h"
28 #include "PartSet_WidgetEditor.h"
29 #include "PartSet_ResultSketchPrs.h"
30 #include "PartSet_ExternalPointsMgr.h"
31 #include "PartSet_PreviewSketchPlane.h"
32
33 #include <XGUI_ModuleConnector.h>
34 #include <XGUI_Displayer.h>
35 #include <XGUI_Workshop.h>
36 #include <XGUI_ContextMenuMgr.h>
37 #include <XGUI_Selection.h>
38 #include <XGUI_SelectionActivate.h>
39 #include <XGUI_SelectionMgr.h>
40 #include <XGUI_ModuleConnector.h>
41 #include <XGUI_PropertyPanel.h>
42 #include <XGUI_ViewerProxy.h>
43 #include <XGUI_OperationMgr.h>
44 #include <XGUI_ErrorMgr.h>
45 #include <XGUI_Tools.h>
46
47 #include <ModuleBase_IPropertyPanel.h>
48 #include <ModuleBase_ISelection.h>
49 #include <ModuleBase_IViewer.h>
50 #include <ModuleBase_IWorkshop.h>
51 #include <ModuleBase_IViewWindow.h>
52 #include <ModuleBase_ModelWidget.h>
53 #include <ModuleBase_Operation.h>
54 #include <ModuleBase_OperationFeature.h>
55 #include <ModuleBase_Operation.h>
56 #include <ModuleBase_WidgetEditor.h>
57 #include <ModuleBase_ViewerPrs.h>
58 #include <ModuleBase_Tools.h>
59 #include <ModuleBase_ResultPrs.h>
60 #include <ModuleBase_ViewerFilters.h>
61
62 #include <GeomDataAPI_Point2D.h>
63 #include <GeomDataAPI_Point2DArray.h>
64
65 #include <GeomAPI_Shape.h>
66
67 #include <Events_Loop.h>
68
69 #include <SketchPlugin_Line.h>
70 #include <SketchPlugin_Sketch.h>
71 #include <SketchPlugin_Point.h>
72 #include <SketchPlugin_Arc.h>
73 #include <SketchPlugin_Circle.h>
74 #include <SketchPlugin_Ellipse.h>
75 #include <SketchPlugin_EllipticArc.h>
76 #include <SketchPlugin_ConstraintLength.h>
77 #include <SketchPlugin_ConstraintDistance.h>
78 #include <SketchPlugin_ConstraintParallel.h>
79 #include <SketchPlugin_ConstraintPerpendicular.h>
80 #include <SketchPlugin_ConstraintRadius.h>
81 #include <SketchPlugin_ConstraintRigid.h>
82 #include <SketchPlugin_ConstraintHorizontal.h>
83 #include <SketchPlugin_ConstraintVertical.h>
84 #include <SketchPlugin_ConstraintEqual.h>
85 #include <SketchPlugin_ConstraintTangent.h>
86 #include <SketchPlugin_ConstraintCoincidence.h>
87 #include <SketchPlugin_Fillet.h>
88 #include <SketchPlugin_ConstraintMirror.h>
89 #include <SketchPlugin_ConstraintAngle.h>
90 #include <SketchPlugin_ConstraintCollinear.h>
91 #include <SketchPlugin_ConstraintMiddle.h>
92 #include <SketchPlugin_MultiRotation.h>
93 #include <SketchPlugin_MultiTranslation.h>
94 #include <SketchPlugin_IntersectionPoint.h>
95 #include <SketchPlugin_Projection.h>
96 #include <SketchPlugin_ConstraintDistanceAlongDir.h>
97 #include <SketchPlugin_ConstraintDistanceHorizontal.h>
98 #include <SketchPlugin_ConstraintDistanceVertical.h>
99
100 #include <SketcherPrs_Tools.h>
101
102 #include <SelectMgr_IndexedMapOfOwner.hxx>
103 #include <StdSelect_BRepOwner.hxx>
104
105 //#include <AIS_DimensionSelectionMode.hxx>
106 #include <AIS_Shape.hxx>
107 #include <AIS_Dimension.hxx>
108
109 #include <ModelAPI_Events.h>
110 #include <ModelAPI_Session.h>
111 #include <ModelAPI_AttributeString.h>
112
113 #include <ModelAPI_Validator.h>
114 #include <ModelAPI_Tools.h>
115
116 #include <QMouseEvent>
117 #include <QApplication>
118 #include <QCursor>
119 #include <QMessageBox>
120 #include <QMainWindow>
121
122 #include <set>
123
124 //#define DEBUG_DO_NOT_BY_ENTER
125 //#define DEBUG_SKETCHER_ENTITIES
126 //#define DEBUG_SKETCH_ENTITIES_ON_MOVE
127 //#define DRAGGING_DEBUG
128 //#define DEBUG_CURSOR
129
130
131 #ifdef DRAGGING_DEBUG
132 #include <QTime>
133 #endif
134
135 /// Fills attribute and result lists by the selected owner. In case if the attribute is found,
136 /// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge,
137 /// put the function result as is to the list of results.
138 /// \param theOwner a viewer selected owner
139 /// \param theFeature a feature, where the attribute is searched
140 /// \param theSketch a current sketch
141 /// \param theSelectedAttribute an output list of attributes
142 /// \param theSelectedResults an output list of edge results
143 void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
144                             const FeaturePtr& theFeature, const FeaturePtr& theSketch,
145                             const ResultPtr& theResult,
146                             std::map<AttributePtr, int>& theSelectedAttributes,
147                             std::set<ResultPtr>& theSelectedResults,
148                             TopTools_MapOfShape& theShapes)
149 {
150   Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(theOwner);
151   if (aBRepOwner.IsNull())
152     return;
153   Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(
154                                                                     aBRepOwner->Selectable());
155   if (aBRepOwner->HasShape()) {
156     const TopoDS_Shape& aShape = aBRepOwner->Shape();
157     theShapes.Add(aShape);
158     TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
159     if (aShapeType == TopAbs_VERTEX) {
160       std::pair<AttributePtr, int> aPntAttrIndex =
161           PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
162       if (aPntAttrIndex.first.get() != NULL)
163         theSelectedAttributes[aPntAttrIndex.first] = aPntAttrIndex.second;
164     }
165     else if (aShapeType == TopAbs_EDGE &&
166              theSelectedResults.find(theResult) == theSelectedResults.end()) {
167       theSelectedResults.insert(theResult);
168     }
169   }
170 }
171
172 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
173   : QObject(theModule),
174     myModule(theModule),
175     myIsEditLaunching(false),
176     myIsDragging(false),
177     myDragDone(false),
178     myIsMouseOverWindow(false),
179     myIsMouseOverViewProcessed(true),
180     myIsPopupMenuActive(false),
181     myPreviousUpdateViewerEnabled(true),
182     myExternalPointsMgr(0),
183     myNoDragMoving(false)
184 {
185   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
186   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
187
188   myPreviousDrawModeEnabled = true;//aViewer->isSelectionEnabled();
189
190   connect(aViewer, SIGNAL(mousePress(ModuleBase_IViewWindow*, QMouseEvent*)),
191           this, SLOT(onMousePressed(ModuleBase_IViewWindow*, QMouseEvent*)));
192
193   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)),
194           this, SLOT(onMouseReleased(ModuleBase_IViewWindow*, QMouseEvent*)));
195
196   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
197           this, SLOT(onMouseMoved(ModuleBase_IViewWindow*, QMouseEvent*)));
198
199   connect(aViewer, SIGNAL(mouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)),
200           this, SLOT(onMouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)));
201
202   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
203   XGUI_Workshop* aWorkshop = aConnector->workshop();
204   connect(aWorkshop, SIGNAL(applicationStarted()), this, SLOT(onApplicationStarted()));
205
206   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
207   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
208   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
209
210   mySketchPlane = new PartSet_PreviewSketchPlane();
211
212   registerSelectionFilter(SF_SketchCirclePointFilter, new PartSet_CirclePointFilter(anIWorkshop));
213   registerSelectionFilter(SF_SketchPlaneFilter, new ModuleBase_ShapeInPlaneFilter());
214
215   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_DOF_OBJECTS));
216 }
217
218 PartSet_SketcherMgr::~PartSet_SketcherMgr()
219 {
220   delete mySketchPlane;
221 }
222
223 void PartSet_SketcherMgr::onEnterViewPort()
224 {
225   // 1. if the mouse over window, update the next flag. Do not perform update visibility of
226   // created feature because it should be done in onMouseMove(). Some widgets watch
227   // the mouse move and use the cursor position to update own values. If the presentaion is
228   // redisplayed before this update, the feature presentation jumps from reset value to current.
229   myIsMouseOverWindow = true;
230
231   #ifdef DEBUG_DO_NOT_BY_ENTER
232   return;
233   #endif
234
235   // It is switched off because of
236   // Task #3067: 5.2.2 Drawing in the sketcher: change the mouse cursor arrow
237     if (canChangeCursor(getCurrentOperation())) {
238       QCursor* aCurrentCursor = QApplication::overrideCursor();
239       if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
240         QApplication::setOverrideCursor(PartSet_Tools::getOperationCursor());
241   //#ifdef DEBUG_CURSOR
242   //      qDebug("onEnterViewPort() : Qt::CrossCursor");
243   //#endif
244       }
245     }
246
247   if (!isNestedCreateOperation(getCurrentOperation(), activeSketch()))
248     return;
249
250   operationMgr()->onValidateOperation();
251
252   // we need change displayed state of the current operation feature
253   // if the feature is presentable, e.g. distance construction. It has no results, so workshop does
254   // not accept a signal about the result created. Nothing is shown until mouse is moved out/in view
255   // port. If the isDisplayed flag is true, the presentable feature is displayed as soon as the
256   // presentation becomes valid and redisplay happens
257   //ModuleBase_Operation* aOperation = getCurrentOperation();
258   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
259                                                                            (getCurrentOperation());
260   if (aFOperation) {
261     FeaturePtr aFeature = aFOperation->feature();
262     if (aFeature.get() && aFeature->data()->isValid()) {
263       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature), false);
264     }
265   }
266 }
267
268 void PartSet_SketcherMgr::onLeaveViewPort()
269 {
270   myIsMouseOverViewProcessed = false;
271   myIsMouseOverWindow = false;
272
273   #ifdef DEBUG_DO_NOT_BY_ENTER
274   return;
275   #endif
276
277   if (canChangeCursor(getCurrentOperation())) {
278     QApplication::restoreOverrideCursor();
279 //#ifdef DEBUG_CURSOR
280 //    qDebug("onLeaveViewPort() : None");
281 //#endif
282   }
283
284   if (!isNestedCreateOperation(getCurrentOperation(), activeSketch()))
285     return;
286
287   // the method should be performed if the popup menu is called,
288   // the reset of the current widget should not happen
289   if (myIsPopupMenuActive)
290     return;
291
292   // it is important to validate operation here only if sketch entity create operation is active
293   // because at this operation we reacts to the mouse leave/enter view port
294   operationMgr()->onValidateOperation();
295
296   // 2. if the mouse IS NOT over window, reset the active widget value and hide the presentation
297   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
298   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
299   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
300   // disable the viewer update in order to avoid visualization of redisplayed feature in viewer
301   // obtained after reset value
302   bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
303   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
304   if (anActiveWidget)
305     anActiveWidget->reset();
306
307   // hides the presentation of the current operation feature
308   // the feature is to be erased here, but it is correct to call canDisplayObject because
309   // there can be additional check (e.g. editor widget in distance constraint)
310   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
311                                                                            (getCurrentOperation());
312   if (aFOperation) {
313     FeaturePtr aFeature = aFOperation->feature();
314     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
315   }
316   // we should update viewer after the presentation are hidden in the viewer
317   // otherwise the reset presentation(line) appears in the viewer(by quick move from viewer to PP)
318   aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
319 }
320
321 /*
322 //Temporary commented as we do not modify values in property panel
323 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
324 {
325   if (!isNestedEditOperation(getCurrentOperation(), myModule->sketchMgr()->activeSketch()) ||
326       myModule->sketchReentranceMgr()->isInternalEditActive())
327     return;
328   // it is necessary to save current selection in order to restore it after the values are modifed
329   storeSelection(ST_SelectAndHighlightType);
330
331   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
332   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
333   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
334   myPreviousUpdateViewerEnabled = aDisplayer->enableUpdateViewer(false);
335 }
336
337 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
338 {
339   if (!isNestedEditOperation(getCurrentOperation(), myModule->sketchMgr()->activeSketch()) ||
340       myModule->sketchReentranceMgr()->isInternalEditActive()) {
341     myModule->sketchReentranceMgr()->updateInternalEditActiveState();
342     return;
343   }
344   // it is necessary to restore current selection in order to restore it after values are modified
345   restoreSelection();
346   myCurrentSelection.clear();
347
348   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the
349   // viewer happens by deselect/select the modified objects. The flag should be restored after
350   // the selection processing. The update viewer should be also called.
351   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
352   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
353   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
354   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
355   aDisplayer->updateViewer();
356 }
357 */
358
359 bool PartSet_SketcherMgr::isDragModeCreation() const
360 {
361   ModuleBase_Operation* aOp = getCurrentOperation();
362   if (!aOp)
363     return false;
364   bool aUserPref = Config_PropManager::boolean(SKETCH_TAB_NAME, "create_by_dragging");
365   if (!aUserPref)
366     return false;
367   QString aId = aOp->id();
368   // Acceptable features;
369   QStringList aList;
370   aList << "SketchLine" << "SketchMacroCircle" << "SketchMacroArc" <<
371     "SketchMacroEllipse" << "SketchMacroEllipticArc" << "SketchRectangle";
372   return aList.contains(aId);
373 }
374
375 static bool MyModeByDrag = false;
376 static bool MyMultiselectionState = true;
377
378 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
379 {
380   MyModeByDrag = isDragModeCreation();
381
382   // Clear dragging mode
383   myIsDragging = false;
384
385   myMousePoint.setX(theEvent->x());
386   myMousePoint.setY(theEvent->y());
387
388   if (myModule->sketchReentranceMgr()->processMousePressed(theWnd, theEvent))
389     return;
390   //get2dPoint(theWnd, theEvent, myClickedPoint);
391   if (!(theEvent->buttons() & Qt::LeftButton))
392     return;
393
394   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
395   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
396   //if (!aViewer->canDragByMouse())
397   //  return;
398
399   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
400                                                                (getCurrentOperation());
401   if (!aFOperation)
402     return;
403
404   bool isEditing = aFOperation->isEditOperation();
405   bool aCanDrag = aViewer->canDragByMouse();
406
407   //if (!aViewer->canDragByMouse() && isEditing) {
408   //  // Do not edit by dragging
409   //  return;
410   //}
411
412   if (isEditing) {
413     // If the current widget is a selector, do nothing, it processes the mouse press
414     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
415     if(anActiveWidget && anActiveWidget->isViewerSelector()) {
416       return;
417     }
418   }
419
420   // Use only for sketch operations
421   if (myCurrentSketch) {
422     if (!PartSet_Tools::sketchPlane(myCurrentSketch))
423       return;
424
425     bool isSketcher = isSketchOperation(aFOperation);
426     bool isSketchOpe = isNestedSketchOperation(aFOperation);
427
428     // Avoid non-sketch operations
429     if ((!isSketchOpe) && (!isSketcher))
430       return;
431
432     // Ignore creation sketch operation
433     if ((!isSketcher) && (!isEditing)) {
434       if (MyModeByDrag) {
435         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
436         PartSet_MouseProcessor* aProcessor = dynamic_cast<PartSet_MouseProcessor*>(anActiveWidget);
437         if (aProcessor) {
438           MyMultiselectionState = aViewer->isMultiSelectionEnabled();
439           aViewer->enableMultiselection(false);
440           myIsDragging = true;
441           ModuleBase_ISelection* aSelection = aWorkshop->selection();
442           QList<ModuleBase_ViewerPrsPtr> aPreSelected = aSelection->getHighlighted();
443           if (!aPreSelected.empty())
444             aProcessor->setPreSelection(aPreSelected.first(), theWnd, theEvent);
445           else
446             aProcessor->mouseReleased(theWnd, theEvent);
447         }
448       }
449       return;
450     }
451     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
452     storeSelection(aHasShift ? ST_SelectAndHighlightType : ST_HighlightType, myCurrentSelection);
453
454     if (myCurrentSelection.empty()) {
455       if (isSketchOpe && (!isSketcher))
456         // commit previous operation
457         if (!aFOperation->commit())
458           aFOperation->abort();
459       return;
460     }
461     // Init flyout point for radius rotation
462     FeaturePtr aFeature = myCurrentSelection.begin().key();
463     get2dPoint(theWnd, theEvent, myCurrentPoint);
464     if (isSketcher) {
465       if (aCanDrag) {
466         myIsDragging = true;
467         myDragDone = false;
468       }
469       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
470       launchEditing();
471       if (aFeature.get() != NULL) {
472         std::shared_ptr<SketchPlugin_Feature> aSPFeature =
473                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
474         if (aSPFeature.get() &&
475           (aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID() ||
476            aSPFeature->getKind() == SketchPlugin_ConstraintAngle::ID())) {
477           DataPtr aData = aSPFeature->data();
478           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
479           std::shared_ptr<GeomDataAPI_Point2D> aFPAttr =
480             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
481           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
482         }
483       }
484     } else if (isSketchOpe && isEditing) {
485       // If selected another object commit current result
486       bool aPrevLaunchingState = myIsEditLaunching;
487       /// store editing state for Edit operation in order to do not clear highlight by restart
488       /// of edit operation.
489       /// Internal edit should not be stored as editing operation as the result will be a
490       /// creation operation, where previous selection should not be used(and will be cleared)
491       myIsEditLaunching = !myModule->sketchReentranceMgr()->isInternalEditActive();
492
493       std::shared_ptr<SketchPlugin_Feature> aSPFeature =
494         std::dynamic_pointer_cast<SketchPlugin_Feature>(aFOperation->feature());
495       bool isRelaunchEditing = true;
496       if (aSPFeature->isExternal()) {
497         foreach(FeaturePtr aF, myCurrentSelection.keys()) {
498           FeaturePtr aProducerFeature = PartSet_Tools::findRefsToMeFeature(aF,
499             aSPFeature->getKind());
500           if (aProducerFeature == aSPFeature) {
501             isRelaunchEditing = false;
502             break;
503           }
504         }
505       }
506       else {
507         if (myCurrentSelection.size() > 1)
508           isRelaunchEditing = !myCurrentSelection.contains(aSPFeature);
509       }
510       if (isRelaunchEditing)
511         aFOperation->commit();
512
513       if (aCanDrag) {
514         myIsDragging = true;
515         myDragDone = false;
516       }
517       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
518       if (isRelaunchEditing)
519         launchEditing();
520       myIsEditLaunching = aPrevLaunchingState;
521       if (aFeature.get() != NULL) {
522         std::shared_ptr<SketchPlugin_Feature> aSPFeature =
523                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
524         if (aSPFeature.get() &&
525           (aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID() ||
526            aSPFeature->getKind() == SketchPlugin_ConstraintAngle::ID())) {
527           DataPtr aData = aSPFeature->data();
528           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
529           std::shared_ptr<GeomDataAPI_Point2D> aFPAttr =
530             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
531           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
532         }
533       }
534     }
535   }
536 }
537
538 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
539 {
540   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
541   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
542   if (myIsDragging)
543     aViewer->enableDrawMode(myPreviousDrawModeEnabled);
544
545   bool aWasDragging = myIsDragging;
546   myIsDragging = false;
547
548   if (myModule->sketchReentranceMgr()->processMouseReleased(theWnd, theEvent)) {
549     return;
550   }
551   // if mouse is pressed when it was over view and at release the mouse is out of view, do nothing
552   if (!myIsMouseOverViewProcessed) {
553     return;
554   }
555
556   ModuleBase_OperationFeature* aOp =
557     dynamic_cast<ModuleBase_OperationFeature*>(getCurrentOperation());
558   bool isEditing = false;
559   if (aOp) {
560     isEditing = aOp->isEditOperation();
561     bool aStartNoDragOperation = !aViewer->canDragByMouse() && isEditing;
562     if (aStartNoDragOperation || myNoDragMoving) {
563       // Process edit operation without dragging
564       if (myCurrentSelection.size() > 0)
565         myNoDragMoving = !myNoDragMoving;
566       else
567         myNoDragMoving = false;
568       if (myNoDragMoving)
569         return;
570       else {
571         restoreSelection(myCurrentSelection);
572         myCurrentSelection.clear();
573       }
574     }
575     else {
576       if (isNestedSketchOperation(aOp)) {
577         // Only for sketcher operations
578         if (aWasDragging) {
579           if (myDragDone) {
580             /// the previous selection is lost by mouse release in the viewer(Select method), but
581             /// it is still stored in myCurrentSelection. So, it is possible to restore selection
582             /// It is important for drag(edit with mouse) of sketch entities.
583             restoreSelection(myCurrentSelection);
584             myCurrentSelection.clear();
585           }
586         }
587       }
588     }
589   }
590
591   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
592   PartSet_MouseProcessor* aProcessor = dynamic_cast<PartSet_MouseProcessor*>(anActiveWidget);
593   if (aProcessor) {
594     ModuleBase_ISelection* aSelection = aWorkshop->selection();
595     QList<ModuleBase_ViewerPrsPtr> aPreSelected = aSelection->getHighlighted();
596     if (MyModeByDrag && !aPreSelected.empty() && !isEditing)
597       aProcessor->setPreSelection(aPreSelected.first(), theWnd, theEvent);
598     else
599       aProcessor->mouseReleased(theWnd, theEvent);
600   }
601   if (MyModeByDrag && aOp) {
602     aViewer->enableMultiselection(true);
603     QString aOpId = aOp->id();
604     if (aOpId == "Sketch")
605       return;
606     QPoint aPnt(theEvent->x(), theEvent->y());
607     anActiveWidget = getActiveWidget();
608     if ((aPnt == myMousePoint) && anActiveWidget) {
609       aOp->abort();
610       return;
611     }
612     bool aCanRestart = !anActiveWidget && !isEditing;
613     if (aCanRestart) {
614       module()->launchOperation(aOpId, true);
615     }
616   }
617 }
618
619 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
620 {
621 #ifdef DEBUG_SKETCH_ENTITIES_ON_MOVE
622   CompositeFeaturePtr aSketch = activeSketch();
623   if (aSketch.get()) {
624     std::cout << "mouse move SKETCH FEATURES [" << aSketch->numberOfSubs() << "]:" << std::endl;
625     QStringList anInfo;
626     for (int i = 0, aNbSubs = aSketch->numberOfSubs(); i < aNbSubs; i++) {
627       //std::cout << getFeatureInfo(aSketch->subFeature(i), false) << std::endl;
628       anInfo.append(ModuleBase_Tools::objectInfo(aSketch->subFeature(i)));
629     }
630     QString anInfoStr = anInfo.join("\n");
631     qDebug(QString("%1").arg(anInfo.size()).arg(anInfoStr).toStdString().c_str());
632   }
633 #endif
634
635   if (myModule->sketchReentranceMgr()->processMouseMoved(theWnd, theEvent))
636     return;
637
638   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
639   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
640   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
641
642   if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
643 #ifdef DRAGGING_DEBUG
644     QTime t;
645     t.start();
646 #endif
647     // 1. perform the widget mouse move functionality and display the presentation
648     // the mouse move should be processed in the widget, if it can in order to visualize correct
649     // presentation. These widgets correct the feature attribute according to the mouse position
650     ModuleBase_ModelWidget* anActiveWidget = myModule->activeWidget();
651     PartSet_MouseProcessor* aProcessor = dynamic_cast<PartSet_MouseProcessor*>(anActiveWidget);
652     if (aProcessor)
653       aProcessor->mouseMoved(theWnd, theEvent);
654     if (!myIsMouseOverViewProcessed) {
655       myIsMouseOverViewProcessed = true;
656
657       // the feature is to be erased here, but it is correct to call canDisplayObject because
658       // there can be additional check (e.g. editor widget in distance constraint)
659       ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
660         (getCurrentOperation());
661       if (aFOperation) {
662         FeaturePtr aFeature = aFOperation->feature();
663         visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
664       }
665     }
666     aDisplayer->updateViewer();
667 #ifdef DRAGGING_DEBUG
668     cout << "Mouse move processing " << t.elapsed() << endl;
669 #endif
670   }
671   //myClickedPoint.clear();
672
673   if (myIsDragging || myNoDragMoving) {
674     // 1. the current selection is saved in the mouse press method in order to restore it after
675     //    moving
676     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
677     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
678     // deselected). This flag should be restored in the slot, processed the mouse release signal.
679     ModuleBase_Operation* aCurrentOperation = getCurrentOperation();
680     if (!aCurrentOperation)
681       return;
682     if (isSketchOperation(aCurrentOperation))
683       return; // No edit operation activated
684
685 #ifdef DRAGGING_DEBUG
686     QTime t;
687     t.start();
688 #endif
689
690     Handle(V3d_View) aView = theWnd->v3dView();
691     Point aMousePnt;
692     get2dPoint(theWnd, theEvent, aMousePnt);
693
694     std::shared_ptr<GeomAPI_Pnt2d> anOriginalPosition = std::shared_ptr<GeomAPI_Pnt2d>(
695       new GeomAPI_Pnt2d(myCurrentPoint.myCurX, myCurrentPoint.myCurY));
696     std::shared_ptr<GeomAPI_Pnt2d> aCurrentPosition = std::shared_ptr<GeomAPI_Pnt2d>(
697       new GeomAPI_Pnt2d(aMousePnt.myCurX, aMousePnt.myCurY));
698
699     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the
700     // viewer happens by deselect/select the modified objects. The flag should be restored after
701     // the selection processing. The update viewer should be also called.
702     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
703
704     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
705     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
706     FeatureToSelectionMap::const_iterator anIt = myCurrentSelection.begin(),
707       aLast = myCurrentSelection.end();
708     // 4. the features and attributes modification(move)
709     bool isModified = false;
710     for (; anIt != aLast; anIt++) {
711       FeaturePtr aFeature = anIt.key();
712
713       std::map<AttributePtr, int> anAttributes = anIt.value().myAttributes;
714       // Process selection by attribute: the priority to the attribute
715       if (!anAttributes.empty()) {
716         std::map<AttributePtr, int>::const_iterator anAttIt = anAttributes.begin(),
717           anAttLast = anAttributes.end();
718         for (; anAttIt != anAttLast; anAttIt++) {
719           AttributePtr anAttr = anAttIt->first;
720           if (anAttr.get() == NULL)
721             continue;
722           std::string aAttrId = anAttr->id();
723           DataPtr aData = aFeature->data();
724           if (aData->isValid()) {
725             AttributePtr aPoint = aData->attribute(aAttrId);
726             if (aPoint->attributeType() == GeomDataAPI_Point2D::typeId() ||
727                 aPoint->attributeType() == GeomDataAPI_Point2DArray::typeId()) {
728               bool isImmutable = aPoint->setImmutable(true);
729
730               std::shared_ptr<ModelAPI_ObjectMovedMessage> aMessage = std::shared_ptr
731                 <ModelAPI_ObjectMovedMessage>(new ModelAPI_ObjectMovedMessage(this));
732               aMessage->setMovedAttribute(aPoint, anAttIt->second);
733               aMessage->setOriginalPosition(anOriginalPosition);
734               aMessage->setCurrentPosition(aCurrentPosition);
735               Events_Loop::loop()->send(aMessage);
736
737               isModified = true;
738               aPoint->setImmutable(isImmutable);
739             }
740           }
741         }
742       }
743       else {
744         // Process selection by feature
745         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
746           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
747         if (aSketchFeature) {
748           std::shared_ptr<ModelAPI_ObjectMovedMessage> aMessage = std::shared_ptr
749             <ModelAPI_ObjectMovedMessage>(new ModelAPI_ObjectMovedMessage(this));
750           aMessage->setMovedObject(aFeature);
751           aMessage->setOriginalPosition(anOriginalPosition);
752           aMessage->setCurrentPosition(aCurrentPosition);
753           Events_Loop::loop()->send(aMessage);
754           isModified = true;
755         }
756       }
757     }
758     // the modified state of the current operation should be updated if there are features, which
759     // were changed here
760     if (isModified) {
761       aCurrentOperation->onValuesChanged();
762       Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
763     }
764     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
765
766     // 5. it is necessary to save current selection in order to restore it after the features moving
767     restoreSelection(myCurrentSelection);
768     // 6. restore the update viewer flag and call this update
769     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
770     aDisplayer->updateViewer();
771
772 #ifdef DRAGGING_DEBUG
773     cout << "Mouse move processing " << t.elapsed() << endl;
774 #endif
775
776     myDragDone = true;
777     myCurrentPoint = aMousePnt;
778   }
779 }
780
781 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
782 {
783   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
784                                                                (getCurrentOperation());
785   if (aFOperation && aFOperation->isEditOperation()) {
786     std::string aId = aFOperation->id().toStdString();
787     if (isDistanceOperation(aFOperation))
788     {
789       // Activate dimension value editing on double click
790       ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
791       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
792       // Find corresponded widget to activate value editing
793       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
794         std::string anId = aWgt->attributeID();
795         if (anId == SketchPlugin_Constraint::VALUE() ||
796           anId == SketchPlugin_ConstraintAngle::ANGLE_VALUE_ID() ||
797           anId == SketchPlugin_ConstraintDistanceAlongDir::DISTANCE_VALUE_ID()) {
798           PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
799           if (anEditor)
800             anEditor->showPopupEditor();
801           return;
802         }
803       }
804     }
805   }
806 }
807
808 void PartSet_SketcherMgr::onApplicationStarted()
809 {
810   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
811   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
812   XGUI_Workshop* aWorkshop = aConnector->workshop();
813   PartSet_SketcherReentrantMgr* aReentranceMgr = myModule->sketchReentranceMgr();
814
815   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
816   if (aPropertyPanel) {
817     //connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
818     //        this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
819
820     connect(aPropertyPanel, SIGNAL(noMoreWidgets(const std::string&)),
821             aReentranceMgr, SLOT(onNoMoreWidgets(const std::string&)));
822     //connect(aPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
823     //        aReentranceMgr, SLOT(onWidgetActivated()));
824   }
825
826   XGUI_ViewerProxy* aViewerProxy = aWorkshop->viewer();
827   connect(aViewerProxy, SIGNAL(enterViewPort()), this, SLOT(onEnterViewPort()));
828   connect(aViewerProxy, SIGNAL(leaveViewPort()), this, SLOT(onLeaveViewPort()));
829
830   XGUI_ContextMenuMgr* aContextMenuMgr = aWorkshop->contextMenuMgr();
831   connect(aContextMenuMgr, SIGNAL(beforeContextMenu()), this, SLOT(onBeforeContextMenu()));
832   connect(aContextMenuMgr, SIGNAL(afterContextMenu()), this, SLOT(onAfterContextMenu()));
833 }
834
835 //void PartSet_SketcherMgr::onBeforeWidgetActivated(ModuleBase_ModelWidget* theWidget)
836 //{
837   //if (!myClickedPoint.myIsInitialized)
838   //  return;
839
840   //ModuleBase_Operation* aOperation = getCurrentOperation();
841   // the distance constraint feature should not use the clickedd point
842   // this is workaround in order to don't throw down the flyout point value,
843   // set by execute() method of these type of features
844   //if (isDistanceOperation(aOperation))
845   //  return;
846
847   //PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(theWidget);
848   //if (aPnt2dWgt) {
849   //  aPnt2dWgt->setPoint(myClickedPoint.myCurX, myClickedPoint.myCurY);
850   //}
851 //}
852
853 void PartSet_SketcherMgr::onBeforeContextMenu()
854 {
855   myIsPopupMenuActive = true;
856 }
857
858 void PartSet_SketcherMgr::onAfterContextMenu()
859 {
860   myIsPopupMenuActive = false;
861 }
862
863 void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent,
864                                      Point& thePoint)
865 {
866   Handle(V3d_View) aView = theWnd->v3dView();
867   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
868   double aX, anY;
869   PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, anY);
870   thePoint.setValue(aX, anY);
871 }
872
873 void PartSet_SketcherMgr::launchEditing()
874 {
875   if (!myCurrentSelection.empty()) {
876     FeaturePtr aFeature = myCurrentSelection.begin().key();
877     std::shared_ptr<SketchPlugin_Feature> aSPFeature =
878               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
879     if (aSPFeature) {
880       if (!aSPFeature->isExternal())
881         myModule->editFeature(aSPFeature);
882       else {
883         // need to edit a feature (Projection/IntersectionPoint),
884         // which produces current External feature
885         FeaturePtr aProducerFeature = PartSet_Tools::findRefsToMeFeature(aFeature,
886                                                         SketchPlugin_Projection::ID());
887         if (!aProducerFeature.get())
888           aProducerFeature = PartSet_Tools::findRefsToMeFeature(aFeature,
889                                                         SketchPlugin_IntersectionPoint::ID());
890         if (aProducerFeature.get())
891           myModule->editFeature(aProducerFeature);
892       }
893     }
894   }
895 }
896
897 bool PartSet_SketcherMgr::sketchSolverError()
898 {
899   bool anError = false;
900   CompositeFeaturePtr aSketch = activeSketch();
901   if (aSketch.get()) {
902     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
903     anError = !aAttributeString->value().empty();
904   }
905   return anError;
906 }
907
908 QString PartSet_SketcherMgr::getFeatureError(const FeaturePtr& theFeature)
909 {
910   QString anError;
911   if (!theFeature.get() || !theFeature->data()->isValid())
912     return anError;
913
914   CompositeFeaturePtr aSketch = activeSketch();
915   if (aSketch.get() && aSketch == theFeature) {
916     std::string aSolverError = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR())->value();
917     anError = ModuleBase_Tools::translate(aSketch->getKind(), aSolverError);
918   }
919   return anError;
920 }
921
922 void PartSet_SketcherMgr::clearClickedFlags()
923 {
924   //myClickedPoint.clear();
925   myCurrentPoint.clear();
926 }
927
928 const QStringList& PartSet_SketcherMgr::replicationsIdList()
929 {
930   static QStringList aReplicationIds;
931   if (aReplicationIds.size() == 0) {
932     aReplicationIds << SketchPlugin_ConstraintMirror::ID().c_str();
933     aReplicationIds << SketchPlugin_MultiRotation::ID().c_str();
934     aReplicationIds << SketchPlugin_MultiTranslation::ID().c_str();
935   }
936   return aReplicationIds;
937 }
938
939 const QStringList& PartSet_SketcherMgr::constraintsIdList()
940 {
941   static QStringList aConstraintIds;
942   if (aConstraintIds.size() == 0) {
943     aConstraintIds << SketchPlugin_ConstraintLength::ID().c_str();
944     aConstraintIds << SketchPlugin_ConstraintDistance::ID().c_str();
945     aConstraintIds << SketchPlugin_ConstraintRigid::ID().c_str();
946     aConstraintIds << SketchPlugin_ConstraintRadius::ID().c_str();
947     aConstraintIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
948     aConstraintIds << SketchPlugin_ConstraintParallel::ID().c_str();
949     aConstraintIds << SketchPlugin_ConstraintHorizontal::ID().c_str();
950     aConstraintIds << SketchPlugin_ConstraintVertical::ID().c_str();
951     aConstraintIds << SketchPlugin_ConstraintEqual::ID().c_str();
952     aConstraintIds << SketchPlugin_ConstraintTangent::ID().c_str();
953     aConstraintIds << SketchPlugin_ConstraintCoincidence::ID().c_str();
954     aConstraintIds << SketchPlugin_ConstraintAngle::ID().c_str();
955     aConstraintIds << SketchPlugin_ConstraintCollinear::ID().c_str();
956     aConstraintIds << SketchPlugin_ConstraintMiddle::ID().c_str();
957     aConstraintIds << SketchPlugin_ConstraintMirror::ID().c_str();
958     aConstraintIds << SketchPlugin_MultiTranslation::ID().c_str();
959     aConstraintIds << SketchPlugin_MultiRotation::ID().c_str();
960     aConstraintIds << SketchPlugin_ConstraintDistanceAlongDir::ID().c_str();
961     aConstraintIds << SketchPlugin_ConstraintDistanceHorizontal::ID().c_str();
962     aConstraintIds << SketchPlugin_ConstraintDistanceVertical::ID().c_str();
963   }
964   return aConstraintIds;
965 }
966
967 void PartSet_SketcherMgr::sketchSelectionModes(const CompositeFeaturePtr& theSketch,
968                                                QIntList& theModes)
969 {
970   if (!theSketch.get() || !PartSet_Tools::sketchPlane(theSketch).get())
971     return;
972
973   theModes.append(SketcherPrs_Tools::Sel_Dimension_Text);
974   theModes.append(SketcherPrs_Tools::Sel_Dimension_Line);
975   theModes.append(SketcherPrs_Tools::Sel_Constraint);
976   theModes.append(TopAbs_VERTEX);
977   theModes.append(TopAbs_EDGE);
978 }
979
980 Handle(AIS_InteractiveObject) PartSet_SketcherMgr::createPresentation(const ObjectPtr& theObj)
981 {
982   Handle(AIS_InteractiveObject) aPrs;
983
984   FeaturePtr aFeature = ModelAPI_Feature::feature(theObj);
985   if (aFeature.get() && aFeature->getKind() == SketchPlugin_Sketch::ID()) {
986     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObj);
987     if (aResult.get())
988       aPrs = new PartSet_ResultSketchPrs(aResult);
989   }
990   return aPrs;
991 }
992
993 bool PartSet_SketcherMgr::isSketchOperation(ModuleBase_Operation* theOperation)
994 {
995   return theOperation && theOperation->id().toStdString() == SketchPlugin_Sketch::ID();
996 }
997
998 bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation) const
999 {
1000   bool aNestedSketch = false;
1001
1002   FeaturePtr anActiveSketch = activeSketch();
1003   if (anActiveSketch.get() && theOperation) {
1004     ModuleBase_Operation* aSketchOperation = operationMgr()->findOperation(
1005                                                               anActiveSketch->getKind().c_str());
1006     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1007                                                                                   (theOperation);
1008     if (aSketchOperation && aFOperation) {
1009       FeaturePtr aFeature = aFOperation->feature();
1010       if (aFeature.get()) {
1011         QStringList aGrantedOpIds = aSketchOperation->grantedOperationIds();
1012         aNestedSketch = aGrantedOpIds.contains(aFeature->getKind().c_str());
1013       }
1014     }
1015   }
1016   return aNestedSketch;
1017 }
1018
1019 bool PartSet_SketcherMgr::isNestedSketchFeature(const QString& theFeatureKind) const
1020 {
1021   bool aNestedSketch = false;
1022
1023   FeaturePtr anActiveSketch = activeSketch();
1024   if (anActiveSketch.get()) {
1025     ModuleBase_Operation* aSketchOperation = operationMgr()->findOperation(
1026                                                               anActiveSketch->getKind().c_str());
1027     if (aSketchOperation) {
1028       QStringList aGrantedOpIds = aSketchOperation->grantedOperationIds();
1029       aNestedSketch = aGrantedOpIds.contains(theFeatureKind);
1030     }
1031   }
1032   return aNestedSketch;
1033 }
1034
1035 bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation,
1036                                                   const CompositeFeaturePtr& theSketch) const
1037 {
1038   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1039                                                                (theOperation);
1040   return aFOperation && !aFOperation->isEditOperation() &&
1041          isNestedSketchOperation(aFOperation);
1042 }
1043
1044 bool PartSet_SketcherMgr::isNestedEditOperation(ModuleBase_Operation* theOperation,
1045                                                 const CompositeFeaturePtr& theSketch) const
1046 {
1047   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1048                                                                (theOperation);
1049   return aFOperation && aFOperation->isEditOperation() &&
1050     isNestedSketchOperation(aFOperation);
1051 }
1052
1053 bool PartSet_SketcherMgr::isEntity(const std::string& theId)
1054 {
1055   return (theId == SketchPlugin_Line::ID()) ||
1056          (theId == SketchPlugin_Point::ID()) ||
1057          (theId == SketchPlugin_Arc::ID()) ||
1058          (theId == SketchPlugin_Circle::ID()) ||
1059          (theId == SketchPlugin_Ellipse::ID()) ||
1060          (theId == SketchPlugin_Projection::ID()) ||
1061          (theId == SketchPlugin_IntersectionPoint::ID()) ||
1062          (theId == SketchPlugin_EllipticArc::ID());
1063 }
1064
1065 bool PartSet_SketcherMgr::isExternalFeature(const FeaturePtr& theFeature)
1066 {
1067   std::shared_ptr<SketchPlugin_Feature> aSPFeature =
1068           std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
1069   return aSPFeature.get() && aSPFeature->isExternal();
1070 }
1071
1072 bool PartSet_SketcherMgr::isDistanceOperation(ModuleBase_Operation* theOperation)
1073 {
1074   std::string anId = theOperation ? theOperation->id().toStdString() : "";
1075
1076   return isDistanceKind(anId);
1077 }
1078
1079 bool PartSet_SketcherMgr::isDistanceKind(std::string& theKind)
1080 {
1081   return (theKind == SketchPlugin_ConstraintLength::ID()) ||
1082          (theKind == SketchPlugin_ConstraintDistance::ID()) ||
1083          (theKind == SketchPlugin_ConstraintRadius::ID()) ||
1084          (theKind == SketchPlugin_ConstraintAngle::ID()) ||
1085          (theKind == SketchPlugin_ConstraintDistanceHorizontal::ID()) ||
1086          (theKind == SketchPlugin_ConstraintDistanceVertical::ID()) ||
1087          (theKind == SketchPlugin_ConstraintDistanceAlongDir::ID());
1088 }
1089
1090 void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
1091 {
1092   static Events_ID EVENT_ATTR = Events_Loop::loop()->eventByName(EVENT_VISUAL_ATTRIBUTES);
1093   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1094
1095   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1096                                                                (getCurrentOperation());
1097   if (!aFOperation)
1098     return;
1099
1100   SketcherPrs_Tools::setPixelRatio(ModuleBase_Tools::currentPixelRatio());
1101
1102   myModule->onViewTransformed();
1103
1104   // Display all sketcher sub-Objects
1105   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFOperation->feature());
1106   double aSizeOfView = 0;
1107   std::shared_ptr<GeomAPI_Pnt> aCentralPoint;
1108   if (aFOperation->isEditOperation() &&
1109       mySketchPlane->getDefaultSizeOfView(myCurrentSketch, aSizeOfView, aCentralPoint)) {
1110     mySketchPlane->setSizeOfView(aSizeOfView, true, aCentralPoint);
1111   }
1112
1113   mySketchPlane->createSketchPlane(myCurrentSketch, myModule->workshop());
1114   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
1115
1116   // Hide sketcher result
1117   std::list<ResultPtr> aResults = myCurrentSketch->results();
1118   std::list<ResultPtr>::const_iterator aIt;
1119   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1120     (*aIt)->setDisplayed(false);
1121   }
1122   myCurrentSketch->setDisplayed(false);
1123
1124   // Remove invalid sketch entities
1125   std::set<FeaturePtr> anInvalidFeatures;
1126   ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
1127   int aNumberOfSubs = myCurrentSketch->numberOfSubs();
1128   for (int i = 0; i < aNumberOfSubs; i++) {
1129     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1130     if (aFeature.get()) {
1131       if (!aFactory->validate(aFeature))
1132         anInvalidFeatures.insert(aFeature);
1133     }
1134   }
1135   if (!anInvalidFeatures.empty()) {
1136     std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
1137     ModelAPI_Tools::findAllReferences(anInvalidFeatures, aReferences, false);
1138
1139     std::set<FeaturePtr>::const_iterator anIt = anInvalidFeatures.begin(),
1140                                          aLast = anInvalidFeatures.end();
1141     // separate features to references to parameter features and references to others
1142     QStringList anInvalidFeatureNames;
1143     for (; anIt != aLast; anIt++) {
1144       FeaturePtr aFeature = *anIt;
1145       if (aFeature.get())
1146         anInvalidFeatureNames.append(aFeature->name().c_str());
1147     }
1148     std::string aPrefixInfo = QString("Invalid features of the sketch will be deleted: %1.\n\n").
1149                                   arg(anInvalidFeatureNames.join(", ")).toStdString().c_str();
1150     std::set<FeaturePtr> aFeatureRefsToDelete;
1151     if (ModuleBase_Tools::askToDelete(anInvalidFeatures, aReferences, aConnector->desktop(),
1152                                       aFeatureRefsToDelete, aPrefixInfo)) {
1153       if (!aFeatureRefsToDelete.empty())
1154         anInvalidFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
1155       ModelAPI_Tools::removeFeatures(anInvalidFeatures, true);
1156       Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
1157       // TODO: call the next method in the XGUI_OperationMgr::onOperationStarted().
1158       workshop()->errorMgr()->updateAcceptAllAction(myCurrentSketch);
1159     }
1160   }
1161
1162   // update state of overconstraint listener should be done before sketch features/results
1163   // display (as the display will ask custom color from the listener)
1164   myModule->overconstraintListener()->setActive(true);
1165   // Display sketcher objects
1166   QStringList anInfo;
1167   const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
1168   aNumberOfSubs = myCurrentSketch->numberOfSubs();
1169   for (int i = 0; i < aNumberOfSubs; i++) {
1170     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1171 #ifdef DEBUG_SKETCHER_ENTITIES
1172     anInfo.append(ModuleBase_Tools::objectInfo(aFeature));
1173 #endif
1174     std::list<ResultPtr> aResults = aFeature->results();
1175     std::list<ResultPtr>::const_iterator aIt;
1176     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1177       if ((*aIt)->isDisplayed())
1178         // Display object if it was created outside of GUI
1179         aECreator->sendUpdated((*aIt), EVENT_DISP);
1180       else
1181         (*aIt)->setDisplayed(true);
1182     }
1183     if (aFeature->isDisplayed())
1184       aECreator->sendUpdated(aFeature, EVENT_DISP);
1185     else
1186       aFeature->setDisplayed(true);
1187     aECreator->sendUpdated(aFeature, EVENT_ATTR);
1188   }
1189 #ifdef DEBUG_SKETCHER_ENTITIES
1190   QString anInfoStr = anInfo.join(";\t");
1191   qDebug(QString("startSketch: %1, %2").arg(anInfo.size()).arg(anInfoStr).toStdString().c_str());
1192 #endif
1193
1194   std::shared_ptr<GeomAPI_Pln> aPln;
1195   aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
1196   Handle(SelectMgr_Filter) aFilter = myModule->selectionFilter(SF_SketchPlaneFilter);
1197   if (!aFilter.IsNull())
1198     Handle(ModuleBase_ShapeInPlaneFilter)::DownCast(aFilter)->setPlane(aPln);
1199
1200   workshop()->selectionActivate()->updateSelectionFilters();
1201   workshop()->selectionActivate()->updateSelectionModes();
1202
1203   Events_Loop::loop()->flush(EVENT_ATTR);
1204   Events_Loop::loop()->flush(EVENT_DISP);
1205
1206   myExternalPointsMgr = new PartSet_ExternalPointsMgr(myModule->workshop(), myCurrentSketch);
1207
1208   workshop()->viewer()->set2dMode(true);
1209
1210   PartSet_Fitter* aFitter = new PartSet_Fitter(this);
1211   myModule->workshop()->viewer()->setFitter(aFitter);
1212 }
1213
1214 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
1215 {
1216   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
1217   PartSet_Fitter* aFitter = (PartSet_Fitter*)myModule->workshop()->viewer()->fitter();
1218   myModule->workshop()->viewer()->setFitter(0);
1219   delete aFitter;
1220
1221   myIsMouseOverWindow = false;
1222   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
1223   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
1224   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
1225
1226   if (myExternalPointsMgr) {
1227     delete myExternalPointsMgr;
1228     myExternalPointsMgr = 0;
1229   }
1230   onShowPoints(false);
1231
1232   DataPtr aData = myCurrentSketch->data();
1233   if (!aData->isValid()) {
1234     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1235     // The sketch was aborted
1236     myCurrentSketch = CompositeFeaturePtr();
1237     mySketchPlane->eraseSketchPlane(myModule->workshop());
1238
1239     // Erase all sketcher objects
1240     QObjectPtrList aObjects = aDisplayer->displayedObjects();
1241     foreach (ObjectPtr aObj, aObjects) {
1242       DataPtr aObjData = aObj->data();
1243       if (!aObjData->isValid())
1244         aObj->setDisplayed(false);
1245     }
1246   }
1247   else {
1248     // Hide all sketcher sub-Objects
1249     int aNumberOfSubs = myCurrentSketch->numberOfSubs();
1250     for (int i = 0; i < aNumberOfSubs; i++) {
1251       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1252       std::list<ResultPtr> aResults = aFeature->results();
1253       std::list<ResultPtr>::const_iterator aIt;
1254       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1255         (*aIt)->setDisplayed(false);
1256       }
1257       aFeature->setDisplayed(false);
1258     }
1259     // Display sketcher result
1260     std::list<ResultPtr> aResults = myCurrentSketch->results();
1261     std::list<ResultPtr>::const_iterator aIt;
1262     Events_Loop* aLoop = Events_Loop::loop();
1263     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1264
1265     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1266                                                                            (theOperation);
1267     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1268       if (!aFOperation->isDisplayedOnStart(*aIt)) {
1269         (*aIt)->setDisplayed(true);
1270         // this display event is needed because sketch already may have "displayed" state,
1271         // but not displayed while it is still active (issue 613, abort of existing sketch)
1272         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
1273       }
1274     }
1275     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
1276       myCurrentSketch->setDisplayed(true);
1277
1278     myCurrentSketch = CompositeFeaturePtr();
1279     mySketchPlane->eraseSketchPlane(myModule->workshop());
1280
1281     Events_Loop::loop()->flush(aDispEvent);
1282   }
1283   workshop()->selectionActivate()->updateSelectionFilters();
1284   workshop()->selectionActivate()->updateSelectionModes();
1285   workshop()->viewer()->set2dMode(false);
1286 }
1287
1288 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
1289 {
1290   if (canChangeCursor(theOperation) && myIsMouseOverWindow) {
1291     QCursor* aCurrentCursor = QApplication::overrideCursor();
1292     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
1293       QApplication::setOverrideCursor(PartSet_Tools::getOperationCursor());
1294 //#ifdef DEBUG_CURSOR
1295 //      qDebug("startNestedSketch() : Qt::CrossCursor");
1296 //#endif
1297     }
1298   }
1299 }
1300
1301 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
1302 {
1303   myIsMouseOverViewProcessed = true;
1304   operationMgr()->onValidateOperation();
1305   // when sketch nested operation is stopped the cursor should be restored unconditionally
1306   if (canChangeCursor(theOperation)) {
1307     QApplication::restoreOverrideCursor();
1308 #ifdef DEBUG_CURSOR
1309     qDebug("stopNestedSketch() : None");
1310 #endif
1311   }
1312   /// improvement to deselect automatically all eventual selected objects, when
1313   // returning to the neutral point of the Sketcher
1314   bool isClearSelectionPossible = true;
1315   if (myIsEditLaunching) {
1316     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1317                                                                           (theOperation);
1318     if (aFOperation) {
1319       FeaturePtr aFeature = aFOperation->feature();
1320       if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1321         isClearSelectionPossible = false;
1322       }
1323     }
1324   }
1325   if (isClearSelectionPossible)
1326     workshop()->selector()->clearSelection();
1327   if (myPointsHighlight.size())
1328     onShowPoints(true);
1329 }
1330
1331 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
1332 {
1333   if (isNestedCreateOperation(theOperation, activeSketch())) {
1334     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1335                                                                              (theOperation);
1336     if (aFOperation) {
1337       FeaturePtr aFeature = aFOperation->feature();
1338       // it is necessary to check the the feature data validity because
1339       // some kind of features are removed by an operation commit(the macro state of a feature)
1340       if (aFeature.get() && aFeature->data()->isValid()) {
1341         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
1342       }
1343     }
1344   }
1345 }
1346
1347 bool PartSet_SketcherMgr::sketchSelectionFilter(const ModuleBase_SelectionFilterType theFilterType)
1348 {
1349   return mySelectionFilterTypes.find(theFilterType) != mySelectionFilterTypes.end();
1350 }
1351
1352 void PartSet_SketcherMgr::registerSelectionFilter(
1353   const ModuleBase_SelectionFilterType theFilterType, const Handle(SelectMgr_Filter)& theFilter)
1354 {
1355   mySelectionFilterTypes.insert(theFilterType);
1356   myModule->registerSelectionFilter(theFilterType, theFilter);
1357 }
1358
1359 bool PartSet_SketcherMgr::operationActivatedByPreselection()
1360 {
1361   bool isOperationStopped = false;
1362   ModuleBase_Operation* anOperation = getCurrentOperation();
1363   if(anOperation && isNestedSketchOperation(anOperation)) {
1364     // Set final definitions if they are necessary
1365     //propertyPanelDefined(aOperation);
1366     /// Commit sketcher operations automatically
1367     /// distance operation are able to show popup editor to modify the distance value
1368     /// after entering the value, the operation should be committed/aborted(by Esc key)
1369     bool aCanCommitOperation = true;
1370     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1371                                                                             (anOperation);
1372     if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation)) {
1373       bool aValueAccepted = setDistanceValueByPreselection(anOperation, myModule->workshop(),
1374                                                            aCanCommitOperation);
1375       if (!aValueAccepted)
1376         return isOperationStopped;
1377     }
1378
1379     if (aCanCommitOperation)
1380       isOperationStopped = anOperation->commit();
1381     else {
1382       anOperation->abort();
1383       isOperationStopped = true;
1384     }
1385   }
1386   return isOperationStopped;
1387 }
1388
1389 bool PartSet_SketcherMgr::canUndo() const
1390 {
1391   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1392 }
1393
1394 bool PartSet_SketcherMgr::canRedo() const
1395 {
1396   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1397 }
1398
1399 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1400 {
1401   bool aCanErase = true;
1402   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1403   if (myCurrentSketch.get()) {
1404     return !isObjectOfSketch(theObject);
1405   }
1406   return aCanErase;
1407 }
1408
1409 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1410 {
1411   bool aCanDisplay = true;
1412
1413   bool aHasActiveSketch = activeSketch().get() != NULL;
1414   if (aHasActiveSketch) {
1415     // 1. the sketch feature should not be displayed during the sketch active operation
1416     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch
1417     // nested features can be visualized
1418     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1419     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1420       aCanDisplay = false;
1421     }
1422     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1423                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1424     /// some sketch entities should be never shown, e.g. projection feature
1425     if (aSketchFeature.get())
1426       aCanDisplay = aSketchFeature->canBeDisplayed();
1427   }
1428   else { // there are no an active sketch
1429     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1430     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1431     if (aFeature.get() != NULL) {
1432       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1433                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1434       if (aSketchFeature.get()) {
1435         aCanDisplay = false;
1436       }
1437     }
1438   }
1439
1440   // 3. the method should not filter the objects, which are not related to the current operation.
1441   // The object is filtered just if it is a current operation feature or this feature result
1442   if (aCanDisplay) {
1443     bool isObjectFound = false;
1444     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1445                                                                  (getCurrentOperation());
1446     if (aFOperation) {
1447       FeaturePtr aFeature = aFOperation->feature();
1448       if (aFeature.get()) {
1449         std::list<ResultPtr> aResults = aFeature->results();
1450         if (theObject == aFeature)
1451           isObjectFound = true;
1452         else {
1453           std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1454           for (; anIt != aLast && !isObjectFound; anIt++) {
1455             isObjectFound = *anIt == theObject;
1456           }
1457         }
1458       }
1459     }
1460     if (isObjectFound) {
1461       // 4. For created nested feature operation do not display the created feature if
1462       // the mouse curstor leaves the OCC window.
1463       // The correction cases, which ignores this condition:
1464       // a. the property panel values modification
1465       // b. the popup menu activated
1466       // c. widget editor control
1467       #ifndef DEBUG_DO_NOT_BY_ENTER
1468       if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
1469         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1470         ModuleBase_WidgetEditor* anEditorWdg =
1471           anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1472         // the active widget editor should not influence here. The presentation should be visible
1473         // always when this widget is active.
1474         if (!anEditorWdg && !myIsPopupMenuActive) {
1475           // during a nested create operation, the feature is redisplayed only
1476           // if the mouse over view
1477           // of there was a value modified in the property panel after the mouse left the view
1478           aCanDisplay = canDisplayCurrentCreatedFeature();
1479         }
1480       }
1481       #endif
1482     }
1483   }
1484
1485   // checks the sketcher constraints visibility according to active sketch check box states
1486   if (aCanDisplay) {
1487     bool aProcessed = false;
1488     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1489     if (aFeature.get()) {
1490       bool aConstraintDisplayed = canDisplayConstraint(aFeature, PartSet_Tools::Any, aProcessed);
1491       if (aProcessed)
1492         aCanDisplay = aConstraintDisplayed;
1493     }
1494   }
1495
1496   return aCanDisplay;
1497 }
1498
1499 bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
1500                                              const PartSet_Tools::ConstraintVisibleState& theState,
1501                                              bool& isProcessed) const
1502 {
1503   bool aSwitchedOn = true;
1504
1505   const QStringList& aConstrIds = constraintsIdList();
1506
1507   std::string aKind = theFeature->getKind();
1508   if (aConstrIds.contains(QString(aKind.c_str()))) {
1509     switch (theState) {
1510       case PartSet_Tools::Dimensional: {
1511         bool isDistance = isDistanceKind(aKind);
1512         if (isDistance) {
1513           isProcessed = true;
1514           aSwitchedOn = myIsConstraintsShown[theState];
1515         }
1516       }
1517       break;
1518       case PartSet_Tools::Geometrical: {
1519         bool isGeometrical = !isDistanceKind(aKind);
1520         if (isGeometrical) {
1521           isProcessed = true;
1522           aSwitchedOn = myIsConstraintsShown[theState];
1523         }
1524       }
1525       break;
1526       case PartSet_Tools::Any: {
1527         isProcessed = true;
1528         bool isDistance = isDistanceKind(aKind);
1529         if (isDistance)
1530           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Dimensional];
1531         else
1532           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Geometrical];
1533       }
1534       break;
1535     default:
1536       break;
1537     }
1538   }
1539   return aSwitchedOn;
1540 }
1541
1542 /*void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
1543 {
1544   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1545                                                                            (getCurrentOperation());
1546   if (aFOperation && myCurrentSketch.get()) {
1547     // find results of the current operation
1548     // these results should not be proposed to be deleted
1549     FeaturePtr anOperationFeature = aFOperation->feature();
1550     std::list<ResultPtr> anOperationResultList = anOperationFeature->results();
1551     std::set<ResultPtr> anOperationResults;
1552     std::list<ResultPtr>::const_iterator aRIt = anOperationResultList.begin(),
1553                                         aRLast = anOperationResultList.end();
1554     for (; aRIt != aRLast; aRIt++)
1555       anOperationResults.insert(*aRIt);
1556
1557     std::set<FeaturePtr> anObjectsToBeDeleted;
1558     QStringList anObjectsToBeDeletedNames;
1559     std::list<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1560     for (; anIt != aLast; anIt++) {
1561       ObjectPtr anObject = *anIt;
1562       bool aCanErase = true;
1563       // when the sketch operation is active, results of sketch sub-feature can not be hidden
1564       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1565       // the result is found between current feature results
1566       if (anOperationResults.find(aResult) != anOperationResults.end())
1567         continue;
1568
1569       if (aResult.get()) {
1570         // Display sketcher objects
1571         for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1572           FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1573           std::list<ResultPtr> aResults = aFeature->results();
1574           std::list<ResultPtr>::const_iterator anIt;
1575           for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1576             aCanErase = *anIt != aResult;
1577           }
1578         }
1579       }
1580       if (!aCanErase) {
1581         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
1582         if (aFeature.get() && anObjectsToBeDeleted.find(aFeature) == anObjectsToBeDeleted.end()) {
1583           anObjectsToBeDeleted.insert(aFeature);
1584           anObjectsToBeDeletedNames.append(aFeature->name().c_str());
1585         }
1586       }
1587     }
1588     if (!anObjectsToBeDeleted.empty()) {
1589       QString aFeatureNames = anObjectsToBeDeletedNames.join(", ");
1590       QString aMessage = tr("The following features have incorrect presentation and \
1591 will be hidden: %1. Would you like to delete them?")
1592                          .arg(aFeatureNames);
1593       int anAnswer = QMessageBox::question(qApp->activeWindow(), tr("Features hide"),
1594                                            aMessage, QMessageBox::Ok | QMessageBox::Cancel,
1595                                            QMessageBox::Cancel);
1596       if (anAnswer == QMessageBox::Ok) {
1597         QObjectPtrList anObjects;
1598         std::set<FeaturePtr>::const_iterator anIt = anObjectsToBeDeleted.begin(),
1599                                              aLast = anObjectsToBeDeleted.end();
1600         for (; anIt != aLast; anIt++)
1601           anObjects.append(*anIt);
1602         SessionPtr aMgr = ModelAPI_Session::get();
1603         DocumentPtr aDoc = aMgr->activeDocument();
1604         bool aIsOp = aMgr->isOperation();
1605         if (!aIsOp)
1606           aMgr->startOperation();
1607         workshop()->deleteFeatures(anObjects);
1608         //static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
1609         //static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
1610         //Events_Loop::loop()->flush(aDeletedEvent);
1611         //Events_Loop::loop()->flush(aRedispEvent);
1612
1613         if (!aIsOp)
1614           aMgr->finishOperation();
1615       }
1616     }
1617   }
1618 }*/
1619
1620 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1621 {
1622   bool aCanDisplay = myIsMouseOverWindow;
1623   if (!aCanDisplay) {
1624     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1625     if (anActiveWidget)
1626       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1627   }
1628   return aCanDisplay;
1629 }
1630
1631 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1632 {
1633   return isNestedCreateOperation(theOperation, activeSketch()) ||
1634          myModule->sketchReentranceMgr()->isInternalEditActive();
1635 }
1636
1637 const QMap<PartSet_Tools::ConstraintVisibleState, bool>& PartSet_SketcherMgr::showConstraintStates()
1638 {
1639   return myIsConstraintsShown;
1640 }
1641
1642 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1643 {
1644   if (!myCurrentSketch.get())
1645     return false;
1646   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1647   if (anObjectFeature.get()) {
1648     int aSize = myCurrentSketch->numberOfSubs();
1649     FeaturePtr aCurrentFeature;
1650     for (int i = 0; i < aSize; i++) {
1651       aCurrentFeature = myCurrentSketch->subFeature(i);
1652       if (myCurrentSketch->subFeature(i) == anObjectFeature)
1653         return true;
1654     }
1655   }
1656   return false;
1657 }
1658
1659 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePlane)
1660 {
1661   Handle(SelectMgr_Filter) aFilter = myModule->selectionFilter(SF_SketchPlaneFilter);
1662   if (!aFilter.IsNull())
1663     Handle(ModuleBase_ShapeInPlaneFilter)::DownCast(aFilter)->setPlane(thePlane);
1664
1665   workshop()->selectionActivate()->updateSelectionModes();
1666 }
1667
1668 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
1669                                                          ModuleBase_IWorkshop* theWorkshop,
1670                                                          bool& theCanCommitOperation)
1671 {
1672   bool isValueAccepted = false;
1673   theCanCommitOperation = false;
1674
1675   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1676                                                                               (theOperation);
1677   FeaturePtr aFeature = aFOperation->feature();
1678   // editor is shown only if all attribute references are filled by preseletion
1679   bool anAllRefAttrInitialized = true;
1680
1681   std::list<AttributePtr> aRefAttrs = aFeature->data()->attributes(
1682                                               ModelAPI_AttributeRefAttr::typeId());
1683   std::list<AttributePtr>::const_iterator anIt = aRefAttrs.begin(), aLast = aRefAttrs.end();
1684   for (; anIt != aLast && anAllRefAttrInitialized; anIt++) {
1685     anAllRefAttrInitialized = (*anIt)->isInitialized();
1686   }
1687   if (anAllRefAttrInitialized) {
1688     // Activate dimension value editing on double click
1689     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
1690     QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
1691     // Find corresponded widget to activate value editing
1692     foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
1693       if (aWgt->attributeID() == "ConstraintValue") {
1694         // the featue should be displayed in order to find the AIS text position,
1695         // the place where the editor will be shown
1696         aFeature->setDisplayed(true);
1697         /// the execute is necessary to perform in the feature compute for flyout position
1698         aFeature->execute();
1699
1700         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1701         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1702
1703         PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
1704         if (anEditor) {
1705           int aX = 0, anY = 0;
1706
1707           XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(theWorkshop);
1708           XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1709           AISObjectPtr anAIS = aDisplayer->getAISObject(aFeature);
1710           Handle(AIS_InteractiveObject) anAISIO;
1711           if (anAIS.get() != NULL) {
1712             anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1713           }
1714           if (anAIS.get() != NULL) {
1715             Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1716
1717             if (!anAISIO.IsNull()) {
1718               Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAISIO);
1719               if (!aDim.IsNull()) {
1720                 gp_Pnt aPosition = aDim->GetTextPosition();
1721
1722                 ModuleBase_IViewer* aViewer = aWorkshop->viewer();
1723                 Handle(V3d_View) aView = aViewer->activeView();
1724                 int aCX, aCY;
1725                 aView->Convert(aPosition.X(), aPosition.Y(), aPosition.Z(), aCX, aCY);
1726
1727                 QWidget* aViewPort = aViewer->activeViewPort();
1728                 QPoint aGlPoint = aViewPort->mapToGlobal(QPoint(aCX, aCY));
1729                 aX = aGlPoint.x();
1730                 anY = aGlPoint.y();
1731               }
1732             }
1733             anEditor->setCursorPosition(aX, anY);
1734             isValueAccepted = anEditor->showPopupEditor(false);
1735             theCanCommitOperation = true;
1736           }
1737         }
1738       }
1739     }
1740   }
1741   return isValueAccepted;
1742 }
1743
1744 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1745                                              const FeaturePtr& theSketch,
1746                                              ModuleBase_IWorkshop* theWorkshop,
1747                                              const FeatureToSelectionMap& theSelection,
1748                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1749 {
1750   if (theFeature.get() == NULL)
1751     return;
1752
1753   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1754   SelectionInfo anInfo = anIt.value();
1755   std::map<AttributePtr, int> aSelectedAttributes = anInfo.myAttributes;
1756   std::set<ResultPtr> aSelectedResults = anInfo.myResults;
1757
1758   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1759   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1760
1761   // 1. found the feature's owners. Check the AIS objects of the constructions
1762   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1763   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1764     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1765
1766     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1767     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1768     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1769       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1770       if (!anOwner.IsNull())
1771         theOwnersToSelect.Add(anOwner);
1772     }
1773   }
1774
1775   // 2. found the feature results's owners
1776   std::list<ResultPtr> aResults = theFeature->results();
1777   std::list<ResultPtr>::const_iterator aIt;
1778
1779   bool isSameShape = false;
1780   if (aResults.size() > 0) {
1781     ResultPtr aFirstResult = theFeature->firstResult();
1782     if (aFirstResult.get() && aFirstResult->shape().get()) {
1783       TopoDS_Shape aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
1784       isSameShape = aFirstShape.IsEqual(anInfo.myFirstResultShape);
1785     }
1786   }
1787   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1788     ResultPtr aResult = *aIt;
1789     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1790     if (aAISObj.get() == NULL)
1791       continue;
1792     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1793
1794     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1795     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1796     bool aFoundLocalShape = false;
1797     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1798       Handle(StdSelect_BRepOwner) anOwner =
1799         Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1800       if ( anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
1801         continue;
1802       const TopoDS_Shape& aShape = anOwner->Shape();
1803       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1804       if (aShapeType == TopAbs_VERTEX) {
1805         std::pair<AttributePtr, int> aPntAttrIndex =
1806           PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1807         if (aPntAttrIndex.first.get() != NULL &&
1808             aSelectedAttributes.find(aPntAttrIndex.first) != aSelectedAttributes.end())
1809           theOwnersToSelect.Add(anOwner);
1810         else if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
1811           theOwnersToSelect.Add(anOwner);
1812         }
1813       }
1814       else if (aShapeType == TopAbs_EDGE) {
1815         if (isSameShape && anInfo.myLocalSelectedShapes.Contains(aShape)) {
1816           // try to restore local selection on Shape result
1817           // we can do this only if the shape was not changed
1818           theOwnersToSelect.Add(anOwner);
1819           aFoundLocalShape = true;
1820           break;
1821         }
1822       }
1823     }
1824     if (!aFoundLocalShape) {
1825       // result owners are put in the list of selection only if local selected shapes were not
1826       // found
1827       if (aSelectedResults.find(aResult) != aSelectedResults.end()) {
1828         for (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1829           Handle(StdSelect_BRepOwner) anOwner =
1830               Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1831           if (anOwner.IsNull() || !anOwner->HasShape() || theOwnersToSelect.FindIndex(anOwner))
1832             continue;
1833           // select whole result
1834           theOwnersToSelect.Add(anOwner);
1835         }
1836       }
1837     }
1838   }
1839 }
1840
1841 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget,
1842                                                  const bool isToConnect)
1843 {
1844   //Temporary commented as we do not modify values in property panel
1845   if (isToConnect) {
1846     //connect(theWidget, SIGNAL(beforeValuesChanged()),
1847     //        this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1848     //connect(theWidget, SIGNAL(afterValuesChanged()),
1849     //        this, SLOT(onAfterValuesChangedInPropertyPanel()));
1850     connect(theWidget, SIGNAL(afterValuesChanged()),
1851             myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
1852   }
1853   else {
1854     //disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1855     //            this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1856     //disconnect(theWidget, SIGNAL(afterValuesChanged()),
1857     //            this, SLOT(onAfterValuesChangedInPropertyPanel()));
1858     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1859                myModule->sketchReentranceMgr(), SLOT(onAfterValuesChangedInPropertyPanel()));
1860   }
1861 }
1862
1863 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1864 {
1865   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1866                                                                            (getCurrentOperation());
1867   if (aFOperation) {
1868     if ((PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1869          isNestedSketchOperation(aFOperation)) &&
1870         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1871       FeaturePtr aFeature = aFOperation->feature();
1872       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1873     }
1874   }
1875 }
1876
1877 //void PartSet_SketcherMgr::customisePresentation(const ObjectPtr& theObject)
1878 //{
1879 //  ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1880 //                                                                           (getCurrentOperation());
1881 //  if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1882 //                      isNestedSketchOperation(aFOperation)))
1883 //    SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
1884 //
1885 //  // update entities selection priorities
1886 //  FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1887 //  if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1888 //    // update priority for feature
1889 //    updateSelectionPriority(aFeature, aFeature);
1890 //    // update priority for results of the feature
1891 //    std::list<ResultPtr> aResults = aFeature->results();
1892 //    std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLastIt = aResults.end();
1893 //    for (; anIt != aLastIt; anIt++)
1894 //      updateSelectionPriority(*anIt, aFeature);
1895 //  }
1896 //}
1897
1898 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1899 {
1900   return myModule->workshop()->currentOperation();
1901 }
1902
1903 //**************************************************************
1904 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1905 {
1906   ModuleBase_ModelWidget* aWidget = 0;
1907   ModuleBase_Operation* anOperation = getCurrentOperation();
1908   if (anOperation) {
1909     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1910     if (aPanel)
1911       aWidget = aPanel->activeWidget();
1912   }
1913   return aWidget;
1914 }
1915
1916 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1917                                            const bool isEditOperation,
1918                                            const bool isToDisplay,
1919                                            const bool isFlushRedisplay)
1920 {
1921   #ifdef DEBUG_DO_NOT_BY_ENTER
1922   return;
1923   #endif
1924
1925   if (isEditOperation || !theFeature.get())
1926     return;
1927
1928   // 1. change visibility of the object itself, here the presentable object is processed,
1929   // e.g. constraints features
1930   //FeaturePtr aFeature = aFOperation->feature();
1931   std::list<ResultPtr> aResults = theFeature->results();
1932   if (isToDisplay)
1933     theFeature->setDisplayed(true);
1934   else
1935     theFeature->setDisplayed(false);
1936
1937   // change visibility of the object results, e.g. non-constraint features
1938   std::list<ResultPtr>::const_iterator aIt;
1939   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1940     if (isToDisplay) {
1941       (*aIt)->setDisplayed(true);
1942     }
1943     else {
1944       (*aIt)->setDisplayed(false);
1945     }
1946   }
1947   if (isFlushRedisplay)
1948     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1949 }
1950
1951 void PartSet_SketcherMgr::storeSelection(const SelectionType theType,
1952                         PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
1953 {
1954   if (!myCurrentSketch.get())
1955     return;
1956
1957   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1958   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1959   QList<ModuleBase_ViewerPrsPtr> aStoredPrs;
1960
1961   if (theType == ST_HighlightType || theType == ST_SelectAndHighlightType)
1962     aStoredPrs = aSelect->getHighlighted();
1963
1964   QList<FeaturePtr> aFeatureList;
1965   if (theType == ST_SelectAndHighlightType || theType == ST_SelectType) {
1966     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(
1967                                                               ModuleBase_ISelection::AllControls);
1968     aStoredPrs.append(aSelected);
1969   }
1970
1971   // 1. it is necessary to save current selection in order to restore it after the features moving
1972   theCurrentSelection.clear();
1973
1974   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = aStoredPrs.begin(),
1975                                                 aLast = aStoredPrs.end();
1976
1977   CompositeFeaturePtr aSketch = activeSketch();
1978   for (; anIt != aLast; anIt++) {
1979     ModuleBase_ViewerPrsPtr aPrs = *anIt;
1980     ObjectPtr anObject = aPrs->object();
1981     if (!anObject.get())
1982       continue;
1983
1984     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1985     FeaturePtr aFeature;
1986     if (aResult.get())
1987       aFeature = ModelAPI_Feature::feature(aResult);
1988     else
1989       aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1990
1991     if (!aFeature.get())
1992       continue;
1993
1994     std::set<AttributePtr> aSelectedAttributes;
1995     std::set<ResultPtr> aSelectedResults;
1996     SelectionInfo anInfo;
1997     if (theCurrentSelection.find(aFeature) != theCurrentSelection.end())
1998       anInfo = theCurrentSelection.find(aFeature).value();
1999
2000     TopoDS_Shape aFirstShape;
2001     ResultPtr aFirstResult = aFeature->firstResult();
2002     if (aFirstResult.get() && aFirstResult->shape().get())
2003       aFirstShape = aFirstResult->shape()->impl<TopoDS_Shape>();
2004     anInfo.myFirstResultShape = aFirstShape;
2005     Handle(SelectMgr_EntityOwner) anOwner = aPrs->owner();
2006     if (aResult.get()) {
2007       getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
2008           anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
2009     }
2010     else {
2011       std::list<ResultPtr> aResults = aFeature->results();
2012       std::list<ResultPtr>::const_iterator aIt;
2013       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
2014         ResultPtr aResult = *aIt;
2015         getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
2016           anInfo.myAttributes, anInfo.myResults, anInfo.myLocalSelectedShapes);
2017       }
2018     }
2019     theCurrentSelection[aFeature] = anInfo;
2020   }
2021   //qDebug(QString("  storeSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
2022 }
2023
2024 void PartSet_SketcherMgr::restoreSelection(
2025                                 PartSet_SketcherMgr::FeatureToSelectionMap& theCurrentSelection)
2026 {
2027   if (!myCurrentSketch.get())
2028     return;
2029
2030   //qDebug(QString("restoreSelection: %1").arg(theCurrentSelection.size()).toStdString().c_str());
2031   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
2032   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
2033   FeatureToSelectionMap::const_iterator aSIt = theCurrentSelection.begin(),
2034                                         aSLast = theCurrentSelection.end();
2035   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
2036   anOwnersToSelect.Clear();
2037   for (; aSIt != aSLast; aSIt++) {
2038     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, theCurrentSelection,
2039                        anOwnersToSelect);
2040   }
2041   aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
2042 }
2043
2044 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
2045 {
2046   PartSet_Tools::ConstraintVisibleState aType = (PartSet_Tools::ConstraintVisibleState)theType;
2047
2048   updateBySketchParameters(aType, theState);
2049   myModule->workshop()->viewer()->update();
2050 }
2051
2052 void PartSet_SketcherMgr::updateBySketchParameters(
2053                                    const PartSet_Tools::ConstraintVisibleState& theType,
2054                                    bool theState)
2055 {
2056   if (myCurrentSketch.get() == NULL)
2057     return;
2058
2059   bool aPrevState = myIsConstraintsShown[theType];
2060   myIsConstraintsShown[theType] = theState;
2061
2062   switch (theType) {
2063     case PartSet_Tools::Geometrical:
2064     case PartSet_Tools::Dimensional: {
2065       if (aPrevState != theState) {
2066         int aNumberOfSubs = myCurrentSketch->numberOfSubs();
2067         for (int i = 0; i < aNumberOfSubs; i++) {
2068           FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
2069           bool aProcessed = false;
2070           bool aConstraintDisplayed = canDisplayConstraint(aSubFeature, theType, aProcessed);
2071           if (aProcessed)
2072             aSubFeature->setDisplayed(aConstraintDisplayed);
2073         }
2074         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
2075       }
2076     }
2077     break;
2078     case PartSet_Tools::Expressions: {
2079       if (aPrevState != theState) {
2080         /// call all sketch features redisplay, the expression state will be corrected in customize
2081         /// of distance presentation
2082         SketcherPrs_Tools::ParameterStyle aStyle = myIsConstraintsShown[PartSet_Tools::Expressions]
2083           ? SketcherPrs_Tools::ParameterText : SketcherPrs_Tools::ParameterValue;
2084         SketcherPrs_Tools::setParameterStyle(aStyle);
2085         Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
2086         PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
2087       }
2088     }
2089     break;
2090     default: // [to avoid compilation warning]
2091       break;
2092   }
2093 }
2094
2095 void PartSet_SketcherMgr::updateSelectionPriority(ObjectPtr theObject,
2096                                                   FeaturePtr theFeature)
2097 {
2098   if (!theObject.get() || !theFeature.get())
2099     return;
2100
2101   AISObjectPtr anAIS = workshop()->displayer()->getAISObject(theObject);
2102   Handle(AIS_InteractiveObject) anAISIO;
2103   if (anAIS.get() != NULL) {
2104     anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
2105   }
2106
2107   if (!anAISIO.IsNull()) { // the presentation for the object is visualized
2108     int anAdditionalPriority = 0;
2109     // current feature
2110     std::shared_ptr<SketchPlugin_Feature> aSPFeature =
2111             std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
2112     if (aSPFeature.get() != NULL) {
2113       // 1. Vertices
2114       // 2. Simple segments
2115       // 3. External objects (violet color)
2116       // 4. Auxiliary segments (dotted)
2117       // StdSelect_BRepSelectionTool::Load uses priority calculating:
2118       // Standard_Integer aPriority =
2119       // (thePriority == -1) ? GetStandardPriority (theShape, theType) : thePriority;
2120       // Priority of Vertex is 8, edge(segment) is 7.
2121       // It might be not corrected as provides the condition above.
2122       bool isExternal = aSPFeature->isExternal();
2123       bool isAuxiliary = PartSet_Tools::isAuxiliarySketchEntity(aSPFeature);
2124       // current feature
2125       if (!isExternal && !isAuxiliary)
2126         anAdditionalPriority = 30;
2127       // external feature
2128       if (isExternal)
2129         anAdditionalPriority = 20;
2130       // auxiliary feature
2131       if (isAuxiliary) {
2132         anAdditionalPriority = 10; /// auxiliary objects should have less priority that
2133         // edges/vertices of local selection on not-sketch objects
2134       }
2135       Handle(ModuleBase_ResultPrs) aResult = Handle(ModuleBase_ResultPrs)::DownCast(anAISIO);
2136       if (!aResult.IsNull()) {
2137         aResult->setAdditionalSelectionPriority(anAdditionalPriority);
2138       }
2139     }
2140   }
2141 }
2142
2143 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
2144 {
2145   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
2146   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
2147   return aConnector->workshop();
2148 }
2149
2150 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
2151 {
2152   return workshop()->operationMgr();
2153 }
2154
2155 void PartSet_SketcherMgr::onShowPoints(bool toShow)
2156 {
2157   if (!myCurrentSketch.get())
2158     return;
2159   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
2160   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
2161   Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
2162
2163   bool aToUpdate = false;
2164   if (toShow) {
2165     std::list<ResultPtr> aFreePoints = SketcherPrs_Tools::getFreePoints(myCurrentSketch);
2166
2167     // Delete obsolete presentations
2168     std::list<ResultPtr> aDelList;
2169     foreach(ResultPtr aObj, myPointsHighlight.keys()) {
2170       bool aFound = (std::find(aFreePoints.begin(), aFreePoints.end(), aObj) != aFreePoints.end());
2171       if (!aFound)
2172         aDelList.push_back(aObj);
2173     }
2174     foreach(ResultPtr aObj, aDelList) {
2175       aContext->Remove(myPointsHighlight[aObj], false);
2176       aToUpdate = true;
2177       myPointsHighlight.remove(aObj);
2178     }
2179
2180     // Display new objects
2181     QList<ResultPtr> aKeysList = myPointsHighlight.keys();
2182     std::list<ResultPtr>::const_iterator aIt;
2183     for (aIt = aFreePoints.cbegin(); aIt != aFreePoints.cend(); aIt++) {
2184       if (!aKeysList.contains(*aIt)) {
2185         GeomShapePtr aShapePtr = (*aIt)->shape();
2186         TopoDS_Shape aShape = aShapePtr->impl<TopoDS_Shape>();
2187         Handle(AIS_Shape) aShapePrs = new AIS_Shape(aShape);
2188         aShapePrs->SetColor(Quantity_NOC_BLUE1);
2189         aShapePrs->SetZLayer(Graphic3d_ZLayerId_Top);
2190         Handle(Prs3d_Drawer) aDrawer = aShapePrs->Attributes();
2191         if (aDrawer->HasOwnPointAspect()) {
2192           aDrawer->PointAspect()->SetTypeOfMarker(Aspect_TOM_O_STAR);
2193           aDrawer->PointAspect()->SetColor(Quantity_NOC_BLUE1);
2194           aDrawer->PointAspect()->SetScale(2);
2195         }
2196         else
2197           aDrawer->SetPointAspect(new Prs3d_PointAspect(Aspect_TOM_O_STAR, Quantity_NOC_BLUE1, 2));
2198         aContext->Display(aShapePrs, false);
2199         aContext->Deactivate(aShapePrs);
2200         myPointsHighlight[*aIt] = aShapePrs;
2201         aToUpdate = true;
2202       }
2203     }
2204   }
2205   else {
2206     foreach(Handle(AIS_Shape) aPrs, myPointsHighlight.values()) {
2207       aContext->Remove(aPrs, false);
2208       aToUpdate = true;
2209     }
2210     myPointsHighlight.clear();
2211   }
2212   if (aToUpdate)
2213     aViewer->update();
2214 }
2215
2216 void PartSet_SketcherMgr::processEvent(const std::shared_ptr<Events_Message>& theMessage)
2217 {
2218   if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_DOF_OBJECTS)) {
2219     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
2220       std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
2221     std::set<ObjectPtr> aObjects = anUpdateMsg->objects();
2222     std::set<ObjectPtr>::const_iterator aIt;
2223     QList<ModuleBase_ViewerPrsPtr> aPrsList;
2224     for (aIt = aObjects.cbegin(); aIt != aObjects.cend(); aIt++) {
2225       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*aIt);
2226       if (aFeature.get()) {
2227         std::list<ResultPtr> aRes = aFeature->results();
2228         std::list<ResultPtr>::const_iterator aIt;
2229         for (aIt = aRes.cbegin(); aIt != aRes.cend(); ++aIt) {
2230           ModuleBase_ViewerPrsPtr aPrsPtr(new ModuleBase_ViewerPrs(*aIt));
2231           aPrsList.append(aPrsPtr);
2232         }
2233       }
2234     }
2235     if (aPrsList.size() > 0) {
2236       myModule->workshop()->setSelected(aPrsList);
2237     }
2238   }
2239 }
2240
2241 bool isExternal(const ObjectPtr& theObject)
2242 {
2243   AttributeSelectionPtr aAttr =
2244     theObject->data()->selection(SketchPlugin_SketchEntity::EXTERNAL_ID());
2245   if (aAttr)
2246     return aAttr->context().get() != NULL && !aAttr->isInvalid();
2247   return false;
2248 }
2249
2250 bool isCopy(const ObjectPtr& theObject)
2251 {
2252   AttributeBooleanPtr anAttr = theObject->data()->boolean(SketchPlugin_SketchEntity::COPY_ID());
2253   if (anAttr.get())
2254     return anAttr->value();
2255   return false;
2256 }
2257
2258 bool isIncludeToResult(const ObjectPtr& theObject)
2259 {
2260   AttributeBooleanPtr anAttr;
2261   std::set<AttributePtr> aRefsToMe = theObject->data()->refsToMe();
2262   std::set<AttributePtr>::const_iterator aIt;
2263   for (aIt = aRefsToMe.cbegin(); aIt != aRefsToMe.cend(); ++aIt) {
2264     if ((*aIt)->id() == SketchPlugin_Projection::PROJECTED_FEATURE_ID()) {
2265       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aIt)->owner());
2266       if (aFeature.get()) {
2267         anAttr = aFeature->data()->boolean(SketchPlugin_Projection::INCLUDE_INTO_RESULT());
2268         if (anAttr.get())
2269           return anAttr->value();
2270       }
2271     }
2272   }
2273   return true;
2274 }
2275
2276 //**************************************************************************************
2277 std::vector<int> PartSet_SketcherMgr::colorOfObject(const ObjectPtr& theObject,
2278   const FeaturePtr& theFeature, bool isConstruction) const
2279 {
2280   PartSet_OverconstraintListener* aOCListener = myModule->overconstraintListener();
2281   std::string aKind = theFeature->getKind();
2282
2283   if (aOCListener->isConflictingObject(theObject)) {
2284     return Config_PropManager::color("Visualization", "sketch_overconstraint_color");
2285   }
2286   if (aOCListener->isFullyConstrained()) {
2287     return Config_PropManager::color("Visualization", "sketch_fully_constrained_color");
2288   }
2289   if (isDistanceKind(aKind)) {
2290     return Config_PropManager::color("Visualization", "sketch_dimension_color");
2291   }
2292   if (aKind == SketchPlugin_ConstraintCoincidence::ID())
2293     return std::vector<int>(3, 0);
2294
2295   if (isExternal(theFeature))
2296     return Config_PropManager::color("Visualization", "sketch_external_color");
2297   if (isConstruction)
2298     return Config_PropManager::color("Visualization", "sketch_auxiliary_color");
2299
2300   return Config_PropManager::color("Visualization", "sketch_entity_color");
2301 }
2302
2303 //**************************************************************************************
2304 void PartSet_SketcherMgr::customizeSketchPresentation(const ObjectPtr& theObject,
2305   const AISObjectPtr& thePrs) const
2306 {
2307   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
2308
2309   // set color from preferences
2310   std::shared_ptr<ModelAPI_AttributeBoolean> anAuxiliaryAttr =
2311     aFeature->data()->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID());
2312   bool isConstruction = anAuxiliaryAttr.get() != NULL && anAuxiliaryAttr->value();
2313
2314   std::vector<int> aColor = colorOfObject(theObject, aFeature, isConstruction);
2315   if (!aColor.empty()) {
2316     // The code below causes redisplay again
2317     if (ModelAPI_Session::get()->isOperation()) {
2318       AttributeIntArrayPtr aColorAttr = theObject->data()->intArray(ModelAPI_Result::COLOR_ID());
2319       if (aColorAttr.get()) {
2320         aColorAttr->setSize(3, false);
2321         // Set the color attribute in order do not use default colors in the presentation object
2322         for (int i = 0; i < 3; i++)
2323           aColorAttr->setValue(i, aColor[i], false);
2324       }
2325     }
2326     thePrs->setColor(aColor[0], aColor[1], aColor[2]);
2327   }
2328
2329   int aShapeType = thePrs->getShapeType();
2330   // a compound is processed like the edge because the
2331   // arc feature uses the compound for presentable AIS
2332   if (aShapeType != 6/*an edge*/ && aShapeType != 7/*a vertex*/ && aShapeType != 0/*compound*/)
2333     return;
2334
2335   int aWidth = Config_PropManager::integer("Visualization", "sketch_line_width");
2336   if (isExternal(aFeature)) {
2337     thePrs->setWidth(isIncludeToResult(aFeature)? aWidth : 1);
2338     return;
2339   }
2340   std::string aKind = aFeature->getKind();
2341   if (isDistanceKind(aKind))
2342     return;
2343
2344   if (aShapeType == 6 || aShapeType == 0) { // if this is an edge or a compound
2345     if (isConstruction) {
2346       // Set axilliary line
2347       thePrs->setWidth(SketchPlugin_SketchEntity::SKETCH_LINE_WIDTH_AUXILIARY());
2348       thePrs->setLineStyle(SketchPlugin_SketchEntity::SKETCH_LINE_STYLE_AUXILIARY());
2349     }
2350     else {
2351       thePrs->setWidth(aWidth);
2352       thePrs->setLineStyle(SketchPlugin_SketchEntity::SKETCH_LINE_STYLE());
2353     }
2354   }
2355   else if (aShapeType == 7) { // otherwise this is a vertex
2356                               // The width value do not have effect on the point presentation.
2357                               // It is defined in order to extend selection area of the object.
2358     thePrs->setWidth(17);
2359     //  thePrs->setPointMarker(1, 1.); // Set point as a '+' symbol
2360   }
2361   if (isCopy(aFeature) && !isIncludeToResult(aFeature)) {
2362     double aWidth = thePrs->width();
2363     thePrs->setWidth(aWidth / 2.5);
2364   }
2365
2366   double aDeflection = Config_PropManager::real("Visualization", "construction_deflection");
2367   thePrs->setDeflection(aDeflection);
2368 }
2369
2370 //*************************************************************************************
2371 void PartSet_Fitter::fitAll(Handle(V3d_View) theView)
2372 {
2373   CompositeFeaturePtr aSketch = mySketchMgr->activeSketch();
2374
2375   ModuleBase_IWorkshop* aWorkshop = mySketchMgr->module()->workshop();
2376   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
2377   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
2378
2379   Bnd_Box aBndBox;
2380   int aNumberOfSubs = aSketch->numberOfSubs();
2381   double aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
2382   for (int i = 0; i < aNumberOfSubs; i++) {
2383     FeaturePtr aFeature = aSketch->subFeature(i);
2384     if (aDisplayer->isVisible(aFeature)) {
2385       AISObjectPtr aAisPtr = aDisplayer->getAISObject(aFeature);
2386       Handle(AIS_InteractiveObject) aAisObj = aAisPtr->impl<Handle(AIS_InteractiveObject)>();
2387       if (!aAisObj->IsInfinite()) {
2388         Bnd_Box aBox;
2389         aAisObj->BoundingBox(aBox);
2390         aBndBox.Add(aBox);
2391       }
2392     }
2393     else {
2394       std::list<ResultPtr> aResults = aFeature->results();
2395       std::list<ResultPtr>::const_iterator aIt;
2396       ResultPtr aRes;
2397       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
2398         aRes = (*aIt);
2399         if (aRes->isDisplayed()) {
2400           FeaturePtr aFeature = ModelAPI_Feature::feature(aRes);
2401           if (aFeature.get()) {
2402             std::shared_ptr<SketchPlugin_Feature> aSPFeature =
2403               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
2404             if (aSPFeature.get()) {
2405               bool isAxiliary =
2406                 aSPFeature->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value();
2407               if (!(aSPFeature->isExternal() || isAxiliary)) {
2408                 GeomShapePtr aShape = aRes->shape();
2409                 aShape->computeSize(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2410                 Bnd_Box aBox;
2411                 aBox.Update(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2412                 aBndBox.Add(aBox);
2413               }
2414             }
2415           }
2416         }
2417       }
2418     }
2419   }
2420   if (aBndBox.IsVoid())
2421     theView->FitAll();
2422   else
2423     theView->FitAll(aBndBox, 0.01);
2424 }