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