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