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