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