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