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