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