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