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