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