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