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