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