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