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