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