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