Salome HOME
66a67efc418a917d2d4085aa1e9ad7452db47f02
[modules/shaper.git] / src / PartSet / PartSet_WidgetPoint2d.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        PartSet_WidgetPoint2D.cpp
4 // Created:     25 Apr 2014
5 // Author:      Natalia ERMOLAEVA
6
7 #include "PartSet_WidgetPoint2d.h"
8 #include <PartSet_Tools.h>
9 #include <PartSet_Module.h>
10
11 #include <ModuleBase_ParamSpinBox.h>
12 #include <ModuleBase_Tools.h>
13 #include <ModuleBase_IViewer.h>
14 #include <ModuleBase_IViewWindow.h>
15 #include <ModuleBase_ISelection.h>
16
17 #include <Config_Keywords.h>
18 #include <Config_WidgetAPI.h>
19
20 #include <Events_Loop.h>
21 #include <ModelAPI_Events.h>
22
23 #include <ModelAPI_Feature.h>
24 #include <ModelAPI_Data.h>
25 #include <ModelAPI_Object.h>
26 #include <GeomDataAPI_Point2D.h>
27 #include <GeomAPI_Pnt2d.h>
28
29 #include <SketchPlugin_Feature.h>
30 #include <SketchPlugin_ConstraintCoincidence.h>
31 #include <SketchPlugin_Line.h>
32 #include <SketchPlugin_Arc.h>
33 #include <SketchPlugin_Circle.h>
34 #include <SketchPlugin_Point.h>
35
36 #include <QGroupBox>
37 #include <QGridLayout>
38 #include <QLabel>
39 #include <QEvent>
40 #include <QMouseEvent>
41 #include <QApplication>
42
43 #include <TopoDS.hxx>
44 #include <TopoDS_Vertex.hxx>
45 #include <BRep_Tool.hxx>
46
47 #include <cfloat>
48 #include <climits>
49
50 const double MaxCoordinate = 1e12;
51
52 static QStringList MyFeaturesForCoincedence;
53
54 PartSet_WidgetPoint2D::PartSet_WidgetPoint2D(QWidget* theParent, 
55                                              ModuleBase_IWorkshop* theWorkshop,
56                                              const Config_WidgetAPI* theData,
57                                              const std::string& theParentId)
58  : ModuleBase_ModelWidget(theParent, theData, theParentId), myWorkshop(theWorkshop)
59 {
60   if (MyFeaturesForCoincedence.isEmpty()) {
61     MyFeaturesForCoincedence << SketchPlugin_Line::ID().c_str()
62       << SketchPlugin_Arc::ID().c_str()
63       << SketchPlugin_Point::ID().c_str()
64       << SketchPlugin_Circle::ID().c_str();
65   }
66
67   // the control should accept the focus, so the boolen flag is corrected to be true
68   myIsObligatory = true;
69   //myOptionParam = theData->getProperty(PREVIOUS_FEATURE_PARAM);
70   QString aPageName = QString::fromStdString(theData->getProperty(CONTAINER_PAGE_NAME));
71   myGroupBox = new QGroupBox(aPageName, theParent);
72   myGroupBox->setFlat(false);
73
74   QGridLayout* aGroupLay = new QGridLayout(myGroupBox);
75   ModuleBase_Tools::adjustMargins(aGroupLay);
76   aGroupLay->setSpacing(2);
77   aGroupLay->setColumnStretch(1, 1);
78   {
79     QLabel* aLabel = new QLabel(myGroupBox);
80     aLabel->setText(tr("X "));
81     aGroupLay->addWidget(aLabel, 0, 0);
82
83     myXSpin = new ModuleBase_ParamSpinBox(myGroupBox);
84     myXSpin->setMinimum(-DBL_MAX);
85     myXSpin->setMaximum(DBL_MAX);
86     myXSpin->setToolTip(tr("X"));
87     aGroupLay->addWidget(myXSpin, 0, 1);
88
89     connect(myXSpin, SIGNAL(valueChanged(const QString&)), this, SIGNAL(valuesModified()));
90   }
91   {
92     QLabel* aLabel = new QLabel(myGroupBox);
93     aLabel->setText(tr("Y "));
94     aGroupLay->addWidget(aLabel, 1, 0);
95
96     myYSpin = new ModuleBase_ParamSpinBox(myGroupBox);
97     myYSpin->setMinimum(-DBL_MAX);
98     myYSpin->setMaximum(DBL_MAX);
99     myYSpin->setToolTip(tr("Y"));
100     aGroupLay->addWidget(myYSpin, 1, 1);
101
102     connect(myYSpin, SIGNAL(valueChanged(const QString&)), this, SIGNAL(valuesModified()));
103   }
104   QVBoxLayout* aLayout = new QVBoxLayout(this);
105   ModuleBase_Tools::zeroMargins(aLayout);
106   aLayout->addWidget(myGroupBox);
107   setLayout(aLayout);
108 }
109
110 bool PartSet_WidgetPoint2D::resetCustom()
111 {
112   bool aDone = false;
113   if (!isUseReset() || isComputedDefault() || myXSpin->hasVariable() || myYSpin->hasVariable()) {
114     aDone = false;
115   }
116   else {
117     bool isOk;
118     double aDefValue = QString::fromStdString(getDefaultValue()).toDouble(&isOk);
119     // it is important to block the spin box control in order to do not through out the
120     // locking of the validating state.
121     ModuleBase_Tools::setSpinValue(myXSpin, isOk ? aDefValue : 0.0);
122     ModuleBase_Tools::setSpinValue(myYSpin, isOk ? aDefValue : 0.0);
123     storeValueCustom();
124     aDone = true;
125   }
126   return aDone;
127 }
128
129 PartSet_WidgetPoint2D::~PartSet_WidgetPoint2D()
130 {
131 }
132
133 bool PartSet_WidgetPoint2D::setSelection(QList<ModuleBase_ViewerPrs>& theValues,
134                                          const bool theToValidate)
135 {
136   if (theValues.empty())
137     return false;
138
139   ModuleBase_ViewerPrs aValue = theValues.takeFirst();
140
141   Handle(V3d_View) aView = myWorkshop->viewer()->activeView();
142   bool isDone = false;
143   TopoDS_Shape aShape = aValue.shape();
144   double aX, aY;
145   if (getPoint2d(aView, aShape, aX, aY)) {
146     isDone = setPoint(aX, aY);
147   }
148   return isDone;
149 }
150
151 bool PartSet_WidgetPoint2D::setPoint(double theX, double theY)
152 {
153   if (fabs(theX) >= MaxCoordinate)
154     return false;
155   if (fabs(theY) >= MaxCoordinate)
156     return false;
157
158   ModuleBase_Tools::setSpinValue(myXSpin, theX);
159   ModuleBase_Tools::setSpinValue(myYSpin, theY);
160
161   storeValue();
162   return true;
163 }
164
165 bool PartSet_WidgetPoint2D::storeValueCustom() const
166 {
167   std::shared_ptr<ModelAPI_Data> aData = myFeature->data();
168   if (!aData) // can be on abort of sketcher element
169     return false;
170   std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
171       aData->attribute(attributeID()));
172
173   PartSet_WidgetPoint2D* that = (PartSet_WidgetPoint2D*) this;
174   bool isBlocked = that->blockSignals(true);
175   bool isImmutable = aPoint->setImmutable(true);
176
177   // if text is not empty then setValue will be ignored
178   // so we should set the text at first
179   aPoint->setText(myXSpin->hasVariable() ? myXSpin->text().toStdString() : "",
180                   myYSpin->hasVariable() ? myYSpin->text().toStdString() : "");
181   aPoint->setValue(!myXSpin->hasVariable() ? myXSpin->value() : aPoint->x(),
182                    !myYSpin->hasVariable() ? myYSpin->value() : aPoint->y());
183
184   // after movement the solver will call the update event: optimization
185   moveObject(myFeature);
186   aPoint->setImmutable(isImmutable);
187   that->blockSignals(isBlocked);
188
189   return true;
190 }
191
192 bool PartSet_WidgetPoint2D::restoreValueCustom()
193 {
194   std::shared_ptr<ModelAPI_Data> aData = myFeature->data();
195   std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
196       aData->attribute(attributeID()));
197   QString aTextX = QString::fromStdString(aPoint->textX());
198   QString aTextY = QString::fromStdString(aPoint->textY());
199
200   bool isDouble = false;
201   double aVal = 0;
202   if (aTextX.isEmpty()) {
203     ModuleBase_Tools::setSpinValue(myXSpin, aPoint->x());
204   } else {
205     aVal = aTextX.toDouble(&isDouble);
206     if (isDouble)
207       ModuleBase_Tools::setSpinValue(myXSpin, aVal);
208     else
209       ModuleBase_Tools::setSpinText(myXSpin, aTextX);
210   }
211   if (aTextY.isEmpty()) {
212     ModuleBase_Tools::setSpinValue(myYSpin, aPoint->y());
213   } else {
214     aVal = aTextY.toDouble(&isDouble);
215     if (isDouble)
216       ModuleBase_Tools::setSpinValue(myYSpin, aVal);
217     else
218       ModuleBase_Tools::setSpinText(myYSpin, aTextY);
219   }
220   //if (aTextX.empty() || aTextY.empty()) {
221   //  ModuleBase_Tools::setSpinValue(myXSpin, aPoint->x());
222   //  ModuleBase_Tools::setSpinValue(myYSpin, aPoint->y());
223   //} else {
224   //  ModuleBase_Tools::setSpinText(myXSpin, QString::fromStdString(aTextX));
225   //  ModuleBase_Tools::setSpinText(myYSpin, QString::fromStdString(aTextY));
226   //}
227   return true;
228 }
229
230 QList<QWidget*> PartSet_WidgetPoint2D::getControls() const
231 {
232   QList<QWidget*> aControls;
233   aControls.append(myXSpin);
234   aControls.append(myYSpin);
235   return aControls;
236 }
237
238
239 void PartSet_WidgetPoint2D::activateCustom()
240 {
241   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
242   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)), 
243           this, SLOT(onMouseMove(ModuleBase_IViewWindow*, QMouseEvent*)));
244   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)), 
245           this, SLOT(onMouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)));
246
247   QIntList aModes;
248   aModes << TopAbs_VERTEX;
249   aModes << TopAbs_EDGE;
250   myWorkshop->activateSubShapesSelection(aModes);
251 }
252
253 void PartSet_WidgetPoint2D::deactivate()
254 {
255   ModuleBase_ModelWidget::deactivate();
256   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
257   disconnect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
258              this, SLOT(onMouseMove(ModuleBase_IViewWindow*, QMouseEvent*)));
259   disconnect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)), 
260              this, SLOT(onMouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)));
261
262   myWorkshop->deactivateSubShapesSelection();
263 }
264
265 bool PartSet_WidgetPoint2D::getPoint2d(const Handle(V3d_View)& theView, 
266                                        const TopoDS_Shape& theShape, 
267                                        double& theX, double& theY) const
268 {
269   if (!theShape.IsNull()) {
270     if (theShape.ShapeType() == TopAbs_VERTEX) {
271       const TopoDS_Vertex& aVertex = TopoDS::Vertex(theShape);
272       if (!aVertex.IsNull()) {
273         // A case when point is taken from existing vertex
274         gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
275         PartSet_Tools::convertTo2D(aPoint, mySketch, theView, theX, theY);
276         return true;
277       }
278     }
279   }
280   return false;
281 }
282
283 void PartSet_WidgetPoint2D::setConstraintWith(const ObjectPtr& theObject)
284 {
285   // Create point-edge coincedence
286   FeaturePtr aFeature = mySketch->addFeature(SketchPlugin_ConstraintCoincidence::ID());
287   std::shared_ptr<ModelAPI_Data> aData = aFeature->data();
288
289   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef1 = std::dynamic_pointer_cast<
290       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
291   AttributePtr aThisAttr = feature()->data()->attribute(attributeID());
292   std::shared_ptr<GeomDataAPI_Point2D> aThisPoint = 
293     std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aThisAttr);
294   aRef1->setAttr(aThisPoint);
295
296   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef2 = std::dynamic_pointer_cast<
297       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
298   aRef2->setObject(theObject);
299
300   aFeature->execute();
301 }
302
303 void PartSet_WidgetPoint2D::onMouseRelease(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
304 {
305   // the contex menu release by the right button should not be processed by this widget
306   if (theEvent->button() != Qt::LeftButton)
307     return;
308
309   ModuleBase_ISelection* aSelection = myWorkshop->selection();
310   Handle(V3d_View) aView = theWnd->v3dView();
311   // TODO: This fragment doesn't work because bug in OCC Viewer. It can be used after fixing.
312   NCollection_List<TopoDS_Shape> aShapes;
313   std::list<ObjectPtr> aObjects;
314   aSelection->selectedShapes(aShapes, aObjects);
315   // if we have selection
316   if (aShapes.Extent() > 0) {
317     TopoDS_Shape aShape = aShapes.First();
318     ObjectPtr aObject = aObjects.front();
319     FeaturePtr aSelectedFeature = ModelAPI_Feature::feature(aObject);
320     bool anExternal = false;
321     if (aSelectedFeature.get() != NULL) {
322       std::shared_ptr<SketchPlugin_Feature> aSPFeature = 
323               std::dynamic_pointer_cast<SketchPlugin_Feature>(aSelectedFeature);
324       if ((!aSPFeature) && (!aShape.IsNull())) {
325         anExternal = true;
326         ResultPtr aFixedObject = PartSet_Tools::findFixedObjectByExternal(aShape, aObject, mySketch);
327         if (!aFixedObject.get())
328           aObject = PartSet_Tools::createFixedObjectByExternal(aShape, aObject, mySketch);
329
330         double aX, aY;
331         if (getPoint2d(aView, aShape, aX, aY) && isFeatureContainsPoint(myFeature, aX, aY)) {
332           // do not create a constraint to the point, which already used by the feature
333           // if the feature contains the point, focus is not switched
334           setPoint(aX, aY);
335         }
336         else {
337           if (getPoint2d(aView, aShape, aX, aY))
338             setPoint(aX, aY);
339           setConstraintWith(aObject);
340           emit vertexSelected();
341           emit focusOutWidget(this);
342         }
343       }
344     }
345     if (!anExternal) {
346       double aX, aY;
347       bool isProcessed = false;
348       if (getPoint2d(aView, aShape, aX, aY) && isFeatureContainsPoint(myFeature, aX, aY)) {
349         // when the point is selected, the coordinates of the point should be set into the attribute
350         // if the feature contains the point, focus is not switched
351         setPoint(aX, aY);
352       }
353       else {
354         // do not set a coincidence constraint in the attribute if the feature contains a point
355         // with the same coordinates. It is important for line creation in order to do not set
356         // the same constraints for the same points, oterwise the result line has zero length.
357         if (getPoint2d(aView, aShape, aX, aY)) {
358           setPoint(aX, aY);
359           PartSet_Tools::setConstraints(mySketch, feature(), attributeID(), aX, aY);
360         }
361         else if (aShape.ShapeType() == TopAbs_EDGE) {
362           if (MyFeaturesForCoincedence.contains(myFeature->getKind().c_str()))
363             setConstraintWith(aObject);
364         }
365         // it is important to perform updateObject() in order to the current value is 
366         // processed by Sketch Solver. Test case: line is created from a previous point
367         // to some distance, but in the area of the highlighting of the point. Constraint
368         // coincidence is created, after the solver is performed, the distance between the
369         // points of the line becomes less than the tolerance. Validator of the line returns
370         // false, the line will be aborted, but sketch stays valid.
371         updateObject(feature());
372         emit vertexSelected();
373         emit focusOutWidget(this);
374       }
375     }
376   }
377   // End of Bug dependent fragment
378   else {
379     // A case when point is taken from mouse event
380     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWnd->v3dView());
381     double aX, anY;
382     PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, anY);
383
384     // if the feature contains the point, focus is not switched
385     if (!setPoint(aX, anY) || isFeatureContainsPoint(myFeature, aX, anY))
386       return;
387
388     /// Start alternative code
389     //std::shared_ptr<GeomDataAPI_Point2D> aFeaturePoint = std::dynamic_pointer_cast<
390     //    GeomDataAPI_Point2D>(feature()->data()->attribute(attributeID()));
391     //QList<FeaturePtr> aIgnore;
392     //aIgnore.append(feature());
393
394     //double aTolerance = aView->Convert(7);
395     //std::shared_ptr<GeomDataAPI_Point2D> aAttrPnt = 
396     //  PartSet_Tools::findAttributePoint(mySketch, aX, anY, aTolerance, aIgnore);
397     //if (aAttrPnt.get() != NULL) {
398     //  aFeaturePoint->setValue(aAttrPnt->pnt());
399     //  PartSet_Tools::createConstraint(mySketch, aAttrPnt, aFeaturePoint);
400     //  emit vertexSelected();
401     //}
402     /// End alternative code
403     emit focusOutWidget(this);
404   }
405 }
406
407
408 void PartSet_WidgetPoint2D::onMouseMove(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
409 {
410   if (isEditingMode())
411     return;
412
413   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWnd->v3dView());
414
415   double aX, anY;
416   PartSet_Tools::convertTo2D(aPoint, mySketch, theWnd->v3dView(), aX, anY);
417   // we need to block the value state change 
418   bool isBlocked = blockValueState(true);
419   setPoint(aX, anY);
420   blockValueState(isBlocked);
421   setValueState(ModifiedInViewer);
422 }
423
424 double PartSet_WidgetPoint2D::x() const
425 {
426   return myXSpin->value();
427 }
428
429 double PartSet_WidgetPoint2D::y() const
430 {
431   return myYSpin->value();
432 }
433
434
435 bool PartSet_WidgetPoint2D::isFeatureContainsPoint(const FeaturePtr& theFeature,
436                                                    double theX, double theY)
437 {
438   bool aPointIsFound = false;
439   AttributePtr aWidgetAttribute = myFeature->attribute(attributeID());
440
441   std::shared_ptr<GeomAPI_Pnt2d> aPnt2d = 
442                                     std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(theX, theY));
443   std::list<AttributePtr> anAttributes =
444                                 myFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
445   std::list<AttributePtr>::iterator anIter = anAttributes.begin();
446   for(; anIter != anAttributes.end() && !aPointIsFound; anIter++) {
447     AttributePoint2DPtr aPoint2DAttribute =
448       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
449     if (aPoint2DAttribute == aWidgetAttribute)
450       continue;
451     if (aPoint2DAttribute.get() && aPoint2DAttribute->isInitialized()) {
452       aPointIsFound = aPoint2DAttribute->pnt()->isEqual(aPnt2d);
453     }
454   }
455   return aPointIsFound;
456 }
457
458 /*void PartSet_WidgetPoint2D::onValuesChanged()
459 {
460   emit valuesChanged();
461 }*/
462
463 bool PartSet_WidgetPoint2D::processEnter()
464 {
465   bool isModified = myXSpin->isModified() || myYSpin->isModified();
466   if (isModified) {
467     bool isXModified = myXSpin->isModified();
468     emit valuesChanged();
469     //onValuesChanged();
470     myXSpin->clearModified();
471     myYSpin->clearModified();
472     if (isXModified)
473       myXSpin->selectAll();
474     else
475       myYSpin->selectAll();
476   }
477   return isModified;
478 }