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