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