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