Salome HOME
24256731d1ca82ba43ebc8a48815b5d4289b0e49
[modules/shaper.git] / src / PartSet / PartSet_SketcherMgr.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        PartSet_SketcherMgr.cpp
4 // Created:     19 Dec 2014
5 // Author:      Vitaly SMETANNIKOV
6
7 #include "PartSet_SketcherMgr.h"
8 #include "PartSet_SketcherReetntrantMgr.h"
9 #include "PartSet_Module.h"
10 #include "PartSet_MouseProcessor.h"
11 #include "PartSet_Tools.h"
12 #include "PartSet_WidgetSketchLabel.h"
13 #include "PartSet_WidgetEditor.h"
14 #include "PartSet_ResultSketchPrs.h"
15
16 #include <XGUI_ModuleConnector.h>
17 #include <XGUI_Displayer.h>
18 #include <XGUI_Workshop.h>
19 #include <XGUI_ContextMenuMgr.h>
20 #include <XGUI_Selection.h>
21 #include <XGUI_SelectionMgr.h>
22 #include <XGUI_ModuleConnector.h>
23 #include <XGUI_PropertyPanel.h>
24 #include <XGUI_ViewerProxy.h>
25 #include <XGUI_OperationMgr.h>
26 #include <XGUI_ErrorMgr.h>
27 #include <XGUI_Tools.h>
28
29 #include <ModuleBase_IPropertyPanel.h>
30 #include <ModuleBase_ISelection.h>
31 #include <ModuleBase_IViewer.h>
32 #include <ModuleBase_IWorkshop.h>
33 #include <ModuleBase_IViewWindow.h>
34 #include <ModuleBase_ModelWidget.h>
35 #include <ModuleBase_Operation.h>
36 #include <ModuleBase_OperationFeature.h>
37 #include <ModuleBase_Operation.h>
38 #include <ModuleBase_WidgetEditor.h>
39 #include <ModuleBase_ViewerPrs.h>
40 #include <ModuleBase_Tools.h>
41 #include <ModuleBase_ResultPrs.h>
42
43 #include <GeomDataAPI_Point2D.h>
44
45 #include <Events_Loop.h>
46
47 #include <SketchPlugin_Line.h>
48 #include <SketchPlugin_Sketch.h>
49 #include <SketchPlugin_Point.h>
50 #include <SketchPlugin_Arc.h>
51 #include <SketchPlugin_Circle.h>
52 #include <SketchPlugin_ConstraintLength.h>
53 #include <SketchPlugin_ConstraintDistance.h>
54 #include <SketchPlugin_ConstraintParallel.h>
55 #include <SketchPlugin_ConstraintPerpendicular.h>
56 #include <SketchPlugin_ConstraintRadius.h>
57 #include <SketchPlugin_ConstraintRigid.h>
58 #include <SketchPlugin_ConstraintHorizontal.h>
59 #include <SketchPlugin_ConstraintVertical.h>
60 #include <SketchPlugin_ConstraintEqual.h>
61 #include <SketchPlugin_ConstraintTangent.h>
62 #include <SketchPlugin_ConstraintCoincidence.h>
63 #include <SketchPlugin_ConstraintFillet.h>
64 #include <SketchPlugin_ConstraintMirror.h>
65 #include <SketchPlugin_ConstraintAngle.h>
66 #include <SketchPlugin_ConstraintCollinear.h>
67 #include <SketchPlugin_ConstraintMiddle.h>
68 #include <SketchPlugin_MultiRotation.h>
69 #include <SketchPlugin_MultiTranslation.h>
70 #include <SketchPlugin_IntersectionPoint.h>
71
72 #include <SketcherPrs_Tools.h>
73
74 #include <SelectMgr_IndexedMapOfOwner.hxx>
75 #include <StdSelect_BRepOwner.hxx>
76
77 //#include <AIS_DimensionSelectionMode.hxx>
78 #include <AIS_Shape.hxx>
79 #include <AIS_Dimension.hxx>
80
81 #include <ModelAPI_Events.h>
82 #include <ModelAPI_Session.h>
83 #include <ModelAPI_AttributeString.h>
84
85 #include <ModelAPI_Validator.h>
86 #include <ModelAPI_Tools.h>
87
88 #include <QMouseEvent>
89 #include <QApplication>
90 #include <QCursor>
91 #include <QMessageBox>
92 #include <QMainWindow>
93
94 //#define DEBUG_DO_NOT_BY_ENTER
95 //#define DEBUG_SKETCHER_ENTITIES
96 //#define DEBUG_SKETCH_ENTITIES_ON_MOVE
97
98 //#define DEBUG_CURSOR
99
100 /// Fills attribute and result lists by the selected owner. In case if the attribute is found,
101 /// by the owner shape, it is put to the list. Otherwise if type of owner shape is edge, put the function
102 /// result as is to the list of results.
103 /// \param theOwner a viewer selected owner
104 /// \param theFeature a feature, where the attribute is searched
105 /// \param theSketch a current sketch
106 /// \param theSelectedAttribute an output list of attributes
107 /// \param theSelectedResults an output list of edge results
108 void getAttributesOrResults(const Handle(SelectMgr_EntityOwner)& theOwner,
109                             const FeaturePtr& theFeature, const FeaturePtr& theSketch,
110                             const ResultPtr& theResult,
111                             std::set<AttributePtr>& aSelectedAttributes,
112                             std::set<ResultPtr>& aSelectedResults)
113 {
114   Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(theOwner);
115   if (aBRepOwner.IsNull())
116     return;
117   Handle(AIS_InteractiveObject) anIO = Handle(AIS_InteractiveObject)::DownCast(
118                                                                     aBRepOwner->Selectable());
119   if (aBRepOwner->HasShape()) {
120     const TopoDS_Shape& aShape = aBRepOwner->Shape();
121     TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
122     if (aShapeType == TopAbs_VERTEX) {
123       AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature,
124                                                                     aShape, theSketch);
125       if (aPntAttr.get() != NULL)
126         aSelectedAttributes.insert(aPntAttr);
127     }
128     else if (aShapeType == TopAbs_EDGE &&
129              aSelectedResults.find(theResult) == aSelectedResults.end()) {
130       aSelectedResults.insert(theResult);
131     }
132   }
133 }
134
135 PartSet_SketcherMgr::PartSet_SketcherMgr(PartSet_Module* theModule)
136   : QObject(theModule), myModule(theModule), myIsDragging(false), myDragDone(false),
137     myIsMouseOverWindow(false),
138     myIsMouseOverViewProcessed(true), myPreviousUpdateViewerEnabled(true),
139     myIsPopupMenuActive(false)
140 {
141   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
142   ModuleBase_IViewer* aViewer = anIWorkshop->viewer();
143
144   myPreviousDrawModeEnabled = true;//aViewer->isSelectionEnabled();
145
146   connect(aViewer, SIGNAL(mousePress(ModuleBase_IViewWindow*, QMouseEvent*)),
147           this, SLOT(onMousePressed(ModuleBase_IViewWindow*, QMouseEvent*)));
148
149   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)),
150           this, SLOT(onMouseReleased(ModuleBase_IViewWindow*, QMouseEvent*)));
151
152   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
153           this, SLOT(onMouseMoved(ModuleBase_IViewWindow*, QMouseEvent*)));
154
155   connect(aViewer, SIGNAL(mouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)),
156           this, SLOT(onMouseDoubleClick(ModuleBase_IViewWindow*, QMouseEvent*)));
157
158   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
159   XGUI_Workshop* aWorkshop = aConnector->workshop();
160   connect(aWorkshop, SIGNAL(applicationStarted()), this, SLOT(onApplicationStarted()));
161
162   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
163   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
164   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
165 }
166
167 PartSet_SketcherMgr::~PartSet_SketcherMgr()
168 {
169   if (!myPlaneFilter.IsNull())
170     myPlaneFilter.Nullify();
171 }
172
173 void PartSet_SketcherMgr::onEnterViewPort()
174 {
175   // 1. if the mouse over window, update the next flag. Do not perform update visibility of
176   // created feature because it should be done in onMouseMove(). Some widgets watch
177   // the mouse move and use the cursor position to update own values. If the presentaion is
178   // redisplayed before this update, the feature presentation jumps from reset value to current.
179   myIsMouseOverWindow = true;
180
181   #ifdef DEBUG_DO_NOT_BY_ENTER
182   return;
183   #endif
184
185   if (canChangeCursor(getCurrentOperation())) {
186     QCursor* aCurrentCursor = QApplication::overrideCursor();
187     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
188       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
189 #ifdef DEBUG_CURSOR
190       qDebug("onEnterViewPort() : Qt::CrossCursor");
191 #endif
192     }
193   }
194
195   if (!isNestedCreateOperation(getCurrentOperation(), activeSketch()))
196     return;
197
198   operationMgr()->onValidateOperation();
199
200   // we need change displayed state of the current operation feature
201   // if the feature is presentable, e.g. distance construction. It has no results, so workshop does
202   // not accept a signal about the result created. Nothing is shown until mouse is moved out/in view
203   // port. If the isDisplayed flag is true, the presentable feature is displayed as soon as the
204   // presentation becomes valid and redisplay happens
205   //ModuleBase_Operation* aOperation = getCurrentOperation();
206   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
207                                                                            (getCurrentOperation());
208   if (aFOperation) {
209     FeaturePtr aFeature = aFOperation->feature();
210     if (aFeature.get() && aFeature->data()->isValid()) {
211       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature), false);
212     }
213   }
214 }
215
216 void PartSet_SketcherMgr::onLeaveViewPort()
217 {
218   myIsMouseOverViewProcessed = false;
219   myIsMouseOverWindow = false;
220
221   #ifdef DEBUG_DO_NOT_BY_ENTER
222   return;
223   #endif
224
225   if (canChangeCursor(getCurrentOperation())) {
226     QApplication::restoreOverrideCursor();
227 #ifdef DEBUG_CURSOR
228     qDebug("onLeaveViewPort() : None");
229 #endif
230   }
231
232   if (!isNestedCreateOperation(getCurrentOperation(), activeSketch()))
233     return;
234
235   // the method should be performed if the popup menu is called,
236   // the reset of the current widget should not happen
237   if (myIsPopupMenuActive)
238     return;
239
240   // it is important to validate operation here only if sketch entity create operation is active
241   // because at this operation we reacts to the mouse leave/enter view port
242   operationMgr()->onValidateOperation();
243
244   // 2. if the mouse IS NOT over window, reset the active widget value and hide the presentation
245   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
246   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
247   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
248   // disable the viewer update in order to avoid visualization of redisplayed feature in viewer
249   // obtained after reset value
250   bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
251   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
252   if (anActiveWidget)
253     anActiveWidget->reset();
254
255   // hides the presentation of the current operation feature
256   // the feature is to be erased here, but it is correct to call canDisplayObject because
257   // there can be additional check (e.g. editor widget in distance constraint)
258   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
259                                                                            (getCurrentOperation());
260   if (aFOperation) {
261     FeaturePtr aFeature = aFOperation->feature();
262     visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
263   }
264   // we should update viewer after the presentation are hidden in the viewer
265   // otherwise the reset presentation(line) appears in the viewer(by quick move from viewer to PP)
266   aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
267 }
268
269 void PartSet_SketcherMgr::onBeforeValuesChangedInPropertyPanel()
270 {
271   if (!isNestedEditOperation(getCurrentOperation(), myModule->sketchMgr()->activeSketch()) ||
272       myModule->sketchReentranceMgr()->isInternalEditActive())
273     return;
274   // it is necessary to save current selection in order to restore it after the values are modifed
275   storeSelection();
276
277   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
278   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
279   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
280   myPreviousUpdateViewerEnabled = aDisplayer->enableUpdateViewer(false);
281 }
282
283 void PartSet_SketcherMgr::onAfterValuesChangedInPropertyPanel()
284 {
285   if (!isNestedEditOperation(getCurrentOperation(), myModule->sketchMgr()->activeSketch()) ||
286       myModule->sketchReentranceMgr()->isInternalEditActive()) {
287     myModule->sketchReentranceMgr()->updateInternalEditActiveState();
288     return;
289   }
290   // it is necessary to restore current selection in order to restore it after the values are modified
291   restoreSelection();
292   myCurrentSelection.clear();
293
294   // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
295   // viewer happens by deselect/select the modified objects. The flag should be restored after
296   // the selection processing. The update viewer should be also called.
297   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
298   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
299   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
300   aDisplayer->enableUpdateViewer(myPreviousUpdateViewerEnabled);
301   aDisplayer->updateViewer();
302
303
304 }
305
306 void PartSet_SketcherMgr::onMousePressed(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
307 {
308   if (myModule->sketchReentranceMgr()->processMousePressed(theWnd, theEvent))
309     return;
310
311   //get2dPoint(theWnd, theEvent, myClickedPoint);
312
313   if (!(theEvent->buttons() & Qt::LeftButton))
314     return;
315
316   // Clear dragging mode
317   myIsDragging = false;
318
319   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
320   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
321   if (!aViewer->canDragByMouse())
322     return;
323
324   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
325                                                                (getCurrentOperation());
326   if (!aFOperation)
327     return;
328
329   if (aFOperation->isEditOperation()) {
330     // If the current widget is a selector, do nothing, it processes the mouse press
331     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
332     if(anActiveWidget && anActiveWidget->isViewerSelector()) {
333       return;
334     }
335   }
336
337   // Use only for sketch operations
338   if (myCurrentSketch) {
339     if (!PartSet_Tools::sketchPlane(myCurrentSketch))
340       return;
341
342     bool isSketcher = isSketchOperation(aFOperation);
343     bool isSketchOpe = isNestedSketchOperation(aFOperation, activeSketch());
344
345     // Avoid non-sketch operations
346     if ((!isSketchOpe) && (!isSketcher))
347       return;
348
349     bool isEditing = aFOperation->isEditOperation();
350
351     // Ignore creation sketch operation
352     if ((!isSketcher) && (!isEditing))
353       return;
354
355     Handle(AIS_InteractiveContext) aContext = aViewer->AISContext();
356     // Remember highlighted objects for editing
357     ModuleBase_ISelection* aSelect = aWorkshop->selection();
358
359     bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
360     storeSelection(!aHasShift);
361
362     if (myCurrentSelection.empty()) {
363       if (isSketchOpe && (!isSketcher))
364         // commit previous operation
365         if (!aFOperation->commit())
366           aFOperation->abort();
367       return;
368     }
369     // Init flyout point for radius rotation
370     FeaturePtr aFeature = myCurrentSelection.begin().key();
371
372     if (isSketcher) {
373       myIsDragging = true;
374       get2dPoint(theWnd, theEvent, myCurrentPoint);
375       myDragDone = false;
376
377       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
378       // selection should be restored before edit operation start to process the
379       // selected entities, e.g. selection of point(attribute on a line) should edit the point
380       restoreSelection();
381       launchEditing();
382       if (aFeature.get() != NULL) {
383         std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
384                   std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
385       if (aSPFeature.get() && aSPFeature->getKind() == SketchPlugin_ConstraintRadius::ID()) {
386           DataPtr aData = aSPFeature->data();
387           AttributePtr aAttr = aData->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT());
388           std::shared_ptr<GeomDataAPI_Point2D> aFPAttr = 
389             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aAttr);
390           aFPAttr->setValue(myCurrentPoint.myCurX, myCurrentPoint.myCurY);
391         }
392       }
393     } else if (isSketchOpe && isEditing) {
394       // If selected another object commit current result
395       aFOperation->commit();
396
397       myIsDragging = true;
398       get2dPoint(theWnd, theEvent, myCurrentPoint);
399       myDragDone = false;
400
401       myPreviousDrawModeEnabled = aViewer->enableDrawMode(false);
402       // selection should be restored before edit operation start to process the
403       // selected entities, e.g. selection of point(attribute on a line) should edit the point
404       restoreSelection();
405       launchEditing();
406       restoreSelection();
407     }
408   }
409 }
410
411 void PartSet_SketcherMgr::onMouseReleased(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
412 {
413   if (myModule->sketchReentranceMgr()->processMouseReleased(theWnd, theEvent))
414     return;
415
416   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
417   ModuleBase_IViewer* aViewer = aWorkshop->viewer();
418   if (!aViewer->canDragByMouse())
419     return;
420   ModuleBase_Operation* aOp = getCurrentOperation();
421   if (aOp) {
422     if (isNestedSketchOperation(aOp, activeSketch())) {
423       // Only for sketcher operations
424       if (myIsDragging) {
425         if (myDragDone) {
426           myCurrentSelection.clear();
427         }
428       }
429     }
430   }
431
432   aWorkshop->viewer()->enableDrawMode(myPreviousDrawModeEnabled);
433   myIsDragging = false;
434
435   ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
436   PartSet_MouseProcessor* aProcessor = dynamic_cast<PartSet_MouseProcessor*>(anActiveWidget);
437   if (aProcessor)
438     aProcessor->mouseReleased(theWnd, theEvent);
439 }
440
441 void PartSet_SketcherMgr::onMouseMoved(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
442 {
443 #ifdef DEBUG_SKETCH_ENTITIES_ON_MOVE
444   CompositeFeaturePtr aSketch = activeSketch();
445   std::cout << "SKETCH FEATURES (before split) [" << aSketch->numberOfSubs() << "]:" << std::endl;
446   QStringList anInfo;
447   for (int i = 0, aNbSubs = aSketch->numberOfSubs(); i < aNbSubs; i++) {
448     //std::cout << getFeatureInfo(aSketch->subFeature(i), false) << std::endl;
449     anInfo.append(ModuleBase_Tools::objectInfo(aSketch->subFeature(i)));
450   }
451   QString anInfoStr = anInfo.join(";\t");
452   qDebug(QString("onFeatureUpdatedMsg: %1, %2").arg(anInfo.size()).arg(anInfoStr).toStdString().c_str());
453 #endif
454
455   if (myModule->sketchReentranceMgr()->processMouseMoved(theWnd, theEvent))
456     return;
457
458   if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
459     // 1. perform the widget mouse move functionality and display the presentation
460     // the mouse move should be processed in the widget, if it can in order to visualize correct
461     // presentation. These widgets correct the feature attribute according to the mouse position
462     ModuleBase_ModelWidget* anActiveWidget = myModule->activeWidget();
463     PartSet_MouseProcessor* aProcessor = dynamic_cast<PartSet_MouseProcessor*>(anActiveWidget);
464     if (aProcessor)
465       aProcessor->mouseMoved(theWnd, theEvent);
466     if (!myIsMouseOverViewProcessed) {
467       myIsMouseOverViewProcessed = true;
468
469       // the feature is to be erased here, but it is correct to call canDisplayObject because
470       // there can be additional check (e.g. editor widget in distance constraint)
471       ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
472                                                                                (getCurrentOperation());
473       if (aFOperation) {
474         FeaturePtr aFeature = aFOperation->feature();
475         visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
476       }
477     }
478   }
479   //myClickedPoint.clear();
480
481   if (myIsDragging) {
482     // 1. the current selection is saved in the mouse press method in order to restore it after moving
483     // 2. the enable selection in the viewer should be temporary switched off in order to ignore
484     // mouse press signal in the viewer(it call Select for AIS context and the dragged objects are
485     // deselected). This flag should be restored in the slot, processed the mouse release signal.
486
487     ModuleBase_Operation* aCurrentOperation = getCurrentOperation();
488     if (!aCurrentOperation)
489       return;
490     if (isSketchOperation(aCurrentOperation))
491       return; // No edit operation activated
492
493     Handle(V3d_View) aView = theWnd->v3dView();
494     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
495     double aX, aY;
496     PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, aY);
497     double dX =  aX - myCurrentPoint.myCurX;
498     double dY =  aY - myCurrentPoint.myCurY;
499
500     ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
501     XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
502     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
503     // 3. the flag to disable the update viewer should be set in order to avoid blinking in the 
504     // viewer happens by deselect/select the modified objects. The flag should be restored after
505     // the selection processing. The update viewer should be also called.
506     bool isEnableUpdateViewer = aDisplayer->enableUpdateViewer(false);
507
508     static Events_ID aMoveEvent = Events_Loop::eventByName(EVENT_OBJECT_MOVED);
509     //static Events_ID aUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
510     FeatureToSelectionMap::const_iterator anIt = myCurrentSelection.begin(),
511                                           aLast = myCurrentSelection.end();
512     // 4. the features and attributes modification(move)
513     bool isModified = false;
514     for (; anIt != aLast; anIt++) {
515       FeaturePtr aFeature = anIt.key();
516
517       std::set<AttributePtr> anAttributes = anIt.value().first;
518       // Process selection by attribute: the priority to the attribute
519       if (!anAttributes.empty()) {
520         std::set<AttributePtr>::const_iterator anAttIt = anAttributes.begin(),
521                                                anAttLast = anAttributes.end();
522         for (; anAttIt != anAttLast; anAttIt++) {
523           AttributePtr anAttr = *anAttIt;
524           if (anAttr.get() == NULL)
525             continue;
526           std::string aAttrId = anAttr->id();
527           DataPtr aData = aFeature->data();
528           if (aData->isValid()) {
529             std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
530               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aData->attribute(aAttrId));
531             if (aPoint.get() != NULL) {
532               bool isImmutable = aPoint->setImmutable(true);
533               aPoint->move(dX, dY);
534               isModified = true;
535               ModelAPI_EventCreator::get()->sendUpdated(aFeature, aMoveEvent);
536               aPoint->setImmutable(isImmutable);
537             }
538           }
539         }
540       } else {
541         // Process selection by feature
542         std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
543           std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
544         if (aSketchFeature) {
545           aSketchFeature->move(dX, dY);
546           isModified = true;
547           ModelAPI_EventCreator::get()->sendUpdated(aSketchFeature, aMoveEvent);
548         }
549       }
550     }
551     // the modified state of the current operation should be updated if there are features, which
552     // were changed here
553     if (isModified) {
554       aCurrentOperation->onValuesChanged();
555     }
556     Events_Loop::loop()->flush(aMoveEvent); // up all move events - to be processed in the solver
557     //Events_Loop::loop()->flush(aUpdateEvent); // up update events - to redisplay presentations
558
559     // 5. it is necessary to save current selection in order to restore it after the features moving
560     restoreSelection();
561     // 6. restore the update viewer flag and call this update
562     aDisplayer->enableUpdateViewer(isEnableUpdateViewer);
563     aDisplayer->updateViewer();
564
565     myDragDone = true;
566     myCurrentPoint.setValue(aX, aY);
567   }
568 }
569
570 void PartSet_SketcherMgr::onMouseDoubleClick(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
571 {
572   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
573                                                                (getCurrentOperation());
574   if (aFOperation && aFOperation->isEditOperation()) {
575     std::string aId = aFOperation->id().toStdString();
576     if (isDistanceOperation(aFOperation))
577     {
578       // Activate dimension value editing on double click
579       ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
580       QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
581       // Find corresponded widget to activate value editing
582       foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
583         if (aWgt->attributeID() == SketchPlugin_Constraint::VALUE() ||
584             aWgt->attributeID() == SketchPlugin_ConstraintAngle::ANGLE_VALUE_ID()) {
585           PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
586           if (anEditor)
587             anEditor->showPopupEditor();
588           return;
589         }
590       }
591     }
592   }
593 }
594
595 void PartSet_SketcherMgr::onApplicationStarted()
596 {
597   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
598   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
599   XGUI_Workshop* aWorkshop = aConnector->workshop();
600   PartSet_SketcherReetntrantMgr* aReentranceMgr = myModule->sketchReentranceMgr();
601
602   XGUI_PropertyPanel* aPropertyPanel = aWorkshop->propertyPanel();
603   if (aPropertyPanel) {
604     //connect(aPropertyPanel, SIGNAL(beforeWidgetActivated(ModuleBase_ModelWidget*)),
605     //        this, SLOT(onBeforeWidgetActivated(ModuleBase_ModelWidget*)));
606
607     connect(aPropertyPanel, SIGNAL(noMoreWidgets(const std::string&)),
608             aReentranceMgr, SLOT(onNoMoreWidgets(const std::string&)));
609     connect(aPropertyPanel, SIGNAL(widgetActivated(ModuleBase_ModelWidget*)),
610             aReentranceMgr, SLOT(onWidgetActivated()));
611   }
612
613   XGUI_ViewerProxy* aViewerProxy = aWorkshop->viewer();
614   connect(aViewerProxy, SIGNAL(enterViewPort()), this, SLOT(onEnterViewPort()));
615   connect(aViewerProxy, SIGNAL(leaveViewPort()), this, SLOT(onLeaveViewPort()));
616
617   XGUI_ContextMenuMgr* aContextMenuMgr = aWorkshop->contextMenuMgr();
618   connect(aContextMenuMgr, SIGNAL(beforeContextMenu()), this, SLOT(onBeforeContextMenu()));
619   connect(aContextMenuMgr, SIGNAL(afterContextMenu()), this, SLOT(onAfterContextMenu()));
620 }
621
622 //void PartSet_SketcherMgr::onBeforeWidgetActivated(ModuleBase_ModelWidget* theWidget)
623 //{
624   //if (!myClickedPoint.myIsInitialized)
625   //  return;
626
627   //ModuleBase_Operation* aOperation = getCurrentOperation();
628   // the distance constraint feature should not use the clickedd point
629   // this is workaround in order to don't throw down the flyout point value,
630   // set by execute() method of these type of features
631   //if (isDistanceOperation(aOperation))
632   //  return;
633
634   //PartSet_WidgetPoint2D* aPnt2dWgt = dynamic_cast<PartSet_WidgetPoint2D*>(theWidget);
635   //if (aPnt2dWgt) {
636   //  aPnt2dWgt->setPoint(myClickedPoint.myCurX, myClickedPoint.myCurY);
637   //}
638 //}
639
640 void PartSet_SketcherMgr::onBeforeContextMenu()
641 {
642   myIsPopupMenuActive = true;
643 }
644
645 void PartSet_SketcherMgr::onAfterContextMenu()
646 {
647   myIsPopupMenuActive = false;
648 }
649
650 void PartSet_SketcherMgr::get2dPoint(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent, 
651                                      Point& thePoint)
652 {
653   Handle(V3d_View) aView = theWnd->v3dView();
654   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), aView);
655   double aX, anY;
656   PartSet_Tools::convertTo2D(aPoint, myCurrentSketch, aView, aX, anY);
657   thePoint.setValue(aX, anY);
658 }
659
660 void PartSet_SketcherMgr::launchEditing()
661 {
662   if (!myCurrentSelection.empty()) {
663     FeaturePtr aFeature = myCurrentSelection.begin().key();
664     std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
665               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
666     if (aSPFeature && (!aSPFeature->isExternal())) {
667       myModule->editFeature(aSPFeature);
668     }
669   }
670 }
671
672 bool PartSet_SketcherMgr::sketchSolverError()
673 {
674   bool anError = false;
675   CompositeFeaturePtr aSketch = activeSketch();
676   if (aSketch.get()) {
677     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
678     anError = !aAttributeString->value().empty();
679   }
680   return anError;
681 }
682
683 QString PartSet_SketcherMgr::getFeatureError(const FeaturePtr& theFeature)
684 {
685   std::string anError = "";
686   if (!theFeature.get() || !theFeature->data()->isValid())
687     return anError.c_str();
688
689   CompositeFeaturePtr aSketch = activeSketch();
690   if (aSketch.get() && aSketch == theFeature) {
691     AttributeStringPtr aAttributeString = aSketch->string(SketchPlugin_Sketch::SOLVER_ERROR());
692     anError = aAttributeString->value();
693     ModuleBase_Tools::translate(aSketch->getKind(), anError);
694   }
695   return anError.c_str();
696 }
697
698 void PartSet_SketcherMgr::clearClickedFlags()
699 {
700   //myClickedPoint.clear();
701   myCurrentPoint.clear();
702 }
703
704 const QStringList& PartSet_SketcherMgr::replicationsIdList()
705 {
706   static QStringList aReplicationIds;
707   if (aReplicationIds.size() == 0) {
708     aReplicationIds << SketchPlugin_ConstraintMirror::ID().c_str();
709     aReplicationIds << SketchPlugin_MultiRotation::ID().c_str();
710     aReplicationIds << SketchPlugin_MultiTranslation::ID().c_str();
711   }
712   return aReplicationIds;
713 }
714
715 const QStringList& PartSet_SketcherMgr::constraintsIdList()
716 {
717   static QStringList aConstraintIds;
718   if (aConstraintIds.size() == 0) {
719     aConstraintIds << SketchPlugin_ConstraintLength::ID().c_str();
720     aConstraintIds << SketchPlugin_ConstraintDistance::ID().c_str();
721     aConstraintIds << SketchPlugin_ConstraintRigid::ID().c_str();
722     aConstraintIds << SketchPlugin_ConstraintRadius::ID().c_str();
723     aConstraintIds << SketchPlugin_ConstraintPerpendicular::ID().c_str();
724     aConstraintIds << SketchPlugin_ConstraintParallel::ID().c_str();
725     aConstraintIds << SketchPlugin_ConstraintHorizontal::ID().c_str();
726     aConstraintIds << SketchPlugin_ConstraintVertical::ID().c_str();
727     aConstraintIds << SketchPlugin_ConstraintEqual::ID().c_str();
728     aConstraintIds << SketchPlugin_ConstraintTangent::ID().c_str();
729     aConstraintIds << SketchPlugin_ConstraintCoincidence::ID().c_str();
730     aConstraintIds << SketchPlugin_ConstraintAngle::ID().c_str();
731     aConstraintIds << SketchPlugin_ConstraintCollinear::ID().c_str();
732     aConstraintIds << SketchPlugin_ConstraintMiddle::ID().c_str();
733   }
734   return aConstraintIds;
735 }
736
737 void PartSet_SketcherMgr::sketchSelectionModes(QIntList& theModes)
738 {
739   theModes.clear();
740
741   theModes.append(SketcherPrs_Tools::Sel_Dimension_Text);
742   theModes.append(SketcherPrs_Tools::Sel_Dimension_Line);
743   theModes.append(SketcherPrs_Tools::Sel_Constraint);
744   theModes.append(TopAbs_VERTEX);
745   theModes.append(TopAbs_EDGE);
746 }
747
748 Handle(AIS_InteractiveObject) PartSet_SketcherMgr::createPresentation(const ResultPtr& theResult)
749 {
750   Handle(AIS_InteractiveObject) aPrs;
751
752   FeaturePtr aFeature = ModelAPI_Feature::feature(theResult);
753   if (aFeature.get() && aFeature->getKind() == SketchPlugin_Sketch::ID()) {
754     aPrs = new PartSet_ResultSketchPrs(theResult);
755   }
756   return aPrs;
757 }
758
759 bool PartSet_SketcherMgr::isSketchOperation(ModuleBase_Operation* theOperation)
760 {
761   return theOperation && theOperation->id().toStdString() == SketchPlugin_Sketch::ID();
762 }
763
764 bool PartSet_SketcherMgr::isNestedSketchOperation(ModuleBase_Operation* theOperation,
765                                                   const CompositeFeaturePtr& theSketch)
766 {
767   bool aNestedSketch = false;
768
769   if (theOperation && theSketch.get()) {
770     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
771                                                                  (theOperation);
772     if (aFOperation) {
773       FeaturePtr aFeature = aFOperation->feature();
774       aNestedSketch = theSketch->isSub(aFeature);
775     }
776   }
777   return aNestedSketch;
778 }
779
780 bool PartSet_SketcherMgr::isNestedCreateOperation(ModuleBase_Operation* theOperation,
781                                                   const CompositeFeaturePtr& theSketch)
782 {
783   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
784                                                                (theOperation);
785   return aFOperation && !aFOperation->isEditOperation() &&
786          isNestedSketchOperation(aFOperation, theSketch);
787 }
788
789 bool PartSet_SketcherMgr::isNestedEditOperation(ModuleBase_Operation* theOperation,
790                                                 const CompositeFeaturePtr& theSketch)
791 {
792   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
793                                                                (theOperation);
794   return aFOperation && aFOperation->isEditOperation() &&
795     isNestedSketchOperation(aFOperation, theSketch);
796 }
797
798 bool PartSet_SketcherMgr::isEntity(const std::string& theId)
799 {
800   return (theId == SketchPlugin_Line::ID()) ||
801          (theId == SketchPlugin_Point::ID()) ||
802          (theId == SketchPlugin_Arc::ID()) ||
803          (theId == SketchPlugin_Circle::ID());
804 }
805
806 bool PartSet_SketcherMgr::isDistanceOperation(ModuleBase_Operation* theOperation)
807 {
808   std::string anId = theOperation ? theOperation->id().toStdString() : "";
809
810   return isDistanceKind(anId);
811 }
812
813 bool PartSet_SketcherMgr::isDistanceKind(std::string& theKind)
814 {
815   return (theKind == SketchPlugin_ConstraintLength::ID()) ||
816          (theKind == SketchPlugin_ConstraintDistance::ID()) ||
817          (theKind == SketchPlugin_ConstraintRadius::ID()) ||
818          (theKind == SketchPlugin_ConstraintAngle::ID());
819 }
820
821 void PartSet_SketcherMgr::startSketch(ModuleBase_Operation* theOperation)
822 {
823   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
824                                                                (getCurrentOperation());
825   if (!aFOperation)
826     return;
827
828   myModule->onViewTransformed();
829
830   // Display all sketcher sub-Objects
831   myCurrentSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFOperation->feature());
832   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
833
834   // Hide sketcher result
835   std::list<ResultPtr> aResults = myCurrentSketch->results();
836   std::list<ResultPtr>::const_iterator aIt;
837   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
838     (*aIt)->setDisplayed(false);
839   }
840   myCurrentSketch->setDisplayed(false);
841
842   // Remove invalid sketch entities
843   std::set<FeaturePtr> anInvalidFeatures;
844   ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
845   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
846     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
847     if (aFeature.get()) {
848       if (!aFactory->validate(aFeature))
849         anInvalidFeatures.insert(aFeature);
850     }
851   }
852   if (!anInvalidFeatures.empty()) {
853     std::map<FeaturePtr, std::set<FeaturePtr> > aReferences;
854     ModelAPI_Tools::findAllReferences(anInvalidFeatures, aReferences, false);
855
856     std::set<FeaturePtr>::const_iterator anIt = anInvalidFeatures.begin(),
857                                          aLast = anInvalidFeatures.end();
858     // separate features to references to parameter features and references to others
859     QStringList anInvalidFeatureNames;
860     for (; anIt != aLast; anIt++) {
861       FeaturePtr aFeature = *anIt;
862       if (aFeature.get())
863         anInvalidFeatureNames.append(aFeature->name().c_str());
864     }
865     std::string aPrefixInfo = QString("Invalid features of the sketch will be deleted: %1.\n\n").
866                                   arg(anInvalidFeatureNames.join(", ")).toStdString().c_str();
867     std::set<FeaturePtr> aFeatureRefsToDelete;
868     if (ModuleBase_Tools::askToDelete(anInvalidFeatures, aReferences, aConnector->desktop(),
869                                       aFeatureRefsToDelete, aPrefixInfo)) {
870       if (!aFeatureRefsToDelete.empty())
871         anInvalidFeatures.insert(aFeatureRefsToDelete.begin(), aFeatureRefsToDelete.end());
872       ModelAPI_Tools::removeFeatures(anInvalidFeatures, true);
873       Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
874       // TODO: call the next method in the XGUI_OperationMgr::onOperationStarted().
875       workshop()->errorMgr()->updateAcceptAllAction(myCurrentSketch);
876     }
877   }
878
879   // Display sketcher objects
880   QStringList anInfo;
881   for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
882     FeaturePtr aFeature = myCurrentSketch->subFeature(i);
883 #ifdef DEBUG_SKETCHER_ENTITIES
884     anInfo.append(ModuleBase_Tools::objectInfo(aFeature));
885 #endif
886     std::list<ResultPtr> aResults = aFeature->results();
887     std::list<ResultPtr>::const_iterator aIt;
888     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
889       (*aIt)->setDisplayed(true);
890     }
891     aFeature->setDisplayed(true);
892   }
893 #ifdef DEBUG_SKETCHER_ENTITIES
894   QString anInfoStr = anInfo.join(";\t");
895   qDebug(QString("startSketch: %1, %2").arg(anInfo.size()).arg(anInfoStr).toStdString().c_str());
896 #endif
897
898   if(myCirclePointFilter.IsNull()) {
899     myCirclePointFilter = new PartSet_CirclePointFilter(myModule->workshop());
900   }
901
902   myModule->workshop()->viewer()->addSelectionFilter(myCirclePointFilter);
903
904   if (myPlaneFilter.IsNull()) 
905     myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
906
907   myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
908   bool aHasPlane = false;
909   std::shared_ptr<GeomAPI_Pln> aPln;
910   aPln = PartSet_Tools::sketchPlane(myCurrentSketch);
911   myPlaneFilter->setPlane(aPln);
912
913   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
914   // all displayed objects should be activated in current selection modes according to switched
915   // plane filter
916   if (aPln.get())
917     aConnector->activateModuleSelectionModes();
918 }
919
920 void PartSet_SketcherMgr::stopSketch(ModuleBase_Operation* theOperation)
921 {
922   myIsMouseOverWindow = false;
923   myIsConstraintsShown[PartSet_Tools::Geometrical] = true;
924   myIsConstraintsShown[PartSet_Tools::Dimensional] = true;
925   myIsConstraintsShown[PartSet_Tools::Expressions] = false;
926
927   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(myModule->workshop());
928
929   DataPtr aData = myCurrentSketch->data();
930   if (!aData->isValid()) {
931     XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
932     // The sketch was aborted
933     myCurrentSketch = CompositeFeaturePtr();
934     // TODO: move this outside of if-else
935     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
936     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
937
938     // Erase all sketcher objects
939     QObjectPtrList aObjects = aDisplayer->displayedObjects();
940     foreach (ObjectPtr aObj, aObjects) {
941       DataPtr aObjData = aObj->data();
942       if (!aObjData->isValid())
943         aObj->setDisplayed(false);
944     }
945   }
946   else {
947     // Hide all sketcher sub-Objects
948     for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
949       FeaturePtr aFeature = myCurrentSketch->subFeature(i);
950       std::list<ResultPtr> aResults = aFeature->results();
951       std::list<ResultPtr>::const_iterator aIt;
952       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
953         (*aIt)->setDisplayed(false);
954       }
955       aFeature->setDisplayed(false);
956     }
957     // Display sketcher result
958     std::list<ResultPtr> aResults = myCurrentSketch->results();
959     std::list<ResultPtr>::const_iterator aIt;
960     Events_Loop* aLoop = Events_Loop::loop();
961     static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
962
963     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
964                                                                            (theOperation);
965     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
966       if (!aFOperation->isDisplayedOnStart(*aIt)) {
967         (*aIt)->setDisplayed(true);
968         // this display event is needed because sketch already may have "displayed" state,
969         // but not displayed while it is still active (issue 613, abort of existing sketch)
970         ModelAPI_EventCreator::get()->sendUpdated(*aIt, aDispEvent);
971       }
972     }
973     if (!aFOperation->isDisplayedOnStart(myCurrentSketch))
974       myCurrentSketch->setDisplayed(true);
975     
976     myCurrentSketch = CompositeFeaturePtr();
977
978     myModule->workshop()->viewer()->removeSelectionFilter(myCirclePointFilter);
979     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
980
981     Events_Loop::loop()->flush(aDispEvent);
982   }
983   // restore the module selection modes, which were changed on startSketch
984   aConnector->activateModuleSelectionModes();
985 }
986
987 void PartSet_SketcherMgr::startNestedSketch(ModuleBase_Operation* theOperation)
988 {
989   if (canChangeCursor(theOperation) && myIsMouseOverWindow) {
990     QCursor* aCurrentCursor = QApplication::overrideCursor();
991     if (!aCurrentCursor || aCurrentCursor->shape() != Qt::CrossCursor) {
992       QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
993 #ifdef DEBUG_CURSOR
994       qDebug("startNestedSketch() : Qt::CrossCursor");
995 #endif
996     }
997   }
998 }
999
1000 void PartSet_SketcherMgr::stopNestedSketch(ModuleBase_Operation* theOperation)
1001 {
1002   myIsMouseOverViewProcessed = true;
1003   operationMgr()->onValidateOperation();
1004   if (canChangeCursor(theOperation)) {
1005     QApplication::restoreOverrideCursor();
1006 #ifdef DEBUG_CURSOR
1007     qDebug("stopNestedSketch() : None");
1008 #endif
1009   }
1010   /// improvement to deselect automatically all eventual selected objects, when
1011   // returning to the neutral point of the Sketcher
1012   // if the operation is restarted, the previous selection is used to initialize started operation
1013   if (!myModule->sketchReentranceMgr()->isInternalEditStarted())
1014     workshop()->selector()->clearSelection();
1015 }
1016
1017 void PartSet_SketcherMgr::commitNestedSketch(ModuleBase_Operation* theOperation)
1018 {
1019   if (isNestedCreateOperation(theOperation, activeSketch())) {
1020     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1021                                                                              (theOperation);
1022     if (aFOperation) {
1023       FeaturePtr aFeature = aFOperation->feature();
1024       // it is necessary to check the the feature data validity because
1025       // some kind of features are removed by an operation commit(the macro state of a feature)
1026       if (aFeature.get() && aFeature->data()->isValid()) {
1027         visualizeFeature(aFeature, aFOperation->isEditOperation(), true);
1028       }
1029     }
1030   }
1031 }
1032
1033 void PartSet_SketcherMgr::activatePlaneFilter(const bool& toActivate)
1034 {
1035   if (toActivate)
1036     myModule->workshop()->viewer()->addSelectionFilter(myPlaneFilter);
1037   else
1038     myModule->workshop()->viewer()->removeSelectionFilter(myPlaneFilter);
1039 }
1040
1041 bool PartSet_SketcherMgr::operationActivatedByPreselection()
1042 {
1043   bool isOperationStopped = false;
1044   ModuleBase_Operation* anOperation = getCurrentOperation();
1045   if(anOperation && PartSet_SketcherMgr::isNestedSketchOperation(anOperation, activeSketch())) {
1046     // Set final definitions if they are necessary
1047     //propertyPanelDefined(aOperation);
1048     /// Commit sketcher operations automatically
1049     /// distance operation are able to show popup editor to modify the distance value
1050     /// after entering the value, the operation should be committed/aborted(by Esc key)
1051     bool aCanCommitOperation = true;
1052     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1053                                                                             (anOperation);
1054     if (aFOperation && PartSet_SketcherMgr::isDistanceOperation(aFOperation)) {
1055       bool aValueAccepted = setDistanceValueByPreselection(anOperation, myModule->workshop(),
1056                                                            aCanCommitOperation);
1057       if (!aValueAccepted)
1058         return isOperationStopped;
1059     }
1060
1061     if (aCanCommitOperation)
1062       isOperationStopped = anOperation->commit();
1063     else {
1064       anOperation->abort();
1065       isOperationStopped = true;
1066     }
1067   }
1068   return isOperationStopped;
1069 }
1070
1071 bool PartSet_SketcherMgr::canUndo() const
1072 {
1073   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1074 }
1075
1076 bool PartSet_SketcherMgr::canRedo() const
1077 {
1078   return isNestedCreateOperation(getCurrentOperation(), activeSketch());
1079 }
1080
1081 bool PartSet_SketcherMgr::canEraseObject(const ObjectPtr& theObject) const
1082 {
1083   bool aCanErase = true;
1084   // when the sketch operation is active, results of sketch sub-feature can not be hidden
1085   if (myCurrentSketch.get()) {
1086     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1087     if (aResult.get()) {
1088       // Display sketcher objects
1089       for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1090
1091         FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1092         std::list<ResultPtr> aResults = aFeature->results();
1093         std::list<ResultPtr>::const_iterator anIt;
1094         for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1095           aCanErase = *anIt != aResult;
1096         }
1097       }
1098     }
1099   }
1100   return aCanErase;
1101 }
1102
1103 bool PartSet_SketcherMgr::canDisplayObject(const ObjectPtr& theObject) const
1104 {
1105   bool aCanDisplay = true;
1106
1107   bool aHasActiveSketch = activeSketch().get() != NULL;
1108   if (aHasActiveSketch) {
1109     // 1. the sketch feature should not be displayed during the sketch active operation
1110     // it is hidden by a sketch operation start and shown by a sketch stop, just the sketch 
1111     // nested features can be visualized
1112     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1113     if (aFeature.get() != NULL && aFeature == activeSketch()) {
1114       aCanDisplay = false;
1115     }
1116     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1117                             std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1118     /// some sketch entities should be never shown, e.g. projection feature
1119     if (aSketchFeature.get())
1120       aCanDisplay = aSketchFeature->canBeDisplayed();
1121   }
1122   else { // there are no an active sketch
1123     // 2. sketch sub-features should not be visualized if the sketch operation is not active
1124     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1125     if (aFeature.get() != NULL) {
1126       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
1127                               std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
1128       if (aSketchFeature.get()) {
1129         aCanDisplay = false;
1130       }
1131     }
1132   }
1133
1134   // 3. the method should not filter the objects, which are not related to the current operation.
1135   // The object is filtered just if it is a current operation feature or this feature result
1136   if (aCanDisplay) {
1137     bool isObjectFound = false;
1138     ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1139                                                                  (getCurrentOperation());
1140     if (aFOperation) {
1141       FeaturePtr aFeature = aFOperation->feature();
1142       if (aFeature.get()) {
1143         std::list<ResultPtr> aResults = aFeature->results();
1144         if (theObject == aFeature)
1145           isObjectFound = true;
1146         else {
1147           std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1148           for (; anIt != aLast && !isObjectFound; anIt++) {
1149             isObjectFound = *anIt == theObject;
1150           }
1151         }
1152       }
1153     }
1154     if (isObjectFound) {
1155       // 4. For created nested feature operation do not display the created feature if
1156       // the mouse curstor leaves the OCC window.
1157       // The correction cases, which ignores this condition:
1158       // a. the property panel values modification
1159       // b. the popup menu activated
1160       // c. widget editor control
1161       #ifndef DEBUG_DO_NOT_BY_ENTER
1162       if (isNestedCreateOperation(getCurrentOperation(), activeSketch())) {
1163         ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1164         ModuleBase_WidgetEditor* anEditorWdg = anActiveWidget ? dynamic_cast<ModuleBase_WidgetEditor*>(anActiveWidget) : 0;
1165         // the active widget editor should not influence here. The presentation should be visible always
1166         // when this widget is active.
1167         if (!anEditorWdg && !myIsPopupMenuActive) {
1168           // during a nested create operation, the feature is redisplayed only if the mouse over view
1169           // of there was a value modified in the property panel after the mouse left the view
1170           aCanDisplay = canDisplayCurrentCreatedFeature();
1171         }
1172       }
1173       #endif
1174     }
1175   }
1176
1177   // checks the sketcher constraints visibility according to active sketch check box states
1178   if (aCanDisplay) {
1179     bool aProcessed = false;
1180     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1181     if (aFeature.get()) {
1182       bool aConstraintDisplayed = canDisplayConstraint(aFeature, PartSet_Tools::Any, aProcessed);
1183       if (aProcessed)
1184         aCanDisplay = aConstraintDisplayed;
1185     }
1186   }
1187
1188   return aCanDisplay;
1189 }
1190
1191 bool PartSet_SketcherMgr::canDisplayConstraint(const FeaturePtr& theFeature,
1192                                              const PartSet_Tools::ConstraintVisibleState& theState,
1193                                              bool& isProcessed) const
1194 {
1195   bool aSwitchedOn = true;
1196
1197   const QStringList& aConstrIds = constraintsIdList();
1198
1199   std::string aKind = theFeature->getKind();
1200   if (aConstrIds.contains(QString(aKind.c_str()))) {
1201     bool isTypedConstraint = false;
1202
1203     switch (theState) {
1204       case PartSet_Tools::Dimensional: {
1205         bool isDistance = isDistanceKind(aKind);
1206         if (isDistance) {
1207           isProcessed = true;
1208           aSwitchedOn = myIsConstraintsShown[theState];
1209         }
1210       }
1211       break;
1212       case PartSet_Tools::Geometrical: {
1213         bool isGeometrical = !isDistanceKind(aKind);
1214         if (isGeometrical) {
1215           isProcessed = true;
1216           aSwitchedOn = myIsConstraintsShown[theState];
1217         }
1218       }
1219       break;
1220       case PartSet_Tools::Any: {
1221         isProcessed = true;
1222         bool isDistance = isDistanceKind(aKind);
1223         if (isDistance)
1224           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Dimensional];
1225         else
1226           aSwitchedOn = myIsConstraintsShown[PartSet_Tools::Geometrical];
1227       }
1228       break;
1229     default:
1230       break;
1231     }
1232   }
1233   return aSwitchedOn;
1234 }
1235
1236 /*void PartSet_SketcherMgr::processHiddenObject(const std::list<ObjectPtr>& theObjects)
1237 {
1238   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1239                                                                            (getCurrentOperation());
1240   if (aFOperation && myCurrentSketch.get()) {
1241     // find results of the current operation
1242     // these results should not be proposed to be deleted
1243     FeaturePtr anOperationFeature = aFOperation->feature();
1244     std::list<ResultPtr> anOperationResultList = anOperationFeature->results();
1245     std::set<ResultPtr> anOperationResults;
1246     std::list<ResultPtr>::const_iterator aRIt = anOperationResultList.begin(),
1247                                         aRLast = anOperationResultList.end();
1248     for (; aRIt != aRLast; aRIt++)
1249       anOperationResults.insert(*aRIt);
1250
1251     std::set<FeaturePtr> anObjectsToBeDeleted;
1252     QStringList anObjectsToBeDeletedNames;
1253     std::list<ObjectPtr>::const_iterator anIt = theObjects.begin(), aLast = theObjects.end();
1254     for (; anIt != aLast; anIt++) {
1255       ObjectPtr anObject = *anIt;
1256       bool aCanErase = true;
1257       // when the sketch operation is active, results of sketch sub-feature can not be hidden
1258       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1259       // the result is found between current feature results
1260       if (anOperationResults.find(aResult) != anOperationResults.end())
1261         continue;
1262
1263       if (aResult.get()) {
1264         // Display sketcher objects
1265         for (int i = 0; i < myCurrentSketch->numberOfSubs() && aCanErase; i++) {
1266           FeaturePtr aFeature = myCurrentSketch->subFeature(i);
1267           std::list<ResultPtr> aResults = aFeature->results();
1268           std::list<ResultPtr>::const_iterator anIt;
1269           for (anIt = aResults.begin(); anIt != aResults.end() && aCanErase; ++anIt) {
1270             aCanErase = *anIt != aResult;
1271           }
1272         }
1273       }
1274       if (!aCanErase) {
1275         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
1276         if (aFeature.get() && anObjectsToBeDeleted.find(aFeature) == anObjectsToBeDeleted.end()) {
1277           anObjectsToBeDeleted.insert(aFeature);
1278           anObjectsToBeDeletedNames.append(aFeature->name().c_str());
1279         }
1280       }
1281     }
1282     if (!anObjectsToBeDeleted.empty()) {
1283       QString aFeatureNames = anObjectsToBeDeletedNames.join(", ");
1284       QString aMessage = tr("The following features have incorrect presentation and \
1285 will be hidden: %1. Would you like to delete them?")
1286                          .arg(aFeatureNames);
1287       int anAnswer = QMessageBox::question(qApp->activeWindow(), tr("Features hide"),
1288                                            aMessage, QMessageBox::Ok | QMessageBox::Cancel,
1289                                            QMessageBox::Cancel);
1290       if (anAnswer == QMessageBox::Ok) {
1291         QObjectPtrList anObjects;
1292         std::set<FeaturePtr>::const_iterator anIt = anObjectsToBeDeleted.begin(),
1293                                              aLast = anObjectsToBeDeleted.end();
1294         for (; anIt != aLast; anIt++)
1295           anObjects.append(*anIt);
1296         SessionPtr aMgr = ModelAPI_Session::get();
1297         DocumentPtr aDoc = aMgr->activeDocument();
1298         bool aIsOp = aMgr->isOperation();
1299         if (!aIsOp)
1300           aMgr->startOperation();
1301         workshop()->deleteFeatures(anObjects);
1302         //static Events_ID aDeletedEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
1303         //static Events_ID aRedispEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
1304         //Events_Loop::loop()->flush(aDeletedEvent);
1305         //Events_Loop::loop()->flush(aRedispEvent);
1306
1307         if (!aIsOp)
1308           aMgr->finishOperation();
1309       }
1310     }
1311   }
1312 }*/
1313
1314 bool PartSet_SketcherMgr::canDisplayCurrentCreatedFeature() const
1315 {
1316   bool aCanDisplay = myIsMouseOverWindow;
1317   if (!aCanDisplay) {
1318     ModuleBase_ModelWidget* anActiveWidget = getActiveWidget();
1319     if (anActiveWidget)
1320       aCanDisplay = anActiveWidget->getValueState() == ModuleBase_ModelWidget::Stored;
1321   }
1322   return aCanDisplay;
1323 }
1324
1325 bool PartSet_SketcherMgr::canChangeCursor(ModuleBase_Operation* theOperation) const
1326 {
1327   return isNestedCreateOperation(theOperation, activeSketch()) ||
1328          myModule->sketchReentranceMgr()->isInternalEditActive();
1329 }
1330
1331 const QMap<PartSet_Tools::ConstraintVisibleState, bool>& PartSet_SketcherMgr::showConstraintStates()
1332 {
1333   return myIsConstraintsShown;
1334 }
1335
1336 bool PartSet_SketcherMgr::isObjectOfSketch(const ObjectPtr& theObject) const
1337 {
1338   bool isFoundObject = false;
1339
1340   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
1341   if (anObjectFeature.get()) {
1342     int aSize = myCurrentSketch->numberOfSubs();
1343     for (int i = 0; i < myCurrentSketch->numberOfSubs() && !isFoundObject; i++) {
1344       FeaturePtr aCurrentFeature = myCurrentSketch->subFeature(i);
1345       isFoundObject = myCurrentSketch->subFeature(i) == anObjectFeature;
1346     }
1347   }
1348   return isFoundObject;
1349 }
1350
1351 void PartSet_SketcherMgr::onPlaneSelected(const std::shared_ptr<GeomAPI_Pln>& thePln)
1352 {
1353   if (myPlaneFilter.IsNull()) 
1354    myPlaneFilter = new ModuleBase_ShapeInPlaneFilter();
1355
1356   myPlaneFilter->setPlane(thePln);
1357 }
1358
1359 bool PartSet_SketcherMgr::setDistanceValueByPreselection(ModuleBase_Operation* theOperation,
1360                                                          ModuleBase_IWorkshop* theWorkshop,
1361                                                          bool& theCanCommitOperation)
1362 {
1363   bool isValueAccepted = false;
1364   theCanCommitOperation = false;
1365
1366   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1367                                                                               (theOperation);
1368   FeaturePtr aFeature = aFOperation->feature();
1369   // editor is shown only if all attribute references are filled by preseletion
1370   bool anAllRefAttrInitialized = true;
1371
1372   std::list<AttributePtr> aRefAttrs = aFeature->data()->attributes(
1373                                               ModelAPI_AttributeRefAttr::typeId());
1374   std::list<AttributePtr>::const_iterator anIt = aRefAttrs.begin(), aLast = aRefAttrs.end();
1375   for (; anIt != aLast && anAllRefAttrInitialized; anIt++) {
1376     anAllRefAttrInitialized = (*anIt)->isInitialized();
1377   }
1378   if (anAllRefAttrInitialized) {
1379     // Activate dimension value editing on double click
1380     ModuleBase_IPropertyPanel* aPanel = aFOperation->propertyPanel();
1381     QList<ModuleBase_ModelWidget*> aWidgets = aPanel->modelWidgets();
1382     // Find corresponded widget to activate value editing
1383     foreach (ModuleBase_ModelWidget* aWgt, aWidgets) {
1384       if (aWgt->attributeID() == "ConstraintValue") {
1385         // the featue should be displayed in order to find the AIS text position,
1386         // the place where the editor will be shown
1387         aFeature->setDisplayed(true);
1388         /// the execute is necessary to perform in the feature compute for flyout position
1389         aFeature->execute();
1390
1391         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
1392         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1393
1394         PartSet_WidgetEditor* anEditor = dynamic_cast<PartSet_WidgetEditor*>(aWgt);
1395         if (anEditor) {
1396           int aX = 0, anY = 0;
1397
1398           XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(theWorkshop);
1399           XGUI_Displayer* aDisplayer = aWorkshop->displayer();
1400           AISObjectPtr anAIS = aDisplayer->getAISObject(aFeature);
1401           Handle(AIS_InteractiveObject) anAISIO;
1402           if (anAIS.get() != NULL) {
1403             anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1404           }
1405           if (anAIS.get() != NULL) {
1406             Handle(AIS_InteractiveObject) anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1407
1408             if (!anAISIO.IsNull()) {
1409               Handle(AIS_Dimension) aDim = Handle(AIS_Dimension)::DownCast(anAISIO);
1410               if (!aDim.IsNull()) {
1411                 gp_Pnt aPosition = aDim->GetTextPosition();
1412
1413                 ModuleBase_IViewer* aViewer = aWorkshop->viewer();
1414                 Handle(V3d_View) aView = aViewer->activeView();
1415                 int aCX, aCY;
1416                 aView->Convert(aPosition.X(), aPosition.Y(), aPosition.Z(), aCX, aCY);
1417
1418                 QWidget* aViewPort = aViewer->activeViewPort();
1419                 QPoint aGlPoint = aViewPort->mapToGlobal(QPoint(aCX, aCY));
1420                 aX = aGlPoint.x();
1421                 anY = aGlPoint.y();
1422               }
1423             }
1424             anEditor->setCursorPosition(aX, anY);
1425             isValueAccepted = anEditor->showPopupEditor(false);
1426             theCanCommitOperation = true;
1427           }
1428         }
1429       }
1430     }
1431   }
1432   return isValueAccepted;
1433 }
1434
1435 void PartSet_SketcherMgr::getSelectionOwners(const FeaturePtr& theFeature,
1436                                              const FeaturePtr& theSketch,
1437                                              ModuleBase_IWorkshop* theWorkshop,
1438                                              const FeatureToSelectionMap& theSelection,
1439                                              SelectMgr_IndexedMapOfOwner& theOwnersToSelect)
1440 {
1441   if (theFeature.get() == NULL)
1442     return;
1443
1444   FeatureToSelectionMap::const_iterator anIt = theSelection.find(theFeature);
1445   std::set<AttributePtr> aSelectedAttributes = anIt.value().first;
1446   std::set<ResultPtr> aSelectedResults = anIt.value().second;
1447
1448   ModuleBase_IViewer* aViewer = theWorkshop->viewer();
1449
1450   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
1451   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
1452
1453   // 1. found the feature's owners. Check the AIS objects of the constructions
1454   AISObjectPtr aAISObj = aDisplayer->getAISObject(theFeature);
1455   if (aAISObj.get() != NULL && aSelectedAttributes.empty() && aSelectedResults.empty()) {
1456     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1457
1458     SelectMgr_IndexedMapOfOwner aSelectedOwners;
1459     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1460     for  (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
1461       Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
1462       if (!anOwner.IsNull())
1463         theOwnersToSelect.Add(anOwner);
1464     }
1465   }
1466
1467   // 2. found the feature results's owners
1468   std::list<ResultPtr> aResults = theFeature->results();
1469   std::list<ResultPtr>::const_iterator aIt;
1470   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt)
1471   {
1472     ResultPtr aResult = *aIt;
1473     AISObjectPtr aAISObj = aDisplayer->getAISObject(aResult);
1474     if (aAISObj.get() == NULL)
1475       continue; 
1476     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1477
1478     SelectMgr_IndexedMapOfOwner aSelectedOwners;  
1479     aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
1480     for  ( Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++ ) {
1481       Handle(StdSelect_BRepOwner) anOwner = Handle(StdSelect_BRepOwner)::DownCast(aSelectedOwners(i));
1482       if ( anOwner.IsNull() || !anOwner->HasShape() )
1483         continue;
1484       const TopoDS_Shape& aShape = anOwner->Shape();
1485       TopAbs_ShapeEnum aShapeType = aShape.ShapeType();
1486       if (aShapeType == TopAbs_VERTEX) {
1487         AttributePtr aPntAttr = PartSet_Tools::findAttributeBy2dPoint(theFeature, aShape, theSketch);
1488         if (aPntAttr.get() != NULL &&
1489             aSelectedAttributes.find(aPntAttr) != aSelectedAttributes.end()) {
1490           theOwnersToSelect.Add(anOwner);
1491         }
1492       }
1493       else if (aShapeType == TopAbs_EDGE) {
1494         bool aFound = aSelectedResults.find(aResult) != aSelectedResults.end();
1495         if (aSelectedResults.find(aResult) != aSelectedResults.end() &&
1496             theOwnersToSelect.FindIndex(anOwner) <= 0)
1497           theOwnersToSelect.Add(anOwner);
1498       }
1499     }
1500   }
1501 }
1502
1503 void PartSet_SketcherMgr::connectToPropertyPanel(ModuleBase_ModelWidget* theWidget, const bool isToConnect)
1504 {
1505   if (isToConnect) {
1506     connect(theWidget, SIGNAL(beforeValuesChanged()),
1507             this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1508     connect(theWidget, SIGNAL(afterValuesChanged()),
1509             this, SLOT(onAfterValuesChangedInPropertyPanel()));
1510   }
1511   else {
1512     disconnect(theWidget, SIGNAL(beforeValuesChanged()),
1513                 this, SLOT(onBeforeValuesChangedInPropertyPanel()));
1514     disconnect(theWidget, SIGNAL(afterValuesChanged()),
1515                 this, SLOT(onAfterValuesChangedInPropertyPanel()));
1516   }
1517 }
1518
1519 void PartSet_SketcherMgr::widgetStateChanged(int thePreviousState)
1520 {
1521   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1522                                                                            (getCurrentOperation());
1523   if (aFOperation) {
1524     if (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1525         PartSet_SketcherMgr::isNestedSketchOperation(aFOperation, activeSketch()) &&
1526         thePreviousState == ModuleBase_ModelWidget::ModifiedInPP) {
1527       FeaturePtr aFeature = aFOperation->feature();
1528       visualizeFeature(aFeature, aFOperation->isEditOperation(), canDisplayObject(aFeature));
1529     }
1530   }
1531 }
1532
1533 void PartSet_SketcherMgr::customizePresentation(const ObjectPtr& theObject)
1534 {
1535   ModuleBase_OperationFeature* aFOperation = dynamic_cast<ModuleBase_OperationFeature*>
1536                                                                            (getCurrentOperation());
1537   if (aFOperation && (PartSet_SketcherMgr::isSketchOperation(aFOperation) ||
1538                       PartSet_SketcherMgr::isNestedSketchOperation(aFOperation, activeSketch())))
1539     SketcherPrs_Tools::sendExpressionShownEvent(myIsConstraintsShown[PartSet_Tools::Expressions]);
1540
1541   // update entities selection priorities
1542   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1543   if (aFeature.get() && PartSet_SketcherMgr::isEntity(aFeature->getKind())) {
1544     // update priority for feature
1545     updateSelectionPriority(aFeature, aFeature);
1546     // update priority for results of the feature
1547     std::list<ResultPtr> aResults = aFeature->results();
1548     std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLastIt = aResults.end();
1549     for (; anIt != aLastIt; anIt++)
1550       updateSelectionPriority(*anIt, aFeature);
1551   }
1552 }
1553
1554 ModuleBase_Operation* PartSet_SketcherMgr::getCurrentOperation() const
1555 {
1556   return myModule->workshop()->currentOperation();
1557 }
1558
1559 //**************************************************************
1560 ModuleBase_ModelWidget* PartSet_SketcherMgr::getActiveWidget() const
1561 {
1562   ModuleBase_ModelWidget* aWidget = 0;
1563   ModuleBase_Operation* anOperation = getCurrentOperation();
1564   if (anOperation) {
1565     ModuleBase_IPropertyPanel* aPanel = anOperation->propertyPanel();
1566     if (aPanel)
1567       aWidget = aPanel->activeWidget();
1568   }
1569   return aWidget;
1570 }
1571
1572 void PartSet_SketcherMgr::visualizeFeature(const FeaturePtr& theFeature,
1573                                            const bool isEditOperation,
1574                                            const bool isToDisplay,
1575                                            const bool isFlushRedisplay)
1576 {
1577   #ifdef DEBUG_DO_NOT_BY_ENTER
1578   return;
1579   #endif
1580
1581   if (isEditOperation || !theFeature.get())
1582     return;
1583
1584   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1585   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1586
1587   // 1. change visibility of the object itself, here the presentable object is processed,
1588   // e.g. constraints features
1589   //FeaturePtr aFeature = aFOperation->feature();
1590   std::list<ResultPtr> aResults = theFeature->results();
1591   if (isToDisplay)
1592     theFeature->setDisplayed(true);
1593   else
1594     theFeature->setDisplayed(false);
1595
1596   // change visibility of the object results, e.g. non-constraint features
1597   std::list<ResultPtr>::const_iterator aIt;
1598   for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1599     if (isToDisplay) {
1600       (*aIt)->setDisplayed(true);
1601     }
1602     else {
1603       (*aIt)->setDisplayed(false);
1604     }
1605   }
1606   if (isFlushRedisplay)
1607     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1608 }
1609
1610 void PartSet_SketcherMgr::storeSelection(const bool theHighlightedOnly)
1611 {
1612   if (!myCurrentSketch.get())
1613     return;
1614
1615   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1616   ModuleBase_ISelection* aSelect = aWorkshop->selection();
1617   QList<ModuleBase_ViewerPrsPtr> aStoredPrs = aSelect->getHighlighted();
1618
1619   QList<FeaturePtr> aFeatureList;
1620   if (!theHighlightedOnly) {
1621     QList<ModuleBase_ViewerPrsPtr> aSelected = aSelect->getSelected(
1622                                                               ModuleBase_ISelection::AllControls);
1623     aStoredPrs.append(aSelected);
1624   }
1625
1626   // 1. it is necessary to save current selection in order to restore it after the features moving
1627   myCurrentSelection.clear();
1628
1629   QList<ModuleBase_ViewerPrsPtr>::const_iterator anIt = aStoredPrs.begin(), aLast = aStoredPrs.end();
1630
1631   CompositeFeaturePtr aSketch = activeSketch();
1632   for (; anIt != aLast; anIt++) {
1633     ModuleBase_ViewerPrsPtr aPrs = *anIt;
1634     ObjectPtr anObject = aPrs->object();
1635     if (!anObject.get())
1636       continue;
1637
1638     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
1639     FeaturePtr aFeature;
1640     if (aResult.get())
1641       aFeature = ModelAPI_Feature::feature(aResult);
1642     else
1643       aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1644
1645
1646     std::set<AttributePtr> aSelectedAttributes;
1647     std::set<ResultPtr> aSelectedResults;
1648     if (myCurrentSelection.find(aFeature) != myCurrentSelection.end()) {
1649       std::pair<std::set<AttributePtr>, std::set<ResultPtr> > aPair = myCurrentSelection.find(aFeature).value();
1650       aSelectedAttributes = aPair.first;
1651       aSelectedResults = aPair.second;
1652     }
1653
1654     Handle(SelectMgr_EntityOwner) anOwner = aPrs->owner();
1655     if (aResult.get()) {
1656       getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1657                              aSelectedAttributes, aSelectedResults);
1658     }
1659     else {
1660       std::list<ResultPtr> aResults = aFeature->results();
1661       std::list<ResultPtr>::const_iterator aIt;
1662       for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
1663         ResultPtr aResult = *aIt;
1664         getAttributesOrResults(anOwner, aFeature, aSketch, aResult,
1665                                aSelectedAttributes, aSelectedResults);
1666       }
1667     }
1668     myCurrentSelection[aFeature] = std::make_pair(aSelectedAttributes, aSelectedResults);
1669   }
1670   //qDebug(QString("  storeSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1671 }
1672
1673 void PartSet_SketcherMgr::restoreSelection()
1674 {
1675   if (!myCurrentSketch.get())
1676     return;
1677
1678   //qDebug(QString("restoreSelection: %1").arg(myCurrentSelection.size()).toStdString().c_str());
1679   ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1680   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1681   FeatureToSelectionMap::const_iterator aSIt = myCurrentSelection.begin(),
1682                                         aSLast = myCurrentSelection.end();
1683   SelectMgr_IndexedMapOfOwner anOwnersToSelect;
1684   for (; aSIt != aSLast; aSIt++) {
1685     anOwnersToSelect.Clear();
1686     getSelectionOwners(aSIt.key(), myCurrentSketch, aWorkshop, myCurrentSelection,
1687                         anOwnersToSelect);
1688     aConnector->workshop()->selector()->setSelectedOwners(anOwnersToSelect, false);
1689   }
1690 }
1691
1692 void PartSet_SketcherMgr::onShowConstraintsToggle(int theType, bool theState)
1693 {
1694   PartSet_Tools::ConstraintVisibleState aType = (PartSet_Tools::ConstraintVisibleState)theType;
1695
1696   updateBySketchParameters(aType, theState);
1697 }
1698
1699 void PartSet_SketcherMgr::updateBySketchParameters(
1700                                    const PartSet_Tools::ConstraintVisibleState& theType,
1701                                    bool theState)
1702 {
1703   if (myCurrentSketch.get() == NULL)
1704     return;
1705
1706   bool aPrevState = myIsConstraintsShown[theType];
1707   myIsConstraintsShown[theType] = theState;
1708
1709   switch (theType) {
1710     case PartSet_Tools::Geometrical:
1711     case PartSet_Tools::Dimensional: {
1712       if (aPrevState != theState) {
1713         ModuleBase_IWorkshop* aWorkshop = myModule->workshop();
1714         XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(aWorkshop);
1715         for (int i = 0; i < myCurrentSketch->numberOfSubs(); i++) {
1716           FeaturePtr aSubFeature = myCurrentSketch->subFeature(i);
1717           bool aProcessed = false;
1718           bool aConstraintDisplayed = canDisplayConstraint(aSubFeature, theType, aProcessed);
1719           if (aProcessed)
1720             aSubFeature->setDisplayed(aConstraintDisplayed);
1721         }
1722         Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
1723       }
1724     }
1725     break;
1726     case PartSet_Tools::Expressions: {
1727       if (aPrevState != theState) {
1728         /// call all sketch features redisplay, the expression state will be corrected in customize
1729         /// of distance presentation
1730         Events_ID anEventId = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1731         PartSet_Tools::sendSubFeaturesEvent(myCurrentSketch, anEventId);
1732       }
1733     }
1734     break;
1735   }
1736 }
1737
1738 void PartSet_SketcherMgr::updateSelectionPriority(ObjectPtr theObject,
1739                                                   FeaturePtr theFeature)
1740 {
1741   if (!theObject.get() || !theFeature.get())
1742     return;
1743
1744   AISObjectPtr anAIS = workshop()->displayer()->getAISObject(theObject);
1745   Handle(AIS_InteractiveObject) anAISIO;
1746   if (anAIS.get() != NULL) {
1747     anAISIO = anAIS->impl<Handle(AIS_InteractiveObject)>();
1748   }
1749
1750   if (!anAISIO.IsNull()) { // the presentation for the object is visualized
1751     int anAdditionalPriority = 0;
1752     // current feature
1753     std::shared_ptr<SketchPlugin_Feature> aSPFeature =
1754             std::dynamic_pointer_cast<SketchPlugin_Feature>(theFeature);
1755     if (aSPFeature.get() != NULL) {
1756       // 1. Vertices
1757       // 2. Simple segments
1758       // 3. External objects (violet color)
1759       // 4. Auxiliary segments (dotted)
1760       // StdSelect_BRepSelectionTool::Load uses priority calculating:
1761       // Standard_Integer aPriority = (thePriority == -1) ? GetStandardPriority (theShape, theType) : thePriority;
1762       // Priority of Vertex is 8, edge(segment) is 7.
1763       // It might be not corrected as provides the condition above.
1764       bool isExternal = aSPFeature->isExternal();
1765       bool isAuxiliary = PartSet_Tools::isAuxiliarySketchEntity(aSPFeature);
1766       // current feature
1767       if (!isExternal && !isAuxiliary)
1768         anAdditionalPriority = 30;
1769       // external feature
1770       if (isExternal)
1771         anAdditionalPriority = 20;
1772       // auxiliary feature
1773       if (isAuxiliary) {
1774         anAdditionalPriority = 10; /// auxiliary objects should have less priority that
1775         // edges/vertices of local selection on not-sketch objects
1776       }
1777       Handle(ModuleBase_ResultPrs) aResult = Handle(ModuleBase_ResultPrs)::DownCast(anAISIO);
1778       if (!aResult.IsNull()) {
1779         aResult->setAdditionalSelectionPriority(anAdditionalPriority);
1780       }
1781     }
1782   }
1783 }
1784
1785 XGUI_Workshop* PartSet_SketcherMgr::workshop() const
1786 {
1787   ModuleBase_IWorkshop* anIWorkshop = myModule->workshop();
1788   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(anIWorkshop);
1789   return aConnector->workshop();
1790 }
1791
1792 XGUI_OperationMgr* PartSet_SketcherMgr::operationMgr() const
1793 {
1794   return workshop()->operationMgr();
1795 }
1796