]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_WidgetSketchLabel.cpp
Salome HOME
Build SHAPER with dev version of OCCT (IR-2020-07-10)
[modules/shaper.git] / src / PartSet / PartSet_WidgetSketchLabel.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "PartSet_WidgetSketchLabel.h"
21 #include "PartSet_Tools.h"
22 #include "PartSet_Module.h"
23 #include "PartSet_PreviewPlanes.h"
24 #include "PartSet_SketcherReentrantMgr.h"
25
26 #include "SketchPlugin_SketchEntity.h"
27
28 #include <XGUI_ActionsMgr.h>
29 #include <XGUI_Displayer.h>
30 #include <XGUI_ModuleConnector.h>
31 #include <XGUI_SelectionActivate.h>
32 #include <XGUI_Selection.h>
33 #include <XGUI_SelectionMgr.h>
34 #include <XGUI_Tools.h>
35 #include <XGUI_ViewerProxy.h>
36 #include <XGUI_Workshop.h>
37
38 #include <ModelAPI_ResultBody.h>
39 #include <ModelAPI_Tools.h>
40 #include <ModelAPI_AttributeString.h>
41 #include <ModelAPI_Events.h>
42
43 #include <ModuleBase_Operation.h>
44 #include <ModuleBase_ViewerPrs.h>
45 #include <ModuleBase_Tools.h>
46 #include <ModuleBase_IModule.h>
47 #include <ModuleBase_IPropertyPanel.h>
48
49 #include <GeomAlgoAPI_FaceBuilder.h>
50 #include <GeomAlgoAPI_ShapeTools.h>
51 #include <GeomDataAPI_Point.h>
52 #include <GeomDataAPI_Dir.h>
53 #include <GeomAPI_XYZ.h>
54 #include <GeomAPI_Face.h>
55 #include <GeomAPI_Edge.h>
56 #include <GeomAPI_ShapeExplorer.h>
57
58 #include <SketchPlugin_Sketch.h>
59 #include <SketcherPrs_Tools.h>
60
61 #include <Precision.hxx>
62 #include <gp_Pln.hxx>
63 #include <gp_Pnt.hxx>
64 #include <gp_Dir.hxx>
65 #include <AIS_Shape.hxx>
66 #include <Bnd_Box.hxx>
67
68 #include <Config_WidgetAPI.h>
69 #include <Config_PropManager.h>
70
71 #include <QLabel>
72 #include <QApplication>
73 #include <QVBoxLayout>
74 #include <QHBoxLayout>
75 #include <QCheckBox>
76 #include <QGroupBox>
77 #include <QPushButton>
78 #include <QLineEdit>
79 #include <QDoubleValidator>
80 #include <QDialog>
81 #include <QTimer>
82
83 #ifndef DBL_MAX
84 #define DBL_MAX 1.7976931348623158e+308
85 #endif
86
87 PartSet_WidgetSketchLabel::PartSet_WidgetSketchLabel(QWidget* theParent,
88                         ModuleBase_IWorkshop* theWorkshop,
89                         const Config_WidgetAPI* theData,
90                         const QMap<PartSet_Tools::ConstraintVisibleState, bool>& toShowConstraints)
91 : ModuleBase_WidgetValidated(theParent, theWorkshop, theData), myOpenTransaction(false),
92 myIsSelection(false)
93 {
94   QVBoxLayout* aLayout = new QVBoxLayout(this);
95   ModuleBase_Tools::zeroMargins(aLayout);
96
97   myStackWidget = new QStackedWidget(this);
98   myStackWidget->setContentsMargins(0,0,0,0);
99   aLayout->addWidget(myStackWidget);
100
101   // Define label for plane selection
102   QWidget* aFirstWgt = new QWidget(this);
103
104   // Size of the View control
105   mySizeOfViewWidget = new QWidget(aFirstWgt);
106   QHBoxLayout* aSizeLayout = new QHBoxLayout(mySizeOfViewWidget);
107   aSizeLayout->addWidget(new QLabel(tr("Size of the view"), mySizeOfViewWidget));
108   mySizeOfView = new QLineEdit(mySizeOfViewWidget);
109
110   QDoubleValidator* aValidator = new QDoubleValidator(0, DBL_MAX, 12, mySizeOfView);
111   aValidator->setLocale(ModuleBase_Tools::doubleLocale());
112   aValidator->setNotation(QDoubleValidator::StandardNotation);
113   mySizeOfView->setValidator(aValidator);
114   aSizeLayout->addWidget(mySizeOfView);
115
116   myPartSetMessage = new QDialog(this, Qt::ToolTip);
117   myPartSetMessage->setModal(false);
118   myPartSetMessage->setStyleSheet("background-color:lightyellow;");
119   QVBoxLayout* aMsgLay = new QVBoxLayout(myPartSetMessage);
120   QString aMsg = tr("The Sketch is created in PartSet.\n"
121     "It will be necessary to create a Part in order to use this sketch for body creation");
122   aMsgLay->addWidget(new QLabel(aMsg, myPartSetMessage));
123   myPartSetMessage->hide();
124
125   mySizeMessage = new QDialog(mySizeOfView, Qt::ToolTip);
126   mySizeMessage->setModal(false);
127   mySizeMessage->setStyleSheet("background-color:lightyellow;");
128   aMsgLay = new QVBoxLayout(mySizeMessage);
129   aMsg = tr("A size of Sketch view can be defined here.");
130   aMsgLay->addWidget(new QLabel(aMsg, mySizeMessage));
131   mySizeMessage->hide();
132
133   QString aText = translate(theData->getProperty("title"));
134   QLabel* aLabel = new QLabel(aText, aFirstWgt);
135   aLabel->setWordWrap(true);
136   QString aTooltip = translate(theData->getProperty("tooltip"));
137   aLabel->setToolTip(aTooltip);
138   aLabel->setIndent(5);
139
140   aLayout = new QVBoxLayout(aFirstWgt);
141   ModuleBase_Tools::zeroMargins(aLayout);
142   aLayout->addWidget(mySizeOfViewWidget);
143   aLayout->addWidget(aLabel);
144
145   myRemoveExternal = new QCheckBox(tr("Remove external dependencies"), aFirstWgt);
146   myRemoveExternal->setChecked(false);
147   aLayout->addWidget(myRemoveExternal);
148   myRemoveExternal->setVisible(false);
149
150   aLayout->addStretch(1);
151
152   myStackWidget->addWidget(aFirstWgt);
153
154   // Define widget for sketch manmagement
155   QWidget* aSecondWgt = new QWidget(this);
156   aLayout = new QVBoxLayout(aSecondWgt);
157   ModuleBase_Tools::zeroMargins(aLayout);
158
159   QGroupBox* aViewBox = new QGroupBox(tr("Sketcher plane"), this);
160   QGridLayout* aViewLayout = new QGridLayout(aViewBox);
161
162   myViewInverted = new QCheckBox(tr("Reversed"), aViewBox);
163   aViewLayout->addWidget(myViewInverted, 0, 0);
164
165   myViewVisible = new QCheckBox(tr("Visible"), aViewBox);
166   myViewVisible->setChecked(true);
167   aViewLayout->addWidget(myViewVisible, 0, 1, Qt::AlignRight);
168   connect(myViewVisible, SIGNAL(toggled(bool)), this, SLOT(onShowViewPlane(bool)));
169
170   QPushButton* aSetViewBtn =
171     new QPushButton(QIcon(":icons/plane_view.png"), tr("Set plane view"), aViewBox);
172   connect(aSetViewBtn, SIGNAL(clicked(bool)), this, SLOT(onSetPlaneView()));
173   aViewLayout->addWidget(aSetViewBtn, 1, 0, 1, 2);
174
175   aLayout->addWidget(aViewBox);
176
177   QMap<PartSet_Tools::ConstraintVisibleState, QString> aStates;
178   aStates[PartSet_Tools::Geometrical] = tr("Show geometrical constraints");
179   aStates[PartSet_Tools::Dimensional] = tr("Show dimensional constraints");
180   aStates[PartSet_Tools::Expressions] = tr("Show existing expressions");
181
182   QMap<PartSet_Tools::ConstraintVisibleState, QString>::const_iterator anIt = aStates.begin(),
183                                                         aLast = aStates.end();
184   for (; anIt != aLast; anIt++) {
185     QCheckBox* aShowConstraints = new QCheckBox(anIt.value(), this);
186     connect(aShowConstraints, SIGNAL(toggled(bool)), this, SLOT(onShowConstraint(bool)));
187     aLayout->addWidget(aShowConstraints);
188
189     PartSet_Tools::ConstraintVisibleState aState = anIt.key();
190     myShowConstraints[aState] = aShowConstraints;
191
192     if (toShowConstraints.contains(aState))
193       aShowConstraints->setChecked(toShowConstraints[aState]);
194   }
195   myShowPoints = new QCheckBox(tr("Show free points"), this);
196   connect(myShowPoints, SIGNAL(toggled(bool)), this, SIGNAL(showFreePoints(bool)));
197   aLayout->addWidget(myShowPoints);
198
199   myAutoConstraints = new QCheckBox(tr("Automatic constraints"), this);
200   myAutoConstraints->setToolTip(tr("Automatic vertical and horizontal constraints"));
201   connect(myAutoConstraints, SIGNAL(toggled(bool)), this, SIGNAL(autoConstraints(bool)));
202   aLayout->addWidget(myAutoConstraints);
203
204   QPushButton* aPlaneBtn = new QPushButton(tr("Change sketch plane"), aSecondWgt);
205   connect(aPlaneBtn, SIGNAL(clicked(bool)), SLOT(onChangePlane()));
206   aLayout->addWidget(aPlaneBtn);
207
208   aLayout->addSpacing(15);
209
210   myDoFLabel = new QLabel("", aSecondWgt);
211   aLayout->addWidget(myDoFLabel);
212
213   myShowDOFBtn = new QPushButton(tr("Show remaining DoFs"), aSecondWgt);
214   aLayout->addWidget(myShowDOFBtn);
215   myShowDOFBtn->setEnabled(false);
216   connect(myShowDOFBtn, SIGNAL(clicked(bool)), SLOT(onShowDOF()));
217
218   myStackWidget->addWidget(aSecondWgt);
219   //setLayout(aLayout);
220
221   myPreviewPlanes = new PartSet_PreviewPlanes();
222 }
223
224 PartSet_WidgetSketchLabel::~PartSet_WidgetSketchLabel()
225 {
226 }
227
228 bool PartSet_WidgetSketchLabel::setSelection(QList<ModuleBase_ViewerPrsPtr>& theValues,
229                                              const bool theToValidate)
230 {
231   // do not use the given selection if the plane of the sketch has been already set.
232   // If this check is absent, a selected plane in the viewer can be set in the sketch
233   // even if the sketch is built on another plane.
234   if (plane().get())
235     return true;
236
237   ModuleBase_ViewerPrsPtr aPrs = theValues.first();
238   bool aDone = setSelectionInternal(theValues, theToValidate);
239   if (aDone)
240     updateByPlaneSelected(aPrs);
241   return aDone;
242 }
243
244 QList<QWidget*> PartSet_WidgetSketchLabel::getControls() const
245 {
246   QList<QWidget*> aResult;
247   aResult << myStackWidget;
248   return aResult;
249 }
250
251 bool PartSet_WidgetSketchLabel::processSelection()
252 {
253   std::shared_ptr<GeomAPI_Pln> aPlane = plane();
254   if (aPlane.get())
255     return false;
256
257   QList<ModuleBase_ViewerPrsPtr> aSelected = getFilteredSelected();
258
259   if (aSelected.empty())
260     return false;
261   ModuleBase_ViewerPrsPtr aPrs = aSelected.first();
262   bool aDone = setSelectionInternal(aSelected, false);
263   if (aDone) {
264     updateByPlaneSelected(aPrs);
265     updateObject(myFeature);
266   }
267
268   return aDone;
269 }
270
271 void PartSet_WidgetSketchLabel::onShowConstraint(bool theOn)
272 {
273   QCheckBox* aSenderCheckBox = qobject_cast<QCheckBox*>(sender());
274
275   QMap<PartSet_Tools::ConstraintVisibleState, QCheckBox*>::const_iterator
276                           anIt = myShowConstraints.begin(), aLast = myShowConstraints.end();
277
278   PartSet_Tools::ConstraintVisibleState aState = PartSet_Tools::Geometrical;
279   bool aFound = false;
280   for (; anIt != aLast && !aFound; anIt++) {
281     aFound = anIt.value() == aSenderCheckBox;
282     if (aFound)
283       aState = anIt.key();
284   }
285   if (aFound)
286     emit showConstraintToggled(aState, theOn);
287 }
288
289 void PartSet_WidgetSketchLabel::blockAttribute(const AttributePtr& theAttribute,
290                                                const bool& theToBlock, bool& isFlushesActived,
291                                                bool& isAttributeSetInitializedBlocked,
292                                                bool& isAttributeSendUpdatedBlocked)
293 {
294   ModuleBase_WidgetValidated::blockAttribute(theAttribute, theToBlock, isFlushesActived,
295                                              isAttributeSetInitializedBlocked,
296                                              isAttributeSendUpdatedBlocked);
297   // We do not restore the previous state of isAttributeSetInitializedBlocked for each of
298   // attributes. It it is necessary, these states should be append to the method attributes
299   // or stored in the widget
300
301   std::list<AttributePtr> anAttributes = myFeature->data()->attributes("");
302   std::list<AttributePtr>::const_iterator anIt = anAttributes.begin(), aLast = anAttributes.end();
303   QStringList aValues;
304   for(; anIt != aLast; anIt++) {
305     AttributePtr anAttribute = *anIt;
306     if (theToBlock)
307       anAttribute->blockSetInitialized(true);
308     else
309       anAttribute->blockSetInitialized(isAttributeSetInitializedBlocked);
310   }
311 }
312
313 bool PartSet_WidgetSketchLabel::setSelectionInternal(
314                                           const QList<ModuleBase_ViewerPrsPtr>& theValues,
315                                           const bool theToValidate)
316 {
317   bool aDone = false;
318   if (theValues.empty()) {
319     // In order to make reselection possible, set empty object and shape should be done
320     setSelectionCustom(ModuleBase_ViewerPrsPtr(
321                               new ModuleBase_ViewerPrs(ObjectPtr(), GeomShapePtr(), NULL)));
322     aDone = false;
323   }
324   else {
325     // it removes the processed value from the parameters list
326     ModuleBase_ViewerPrsPtr aValue = theValues.first();//.takeFirst();
327     if (!theToValidate || isValidInFilters(aValue)) {
328       myIsSelection = true;
329       aDone = setSelectionCustom(aValue);
330       myIsSelection = false;
331     }
332   }
333
334   return aDone;
335 }
336
337 void PartSet_WidgetSketchLabel::updateByPlaneSelected(const ModuleBase_ViewerPrsPtr& thePrs)
338 {
339   // Nullify a temporary remembered plane
340   if (myTmpPlane.get())
341     myTmpPlane.reset();
342
343   GeomPlanePtr aPlane = plane();
344   if (!aPlane.get())
345     return;
346
347   myPartSetMessage->hide();
348   mySizeMessage->hide();
349
350   // 1. hide main planes if they have been displayed and display sketch preview plane
351   myPreviewPlanes->erasePreviewPlanes(myWorkshop);
352
353   QString aSizeOfViewStr = mySizeOfView->text();
354   bool isSetSizeOfView = false;
355   double aSizeOfView = 0;
356   if (!aSizeOfViewStr.isEmpty()) {
357     aSizeOfView = aSizeOfViewStr.toDouble(&isSetSizeOfView);
358     if (isSetSizeOfView && aSizeOfView <= 0) {
359       isSetSizeOfView = false;
360     }
361   }
362   PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
363   if (aModule) {
364     CompositeFeaturePtr aSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(myFeature);
365     aModule->sketchMgr()->previewSketchPlane()->setSizeOfView(aSizeOfView, isSetSizeOfView);
366     if (myViewVisible->isChecked())
367       aModule->sketchMgr()->previewSketchPlane()->createSketchPlane(aSketch, myWorkshop);
368   }
369   // 2. if the planes were displayed, change the view projection
370
371   std::shared_ptr<GeomAPI_Dir> aDir = aPlane->direction();
372   gp_XYZ aXYZ = aDir->impl<gp_Dir>().XYZ();
373   double aTwist = 0.0;
374
375   // Rotate view if the sketcher plane is selected only from preview planes
376   // Preview planes are created only if there is no any shape
377   bool aRotate = Config_PropManager::boolean(SKETCH_TAB_NAME, "rotate_to_plane");
378   if (aRotate) {
379     myWorkshop->viewer()->setViewProjection(aXYZ.X(), aXYZ.Y(), aXYZ.Z(), aTwist);
380   }
381   if (isSetSizeOfView && aSizeOfView > 0) {
382     Handle(V3d_View) aView3d = myWorkshop->viewer()->activeView();
383     if (!aView3d.IsNull()) {
384       Bnd_Box aBndBox;
385       double aHalfSize = aSizeOfView/2.0;
386       aBndBox.Update(-aHalfSize, -aHalfSize, -aHalfSize, aHalfSize, aHalfSize, aHalfSize);
387       aView3d->FitAll(aBndBox, 0.01, false);
388     }
389   }
390   if (myOpenTransaction) {
391     SessionPtr aMgr = ModelAPI_Session::get();
392     aMgr->finishOperation();
393     myOpenTransaction = false;
394   }
395   // 3. Clear text in the label
396   myStackWidget->setCurrentIndex(1);
397   //myLabel->setText("");
398   //myLabel->setToolTip("");
399   XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(myWorkshop);
400
401   // 5. Clear selection mode and define sketching mode
402   emit planeSelected(plane());
403   // after the plane is selected in the sketch, the sketch selection should be activated
404   // it can not be performed in the sketch label widget because, we don't need to switch off
405   // the selection by any label deactivation, but need to switch it off by stop the sketch
406   myWorkshop->selectionActivate()->updateSelectionFilters();
407   myWorkshop->selectionActivate()->updateSelectionModes();
408
409   if (aModule)
410     aModule->onViewTransformed();
411
412   myWorkshop->updateCommandStatus();
413   aWorkshop->selector()->clearSelection();
414   myWorkshop->viewer()->update();
415
416   myRemoveExternal->setVisible(false);
417 }
418
419 std::shared_ptr<GeomAPI_Pln> PartSet_WidgetSketchLabel::plane() const
420 {
421   CompositeFeaturePtr aSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(myFeature);
422   return PartSet_Tools::sketchPlane(aSketch);
423 }
424
425 bool PartSet_WidgetSketchLabel::focusTo()
426 {
427   ModuleBase_Tools::setFocus(myStackWidget, "PartSet_WidgetSketchLabel::focusTo()");
428   return true;
429 }
430
431 void PartSet_WidgetSketchLabel::enableFocusProcessing()
432 {
433   myStackWidget->installEventFilter(this);
434 }
435
436 void PartSet_WidgetSketchLabel::storeAttributeValue(const AttributePtr& theAttribute)
437 {
438   ModuleBase_WidgetValidated::storeAttributeValue(theAttribute);
439 }
440
441 void PartSet_WidgetSketchLabel::restoreAttributeValue(const AttributePtr& theAttribute,
442                                                       const bool theValid)
443 {
444   ModuleBase_WidgetValidated::restoreAttributeValue(theAttribute, theValid);
445
446   // it is not necessary to save the previous plane value because the plane is chosen once
447   DataPtr aData = feature()->data();
448   AttributeSelectionPtr aSelAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
449     (aData->attribute(SketchPlugin_SketchEntity::EXTERNAL_ID()));
450   if (aSelAttr) {
451     ResultPtr anEmptyResult;
452     GeomShapePtr anEmptyShape;
453     aSelAttr->setValue(anEmptyResult, anEmptyShape);
454   }
455   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
456     aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
457   anOrigin->reset();
458   std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
459     aData->attribute(SketchPlugin_Sketch::NORM_ID()));
460   aNormal->reset();
461   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
462     aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
463   aDirX->reset();
464 }
465
466 bool PartSet_WidgetSketchLabel::setSelectionCustom(const ModuleBase_ViewerPrsPtr& thePrs)
467 {
468   if (myIsSelection && myRemoveExternal->isVisible()) {
469     if (myRemoveExternal->isChecked()) {
470       myFeature->customAction(SketchPlugin_Sketch::ACTION_REMOVE_EXTERNAL());
471     }
472   }
473   return fillSketchPlaneBySelection(thePrs);
474 }
475
476 bool PartSet_WidgetSketchLabel::canFillSketch(const ModuleBase_ViewerPrsPtr& thePrs)
477 {
478   bool aCanFillSketch = true;
479   // avoid any selection on sketch object
480   ObjectPtr anObject = thePrs->object();
481   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
482   if (aResult.get()) {
483     FeaturePtr aFeature = ModelAPI_Feature::feature(aResult);
484     if (aFeature->getKind() == SketchPlugin_Sketch::ID())
485       aCanFillSketch = false;
486   }
487   // check plane or planar face of any non-sketch object
488   if (aCanFillSketch) {
489     GeomShapePtr aGeomShape = thePrs->shape();
490     if ((!aGeomShape.get() || aGeomShape->isNull()) && aResult.get()) {
491       aGeomShape = aResult->shape();
492     }
493
494     if (aGeomShape.get() && aGeomShape->shapeType() == GeomAPI_Shape::FACE) {
495       std::shared_ptr<GeomAPI_Face> aGeomFace(new GeomAPI_Face(aGeomShape));
496       aCanFillSketch = aGeomFace.get() && aGeomFace->isPlanar();
497     }
498     else
499       aCanFillSketch = false;
500   }
501   return aCanFillSketch;
502 }
503
504 bool PartSet_WidgetSketchLabel::fillSketchPlaneBySelection(const ModuleBase_ViewerPrsPtr& thePrs)
505 {
506   bool isOwnerSet = false;
507
508   const GeomShapePtr& aShape = thePrs->shape();
509   std::shared_ptr<GeomAPI_Dir> aDir;
510
511   if (aShape.get() && !aShape->isNull()) {
512     const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
513     aDir = setSketchPlane(aTDShape);
514     isOwnerSet = aDir.get();
515   }
516   if (thePrs->object() && (feature() != thePrs->object())) {
517     FeaturePtr aFeature = ModelAPI_Feature::feature(thePrs->object());
518     DataPtr aData = feature()->data();
519     AttributeSelectionPtr aSelAttr =
520       std::dynamic_pointer_cast<ModelAPI_AttributeSelection>
521       (aData->attribute(SketchPlugin_SketchEntity::EXTERNAL_ID()));
522     if (aSelAttr.get()) {
523       ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(thePrs->object());
524       if (aRes.get()) {
525         GeomShapePtr aShapePtr;
526         if (!aShape.get() || aShape->isNull()) {  // selection happens in the OCC viewer
527           aShapePtr = ModelAPI_Tools::shape(aRes);
528         }
529         else { // selection happens in OB browser
530           aShapePtr = aShape;
531         }
532         if (aShapePtr.get() && aShapePtr->isFace()) {
533           const TopoDS_Shape& aTDShape = aShapePtr->impl<TopoDS_Shape>();
534           setSketchPlane(aTDShape);
535           aSelAttr->setValue(aRes, aShapePtr);
536           isOwnerSet = true;
537         }
538       }
539       else {
540         aSelAttr->setValue(aFeature, GeomShapePtr());
541         GeomShapePtr aSelShape = aSelAttr->value();
542         if (!aSelShape.get() && aSelAttr->contextFeature().get() &&
543           aSelAttr->contextFeature()->firstResult().get()) {
544           aSelShape = aSelAttr->contextFeature()->firstResult()->shape();
545         }
546         if (aSelShape.get() && aSelShape->isPlanar()) {
547           const TopoDS_Shape& aTDShape = aSelShape->impl<TopoDS_Shape>();
548           setSketchPlane(aTDShape);
549           isOwnerSet = true;
550         }
551       }
552     }
553   }
554   return isOwnerSet;
555 }
556
557 void PartSet_WidgetSketchLabel::activateCustom()
558 {
559   QWidget* aTopWidget = window();
560   if (aTopWidget)
561     aTopWidget->installEventFilter(this);
562
563   PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
564   if (aModule) {
565     bool isBlocked = myAutoConstraints->blockSignals(true);
566     myAutoConstraints->setChecked(aModule->sketchReentranceMgr()->isAutoConstraints());
567     myAutoConstraints->blockSignals(isBlocked);
568   }
569
570   std::shared_ptr<GeomAPI_Pln> aPlane = plane();
571   if (aPlane.get()) {
572     myStackWidget->setCurrentIndex(1);
573     return;
574   }
575
576   myStackWidget->setCurrentIndex(0);
577   bool aBodyIsVisualized = myPreviewPlanes->hasVisualizedBodies(myWorkshop);
578
579   // Clear previous selection mode It is necessary for correct activation of preview planes
580   XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(myWorkshop);
581   XGUI_Displayer* aDisp = aWorkshop->displayer();
582   aWorkshop->selectionActivate()->activateObjects(QIntList(), aDisp->displayedObjects(), false);
583
584   if (!aBodyIsVisualized) {
585     // We have to select a plane before any operation
586     myPreviewPlanes->showPreviewPlanes(myWorkshop);
587     mySizeOfViewWidget->setVisible(true);
588   }
589   else
590     mySizeOfViewWidget->setVisible(false);
591 }
592
593 void PartSet_WidgetSketchLabel::showEvent(QShowEvent* theEvent)
594 {
595   ModuleBase_WidgetValidated::showEvent(theEvent);
596   QTimer::singleShot(10, this, SLOT(onShowPanel()));
597 }
598
599 void PartSet_WidgetSketchLabel::hideEvent(QHideEvent* theEvent)
600 {
601   ModuleBase_WidgetValidated::hideEvent(theEvent);
602   if (myPartSetMessage->isVisible())
603     myPartSetMessage->hide();
604   if (mySizeMessage->isVisible())
605     mySizeMessage->hide();
606 }
607
608
609 void PartSet_WidgetSketchLabel::onShowPanel()
610 {
611   //if (mySizeOfViewWidget->isVisible()) {
612   if (myStackWidget->currentIndex() == 0) {
613     DocumentPtr aDoc = feature()->document();
614     DocumentPtr aModDoc = ModelAPI_Session::get()->moduleDocument();
615     if (aModDoc == aDoc) {
616       myPartSetMessage->move(mapToGlobal(geometry().bottomLeft()));
617       myPartSetMessage->show();
618     }
619     if (mySizeOfViewWidget->isVisible()) {
620       QPoint aPnt = mySizeOfView->mapToGlobal(mySizeOfView->geometry().center());
621       mySizeMessage->move(aPnt);
622       mySizeMessage->show();
623     }
624   }
625 }
626
627 void PartSet_WidgetSketchLabel::deactivate()
628 {
629   QWidget* aTopWidget = window();
630   if (aTopWidget)
631     aTopWidget->removeEventFilter(this);
632
633   if (myTmpPlane.get()) {
634     setSketchPlane(myTmpPlane);
635     myTmpPlane.reset();
636   }
637
638   ModuleBase_WidgetValidated::deactivate();
639   bool aHidePreview = myPreviewPlanes->isPreviewDisplayed();
640   myPreviewPlanes->erasePreviewPlanes(myWorkshop);
641
642   if (aHidePreview)
643     myWorkshop->viewer()->update();
644
645   if (myOpenTransaction) {
646     SessionPtr aMgr = ModelAPI_Session::get();
647     aMgr->finishOperation();
648     myOpenTransaction = false;
649   }
650 }
651
652 void PartSet_WidgetSketchLabel::selectionModes(int& theModuleSelectionModes, QIntList& theModes)
653 {
654   theModuleSelectionModes = -1;
655   std::shared_ptr<GeomAPI_Pln> aPlane = plane();
656   if (!aPlane.get())
657     theModes << TopAbs_FACE;
658 }
659
660 void PartSet_WidgetSketchLabel::selectionFilters(QIntList& theModuleSelectionFilters,
661                                                  SelectMgr_ListOfFilter& theSelectionFilters)
662 {
663   std::shared_ptr<GeomAPI_Pln> aPlane = plane();
664   if (aPlane.get())
665     return;
666   return ModuleBase_WidgetValidated::selectionFilters(theModuleSelectionFilters,
667                                                       theSelectionFilters);
668 }
669
670 std::shared_ptr<GeomAPI_Dir>
671   PartSet_WidgetSketchLabel::setSketchPlane(const TopoDS_Shape& theShape)
672 {
673   if (theShape.IsNull())
674     return std::shared_ptr<GeomAPI_Dir>();
675
676   // get selected shape
677   std::shared_ptr<GeomAPI_Shape> aGShape(new GeomAPI_Shape);
678   aGShape->setImpl(new TopoDS_Shape(theShape));
679
680   // get plane parameters
681   std::shared_ptr<GeomAPI_Face> aFace(new GeomAPI_Face(aGShape));
682   std::shared_ptr<GeomAPI_Pln> aPlane = aFace->getPlane();
683   if (!aPlane.get())
684     return std::shared_ptr<GeomAPI_Dir>();
685   return setSketchPlane(aPlane);
686 }
687
688 std::shared_ptr<GeomAPI_Dir>
689   PartSet_WidgetSketchLabel::setSketchPlane(std::shared_ptr<GeomAPI_Pln> thePlane)
690 {
691   // set plane parameters to feature
692   std::shared_ptr<ModelAPI_Data> aData = feature()->data();
693   double anA, aB, aC, aD;
694   thePlane->coefficients(anA, aB, aC, aD);
695
696   // calculate attributes of the sketch
697   std::shared_ptr<GeomAPI_Dir> aNormDir(new GeomAPI_Dir(anA, aB, aC));
698   std::shared_ptr<GeomAPI_XYZ> aCoords = aNormDir->xyz();
699   std::shared_ptr<GeomAPI_XYZ> aZero(new GeomAPI_XYZ(0, 0, 0));
700   aCoords = aCoords->multiplied(-aD * aCoords->distance(aZero));
701   std::shared_ptr<GeomAPI_Pnt> anOrigPnt(new GeomAPI_Pnt(aCoords));
702   // X axis is preferable to be dirX on the sketch
703   const double tol = Precision::Confusion();
704   bool isX = fabs(fabs(anA) - 1.0) < tol && fabs(aB) < tol && fabs(aC) < tol;
705   std::shared_ptr<GeomAPI_Dir> aTempDir(
706       isX ? new GeomAPI_Dir(0, 1, 0) : new GeomAPI_Dir(1, 0, 0));
707   std::shared_ptr<GeomAPI_Dir> aYDir(new GeomAPI_Dir(aNormDir->cross(aTempDir)));
708   std::shared_ptr<GeomAPI_Dir> aXDir(new GeomAPI_Dir(aYDir->cross(aNormDir)));
709
710   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
711       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
712   anOrigin->setValue(anOrigPnt);
713   std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
714       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
715   aNormal->setValue(aNormDir);
716   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
717       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
718   aDirX->setValue(aXDir);
719   std::shared_ptr<GeomAPI_Dir> aDir = thePlane->direction();
720   return aDir;
721 }
722
723 void PartSet_WidgetSketchLabel::onSetPlaneView()
724 {
725   std::shared_ptr<GeomAPI_Pln> aPlane = plane();
726   if (aPlane.get()) {
727     std::shared_ptr<GeomAPI_Dir> aDirection = aPlane->direction();
728     gp_Dir aDir = aDirection->impl<gp_Dir>();
729     if (myViewInverted->isChecked())
730       aDir.Reverse();
731     myWorkshop->viewer()->setViewProjection(aDir.X(), aDir.Y(), aDir.Z(), 0.);
732     PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
733     if (aModule)
734       aModule->onViewTransformed();
735   }
736 }
737
738
739 //******************************************************
740 QList<ModuleBase_ViewerPrsPtr> PartSet_WidgetSketchLabel::findCircularEdgesInPlane()
741 {
742   QList<std::shared_ptr<ModuleBase_ViewerPrs>> aResult;
743   XGUI_Workshop* aWorkshop = XGUI_Tools::workshop(myWorkshop);
744   XGUI_Displayer* aDisplayer = aWorkshop->displayer();
745   QObjectPtrList aDispObjects = aDisplayer->displayedObjects();
746
747   std::shared_ptr<GeomAPI_Pln> aPlane = plane();
748   foreach(ObjectPtr aObj, aDispObjects) {
749     ResultPtr aResObj = std::dynamic_pointer_cast<ModelAPI_Result>(aObj);
750     if (aResObj.get()) {
751       GeomShapePtr aShape = aResObj->shape();
752       if (aShape.get()) {
753         GeomAPI_ShapeExplorer aExplorer(aShape, GeomAPI_Shape::EDGE);
754         for(; aExplorer.more(); aExplorer.next()) {
755           GeomShapePtr aEdgeShape = aExplorer.current();
756           GeomAPI_Edge anEdge(aEdgeShape);
757           if ((anEdge.isCircle() || anEdge.isArc() || anEdge.isEllipse()) &&
758                anEdge.isInPlane(aPlane)) {
759             bool isContains = false;
760             // Check that edge is not used.
761             // It is possible that the same edge will be taken from different faces
762             foreach(ModuleBase_ViewerPrsPtr aPrs, aResult) {
763               GeomAPI_Edge aUsedEdge(aPrs->shape());
764               if (aUsedEdge.isEqual(aEdgeShape)) {
765                 isContains = true;
766                 break;
767               }
768             }
769             if (!isContains) {
770               ModuleBase_ViewerPrsPtr aPrs(new ModuleBase_ViewerPrs(aResObj, aEdgeShape));
771               aResult.append(aPrs);
772             }
773           }
774         }
775       }
776     }
777   }
778   return aResult;
779 }
780
781 //******************************************************
782 void PartSet_WidgetSketchLabel::onChangePlane()
783 {
784   PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
785   if (aModule) {
786     mySizeOfViewWidget->setVisible(false);
787     myRemoveExternal->setVisible(true);
788     myStackWidget->setCurrentIndex(0);
789
790     bool aBodyIsVisualized = myPreviewPlanes->hasVisualizedBodies(myWorkshop);
791
792     if (!aBodyIsVisualized) {
793       // We have to select a plane before any operation
794       myPreviewPlanes->showPreviewPlanes(myWorkshop);
795     }
796
797     CompositeFeaturePtr aSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(myFeature);
798     myTmpPlane = PartSet_Tools::sketchPlane(aSketch);
799     PartSet_Tools::nullifySketchPlane(aSketch);
800
801     Handle(SelectMgr_Filter) aFilter = aModule->selectionFilter(SF_SketchPlaneFilter);
802     if (!aFilter.IsNull()) {
803       std::shared_ptr<GeomAPI_Pln> aPln;
804       Handle(ModuleBase_ShapeInPlaneFilter)::DownCast(aFilter)->setPlane(aPln);
805     }
806     XGUI_Workshop* aWorkshop = aModule->getWorkshop();
807
808     aWorkshop->selectionActivate()->updateSelectionFilters();
809     aWorkshop->selectionActivate()->updateSelectionModes();
810
811     SessionPtr aMgr = ModelAPI_Session::get();
812     aMgr->startOperation("Change Sketch plane");
813     myOpenTransaction = true;
814     myWorkshop->viewer()->update();
815   }
816 }
817
818 void PartSet_WidgetSketchLabel::setShowPointsState(bool theState)
819 {
820   bool aBlock = myShowPoints->blockSignals(true);
821   myShowPoints->setChecked(theState);
822   myShowPoints->blockSignals(aBlock);
823 }
824
825 bool PartSet_WidgetSketchLabel::restoreValueCustom()
826 {
827   if (myFeature.get()) {
828     CompositeFeaturePtr aSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(myFeature);
829     if (aSketch.get() && (aSketch->numberOfSubs() > 0)) {
830       AttributeStringPtr aDOFStr = aSketch->string("SolverDOF");
831       if (aDOFStr.get()) {
832         QString aVal(aDOFStr->value().c_str());
833         if (aVal.contains('=')) {
834           // to support old data
835           aVal = aVal.right(aVal.length() - aVal.lastIndexOf('='));
836         }
837         int aDoF = aVal.toInt();
838         if (aDoF == 0) {
839           myDoFLabel->setText(tr("Sketch is fully fixed (DoF = 0)"));
840           myShowDOFBtn->setEnabled(false);
841         } else {
842           myDoFLabel->setText(tr("DoF (degrees of freedom) = ") + aVal);
843           myShowDOFBtn->setEnabled(true);
844         }
845       }
846     }
847     else {
848       myDoFLabel->setText("");
849       myShowDOFBtn->setEnabled(false);
850     }
851   }
852   return true;
853 }
854
855
856 void PartSet_WidgetSketchLabel::onShowDOF()
857 {
858   CompositeFeaturePtr aCompFeature =
859     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(myFeature);
860   if (aCompFeature.get()) {
861     static const Events_ID anEvent = Events_Loop::eventByName(EVENT_GET_DOF_OBJECTS);
862     ModelAPI_EventCreator::get()->sendUpdated(aCompFeature, anEvent);
863     Events_Loop::loop()->flush(anEvent);
864
865     // Transfer focus to the current viewport for correct processing of a key event
866     QWidget* aViewPort = myWorkshop->viewer()->activeViewPort();
867     if (aViewPort)
868       aViewPort->setFocus();
869   }
870 }
871
872 bool PartSet_WidgetSketchLabel::eventFilter(QObject* theObj, QEvent* theEvent)
873 {
874   if (theObj == window()) {
875     int aType = theEvent->type();
876     if ((aType == QEvent::Hide) || (aType == QEvent::WindowDeactivate)) {
877       if (myPartSetMessage->isVisible())
878         myPartSetMessage->hide();
879       if (mySizeMessage->isVisible())
880         mySizeMessage->hide();
881     }
882     else if ((aType == QEvent::Show) || (aType == QEvent::WindowActivate))
883       onShowPanel();
884   }
885   return ModuleBase_WidgetValidated::eventFilter(theObj, theEvent);
886 }
887
888 void PartSet_WidgetSketchLabel::onShowViewPlane(bool toShow)
889 {
890   PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
891   PartSet_PreviewSketchPlane* aPreviewPlane = aModule->sketchMgr()->previewSketchPlane();
892   if (toShow) {
893     CompositeFeaturePtr aSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(myFeature);
894     if (aPreviewPlane->isPlaneCreated())
895       aPreviewPlane->displaySketchPlane(myWorkshop);
896     else
897       aPreviewPlane->createSketchPlane(aSketch, myWorkshop);
898   }
899   else {
900     aPreviewPlane->eraseSketchPlane(myWorkshop, false);
901   }
902   myWorkshop->viewer()->update();
903 }