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