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