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