Salome HOME
Issue #1860: fix end lines with spaces
[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_SketcherReetntrantMgr.h>
11
12 #include <XGUI_Tools.h>
13 #include <XGUI_Workshop.h>
14 #include <XGUI_Displayer.h>
15
16 #include <ModuleBase_ParamSpinBox.h>
17 #include <ModuleBase_Tools.h>
18 #include <ModuleBase_IViewer.h>
19 #include <ModuleBase_IViewWindow.h>
20 #include <ModuleBase_ISelection.h>
21 #include <ModuleBase_ViewerPrs.h>
22 #include <ModuleBase_WidgetValidator.h>
23
24 #include <Config_Keywords.h>
25 #include <Config_WidgetAPI.h>
26
27 #include <Events_Loop.h>
28 #include <ModelAPI_Events.h>
29 #include <ModelAPI_AttributeBoolean.h>
30
31 #include <ModelAPI_Feature.h>
32 #include <ModelAPI_Data.h>
33 #include <ModelAPI_Object.h>
34 #include <GeomDataAPI_Point2D.h>
35 #include <GeomAPI_Pnt2d.h>
36
37 #include <GeomAPI_ShapeExplorer.h>
38 #include <GeomAPI_Vertex.h>
39
40 #include <SketchPlugin_Feature.h>
41 #include <SketchPlugin_ConstraintCoincidence.h>
42 #include <SketchPlugin_Line.h>
43 #include <SketchPlugin_Arc.h>
44 #include <SketchPlugin_Circle.h>
45 #include <SketchPlugin_Point.h>
46
47 #include <QGroupBox>
48 #include <QGridLayout>
49 #include <QLabel>
50 #include <QEvent>
51 #include <QMouseEvent>
52 #include <QApplication>
53
54 #include <TopoDS.hxx>
55 #include <TopoDS_Vertex.hxx>
56 #include <BRep_Tool.hxx>
57
58 #include <cfloat>
59 #include <climits>
60
61 const double MaxCoordinate = 1e12;
62
63 static QStringList MyFeaturesForCoincedence;
64
65 PartSet_WidgetPoint2D::PartSet_WidgetPoint2D(QWidget* theParent,
66                                              ModuleBase_IWorkshop* theWorkshop,
67                                              const Config_WidgetAPI* theData)
68 : ModuleBase_ModelWidget(theParent, theData), myWorkshop(theWorkshop),
69   myValueIsCashed(false), myIsFeatureVisibleInCash(true),
70   myXValueInCash(0), myYValueInCash(0)
71 {
72   if (MyFeaturesForCoincedence.isEmpty()) {
73     MyFeaturesForCoincedence << SketchPlugin_Line::ID().c_str()
74       << SketchPlugin_Arc::ID().c_str()
75       << SketchPlugin_Point::ID().c_str()
76       << SketchPlugin_Circle::ID().c_str();
77   }
78
79   // the control should accept the focus, so the boolean flag is corrected to be true
80   myIsObligatory = true;
81   QString aPageName = QString::fromStdString(theData->getProperty(CONTAINER_PAGE_NAME));
82   myGroupBox = new QGroupBox(aPageName, theParent);
83   myGroupBox->setFlat(false);
84
85   bool aAcceptVariables = theData->getBooleanAttribute(DOUBLE_WDG_ACCEPT_EXPRESSIONS, true);
86
87   QGridLayout* aGroupLay = new QGridLayout(myGroupBox);
88   ModuleBase_Tools::adjustMargins(aGroupLay);
89   aGroupLay->setSpacing(2);
90   aGroupLay->setColumnStretch(1, 1);
91   {
92     QLabel* aLabel = new QLabel(myGroupBox);
93     aLabel->setText(tr("X "));
94     aGroupLay->addWidget(aLabel, 0, 0);
95
96     myXSpin = new ModuleBase_ParamSpinBox(myGroupBox);
97     myXSpin->setAcceptVariables(aAcceptVariables);
98     myXSpin->setMinimum(-DBL_MAX);
99     myXSpin->setMaximum(DBL_MAX);
100     myXSpin->setToolTip(tr("X"));
101     aGroupLay->addWidget(myXSpin, 0, 1);
102
103     connect(myXSpin, SIGNAL(textChanged(const QString&)), this, SIGNAL(valuesModified()));
104     myXSpin->setValueEnabled(isValueEnabled());
105   }
106   {
107     QLabel* aLabel = new QLabel(myGroupBox);
108     aLabel->setText(tr("Y "));
109     aGroupLay->addWidget(aLabel, 1, 0);
110
111     myYSpin = new ModuleBase_ParamSpinBox(myGroupBox);
112     myYSpin->setAcceptVariables(aAcceptVariables);
113     myYSpin->setMinimum(-DBL_MAX);
114     myYSpin->setMaximum(DBL_MAX);
115     myYSpin->setToolTip(tr("Y"));
116     aGroupLay->addWidget(myYSpin, 1, 1);
117
118     connect(myYSpin, SIGNAL(textChanged(const QString&)), this, SIGNAL(valuesModified()));
119     myYSpin->setValueEnabled(isValueEnabled());
120   }
121   QVBoxLayout* aLayout = new QVBoxLayout(this);
122   ModuleBase_Tools::zeroMargins(aLayout);
123   aLayout->addWidget(myGroupBox);
124   setLayout(aLayout);
125
126   myWidgetValidator = new ModuleBase_WidgetValidator(this, myWorkshop);
127 }
128
129 bool PartSet_WidgetPoint2D::isValidSelectionCustom(const ModuleBase_ViewerPrsPtr& theValue)
130 {
131   bool aValid = true;
132
133   PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
134   if (aModule->sketchReentranceMgr()->isInternalEditActive())
135     return true; /// when internal edit is started a new feature is created. I has not results, AIS
136
137   /// the selection is not possible if the current feature has no presentation for the current
138   /// attribute not in AIS not in results. If so, no object in current feature where make
139   /// coincidence, so selection is not necessary
140   bool aFoundPoint = false;
141   GeomShapePtr anAISShape;
142   GeomPresentablePtr aPrs = std::dynamic_pointer_cast<GeomAPI_IPresentable>(myFeature);
143   if (aPrs.get()) {
144     AISObjectPtr anAIS;
145     anAIS = aPrs->getAISObject(anAIS);
146     if (anAIS.get()) {
147       anAISShape = anAIS->getShape();
148     }
149   }
150   const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = myFeature->results();
151   if (!anAISShape.get() && aResults.empty())
152     return true;
153
154   /// analysis of AIS
155   std::shared_ptr<ModelAPI_Data> aData = myFeature->data();
156   std::shared_ptr<GeomDataAPI_Point2D> aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
157       aData->attribute(attributeID()));
158   std::shared_ptr<GeomAPI_Pnt2d> aPoint = aPointAttr->pnt();
159   if (anAISShape.get())
160     aFoundPoint = shapeContainsPoint(anAISShape, aPoint, mySketch);
161
162   /// analysis of results
163   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
164   for (; aRIter != aResults.cend() && !aFoundPoint; aRIter++) {
165     ResultPtr aResult = *aRIter;
166     if (aResult.get() && aResult->shape().get()) {
167       GeomShapePtr aShape = aResult->shape();
168       aFoundPoint = shapeContainsPoint(aShape, aPoint, mySketch);
169     }
170   }
171   return aFoundPoint;
172 }
173
174 bool PartSet_WidgetPoint2D::resetCustom()
175 {
176   bool aDone = false;
177   if (!isUseReset() || isComputedDefault() || myXSpin->hasVariable() || myYSpin->hasVariable()) {
178     aDone = false;
179   }
180   else {
181     if (myValueIsCashed) {
182       // if the restored value should be hidden, aDone = true to set
183       // reset state for the widget in the parent
184       aDone = restoreCurentValue();
185       emit objectUpdated();
186     }
187     else {
188       bool isOk;
189       double aDefValue = QString::fromStdString(getDefaultValue()).toDouble(&isOk);
190       // it is important to block the spin box control in order to do not through out the
191       // locking of the validating state.
192       ModuleBase_Tools::setSpinValue(myXSpin, isOk ? aDefValue : 0.0);
193       ModuleBase_Tools::setSpinValue(myYSpin, isOk ? aDefValue : 0.0);
194       storeValueCustom();
195       aDone = true;
196     }
197   }
198   return aDone;
199 }
200
201 PartSet_WidgetPoint2D::~PartSet_WidgetPoint2D()
202 {
203 }
204
205 bool PartSet_WidgetPoint2D::setSelection(QList<ModuleBase_ViewerPrsPtr>& theValues,
206                                          const bool theToValidate)
207 {
208   bool isDone = false;
209   if (theValues.empty())
210     return isDone;
211
212   ModuleBase_ViewerPrsPtr aValue = theValues.takeFirst();
213   GeomShapePtr aShape = aValue->shape();
214   if (aShape.get() && !aShape->isNull()) {
215     Handle(V3d_View) aView = myWorkshop->viewer()->activeView();
216     double aX, aY;
217     const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
218     if (getPoint2d(aView, aTDShape, aX, aY)) {
219       isDone = setPoint(aX, aY);
220       PartSet_Tools::setConstraints(mySketch, feature(), attributeID(), aX, aY);
221     }
222   }
223   return isDone;
224 }
225
226 void PartSet_WidgetPoint2D::selectContent()
227 {
228   myXSpin->selectAll();
229 }
230
231 bool PartSet_WidgetPoint2D::setPoint(double theX, double theY)
232 {
233   if (fabs(theX) >= MaxCoordinate)
234     return false;
235   if (fabs(theY) >= MaxCoordinate)
236     return false;
237
238   ModuleBase_Tools::setSpinValue(myXSpin, theX);
239   ModuleBase_Tools::setSpinValue(myYSpin, theY);
240
241   storeValue();
242   return true;
243 }
244
245 bool PartSet_WidgetPoint2D::storeValueCustom()
246 {
247   std::shared_ptr<ModelAPI_Data> aData = myFeature->data();
248   if (!aData) // can be on abort of sketcher element
249     return false;
250   std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
251       aData->attribute(attributeID()));
252
253   PartSet_WidgetPoint2D* that = (PartSet_WidgetPoint2D*) this;
254   bool isBlocked = that->blockSignals(true);
255   bool isImmutable = aPoint->setImmutable(true);
256
257   // if text is not empty then setValue will be ignored
258   // so we should set the text at first
259   aPoint->setText(myXSpin->hasVariable() ? myXSpin->text().toStdString() : "",
260                   myYSpin->hasVariable() ? myYSpin->text().toStdString() : "");
261   aPoint->setValue(!myXSpin->hasVariable() ? myXSpin->value() : aPoint->x(),
262                    !myYSpin->hasVariable() ? myYSpin->value() : aPoint->y());
263
264   // after movement the solver will call the update event: optimization
265   moveObject(myFeature);
266   aPoint->setImmutable(isImmutable);
267   that->blockSignals(isBlocked);
268
269   return true;
270 }
271
272 bool PartSet_WidgetPoint2D::restoreValueCustom()
273 {
274   std::shared_ptr<ModelAPI_Data> aData = myFeature->data();
275   std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
276       aData->attribute(attributeID()));
277   QString aTextX = QString::fromStdString(aPoint->isInitialized() ? aPoint->textX() : "0");
278   QString aTextY = QString::fromStdString(aPoint->isInitialized() ? aPoint->textY() : "0");
279
280   bool isDouble = false;
281   double aVal = 0;
282   if (aTextX.isEmpty()) {
283     ModuleBase_Tools::setSpinValue(myXSpin, aPoint->x());
284   } else {
285     aVal = aTextX.toDouble(&isDouble);
286     if (isDouble)
287       ModuleBase_Tools::setSpinValue(myXSpin, aVal);
288     else
289       ModuleBase_Tools::setSpinText(myXSpin, aTextX);
290   }
291   if (aTextY.isEmpty()) {
292     ModuleBase_Tools::setSpinValue(myYSpin, aPoint->y());
293   } else {
294     aVal = aTextY.toDouble(&isDouble);
295     if (isDouble)
296       ModuleBase_Tools::setSpinValue(myYSpin, aVal);
297     else
298       ModuleBase_Tools::setSpinText(myYSpin, aTextY);
299   }
300   //if (aTextX.empty() || aTextY.empty()) {
301   //  ModuleBase_Tools::setSpinValue(myXSpin, aPoint->x());
302   //  ModuleBase_Tools::setSpinValue(myYSpin, aPoint->y());
303   //} else {
304   //  ModuleBase_Tools::setSpinText(myXSpin, QString::fromStdString(aTextX));
305   //  ModuleBase_Tools::setSpinText(myYSpin, QString::fromStdString(aTextY));
306   //}
307   return true;
308 }
309
310 void PartSet_WidgetPoint2D::storeCurentValue()
311 {
312   // do not use cash if a variable is used
313   if (myXSpin->hasVariable() || myYSpin->hasVariable())
314     return;
315
316   myValueIsCashed = true;
317   myIsFeatureVisibleInCash = XGUI_Displayer::isVisible(
318                        XGUI_Tools::workshop(myWorkshop)->displayer(), myFeature);
319   myXValueInCash = myXSpin->value();
320   myYValueInCash = myYSpin->value();
321 }
322
323 bool PartSet_WidgetPoint2D::restoreCurentValue()
324 {
325   bool aRestoredAndHidden = true;
326
327   bool isVisible = myIsFeatureVisibleInCash;
328   // fill the control widgets by the cashed value
329
330   myValueIsCashed = false;
331   myIsFeatureVisibleInCash = true;
332   ModuleBase_Tools::setSpinValue(myXSpin, myXValueInCash);
333   ModuleBase_Tools::setSpinValue(myYSpin, myYValueInCash);
334
335   // store value to the model
336   storeValueCustom();
337   if (isVisible) {
338     setValueState(Stored);
339     aRestoredAndHidden = false;
340   }
341   else
342     aRestoredAndHidden = true;
343
344   return aRestoredAndHidden;
345 }
346
347 QList<QWidget*> PartSet_WidgetPoint2D::getControls() const
348 {
349   QList<QWidget*> aControls;
350   aControls.append(myXSpin);
351   aControls.append(myYSpin);
352   return aControls;
353 }
354
355
356 void PartSet_WidgetPoint2D::activateCustom()
357 {
358   QIntList aModes;
359   aModes << TopAbs_VERTEX;
360   aModes << TopAbs_EDGE;
361   myWorkshop->activateSubShapesSelection(aModes);
362
363   if (!isEditingMode()) {
364     FeaturePtr aFeature = feature();
365     if (aFeature.get() && aFeature->getKind() == SketchPlugin_Point::ID())
366       storeValue();
367   }
368 }
369
370 void PartSet_WidgetPoint2D::deactivate()
371 {
372   // the value of the control should be stored to model if it was not
373   // initialized yet. It is important when we leave this control by Tab key.
374   // It should not be performed by the widget activation as the preview
375   // is visualized with default value. Line point is moved to origin.
376   AttributePtr anAttribute = myFeature->data()->attribute(attributeID());
377   if (anAttribute && !anAttribute->isInitialized())
378     storeValue();
379
380   ModuleBase_ModelWidget::deactivate();
381   myWorkshop->deactivateSubShapesSelection();
382 }
383
384 bool PartSet_WidgetPoint2D::getPoint2d(const Handle(V3d_View)& theView,
385                                        const TopoDS_Shape& theShape,
386                                        double& theX, double& theY) const
387 {
388   if (!theShape.IsNull()) {
389     if (theShape.ShapeType() == TopAbs_VERTEX) {
390       const TopoDS_Vertex& aVertex = TopoDS::Vertex(theShape);
391       if (!aVertex.IsNull()) {
392         // A case when point is taken from existing vertex
393         gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
394         PartSet_Tools::convertTo2D(aPoint, mySketch, theView, theX, theY);
395         return true;
396       }
397     }
398   }
399   return false;
400 }
401
402 bool PartSet_WidgetPoint2D::setConstraintWith(const ObjectPtr& theObject)
403 {
404   std::shared_ptr<GeomDataAPI_Point2D> aFeaturePoint;
405   if (feature()->isMacro()) {
406     AttributePtr aThisAttr = feature()->data()->attribute(attributeID());
407     std::shared_ptr<GeomDataAPI_Point2D> anAttrPoint =
408                                std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aThisAttr);
409     if (anAttrPoint.get()) {
410       // the macro feature will be removed after the operation is stopped, so we need to build
411       // coicidence to possible sub-features
412       aFeaturePoint = PartSet_Tools::findFirstEqualPointInArgumentFeatures(feature(),
413                                                                  anAttrPoint->pnt());
414     }
415   }
416   else {
417     AttributePtr aThisAttr = feature()->data()->attribute(attributeID());
418     aFeaturePoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aThisAttr);
419   }
420   if (!aFeaturePoint.get())
421     return false;
422
423   // Create point-edge coincedence
424   FeaturePtr aFeature = mySketch->addFeature(SketchPlugin_ConstraintCoincidence::ID());
425   std::shared_ptr<ModelAPI_Data> aData = aFeature->data();
426
427   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef1 = std::dynamic_pointer_cast<
428       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
429
430   aRef1->setAttr(aFeaturePoint);
431
432   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef2 = std::dynamic_pointer_cast<
433       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
434   aRef2->setObject(theObject);
435
436   // we need to flush created signal in order to coincidence is processed by solver
437   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
438
439   return true;
440 }
441
442 void PartSet_WidgetPoint2D::mouseReleased(ModuleBase_IViewWindow* theWindow, QMouseEvent* theEvent)
443 {
444   // the contex menu release by the right button should not be processed by this widget
445   if (theEvent->button() != Qt::LeftButton)
446     return;
447
448   ModuleBase_ISelection* aSelection = myWorkshop->selection();
449   Handle(V3d_View) aView = theWindow->v3dView();
450
451   QList<ModuleBase_ViewerPrsPtr> aList = aSelection->getSelected(ModuleBase_ISelection::Viewer);
452   ModuleBase_ViewerPrsPtr aFirstValue =
453     aList.size() > 0 ? aList.first() : ModuleBase_ViewerPrsPtr();
454   if (!aFirstValue.get() && myPreSelected.get()) {
455     aFirstValue = myPreSelected;
456   }
457   // if we have selection and use it
458   if (aFirstValue.get() && isValidSelectionCustom(aFirstValue)) {
459     GeomShapePtr aGeomShape = aFirstValue->shape();
460     TopoDS_Shape aShape = aGeomShape->impl<TopoDS_Shape>();
461     ObjectPtr aObject = aFirstValue->object();
462
463     FeaturePtr aSelectedFeature = ModelAPI_Feature::feature(aObject);
464     bool anExternal = false;
465     std::shared_ptr<SketchPlugin_Feature> aSPFeature;
466     if (aSelectedFeature.get() != NULL)
467       aSPFeature = std::dynamic_pointer_cast<SketchPlugin_Feature>(aSelectedFeature);
468       if ((!aSPFeature && !aShape.IsNull()) ||
469           (aSPFeature.get() && aSPFeature->isExternal())) {
470         ResultPtr aFixedObject;
471         anExternal = true;
472         aFixedObject = PartSet_Tools::findFixedObjectByExternal(aShape, aObject, mySketch);
473         if (!aFixedObject.get())
474           aFixedObject = PartSet_Tools::createFixedObjectByExternal(aShape, aObject, mySketch);
475         double aX, aY;
476         if (getPoint2d(aView, aShape, aX, aY) && isFeatureContainsPoint(myFeature, aX, aY)) {
477           // do not create a constraint to the point, which already used by the feature
478           // if the feature contains the point, focus is not switched
479           setPoint(aX, aY);
480         }
481         else {
482           if (getPoint2d(aView, aShape, aX, aY))
483             setPoint(aX, aY);
484           else
485             setValueState(Stored); // in case of edge selection, Apply state should also be updated
486           bool anOrphanPoint = aShape.ShapeType() == TopAbs_VERTEX ||
487                                isOrphanPoint(aSelectedFeature, mySketch, aX, aY);
488           if (anExternal) {
489             // we should not stop reentrant operation on external objects because
490             anOrphanPoint = true;
491             // they are not participate in the contour creation excepting external vertices
492             if (aShape.ShapeType() == TopAbs_VERTEX) {
493               FeaturePtr aFixedFeature = ModelAPI_Feature::feature(aFixedObject);
494               if (aFixedFeature.get() && aFixedFeature->getKind() == SketchPlugin_Point::ID()) {
495                 anOrphanPoint = isOrphanPoint(aFixedFeature, mySketch, aX, aY);
496               }
497             }
498             else {
499               // point is taken from mouse event and set in attribute.
500               // It should be done before setting
501               // coinident constraint to the external line. If a point is created, it should be
502               // in the mouse clicked point
503               gp_Pnt aPoint =
504                 PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
505               double aX, anY;
506               PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, anY);
507               setPoint(aX, anY);
508             }
509           }
510           if (aFixedObject.get())
511             setConstraintWith(aFixedObject);
512           // fignal updated should be flushed in order to visualize possible created
513           // external objects e.g. selection of trihedron axis when input end arc point
514           updateObject(feature());
515
516           if (!anOrphanPoint)
517             emit vertexSelected(); // it stops the reentrant operation
518
519           emit focusOutWidget(this);
520         }
521       }
522     if (!anExternal) {
523       double aX, aY;
524       bool isProcessed = false;
525       if (getPoint2d(aView, aShape, aX, aY) && isFeatureContainsPoint(myFeature, aX, aY)) {
526         // when the point is selected, the coordinates of the point should be set into the attribute
527         // if the feature contains the point, focus is not switched
528         setPoint(aX, aY);
529       }
530       else {
531         bool anOrphanPoint = isOrphanPoint(aSelectedFeature, mySketch, aX, aY);
532         // do not set a coincidence constraint in the attribute if the feature contains a point
533         // with the same coordinates. It is important for line creation in order to do not set
534         // the same constraints for the same points, oterwise the result line has zero length.
535         bool isAuxiliaryFeature = false;
536         if (getPoint2d(aView, aShape, aX, aY)) {
537           setPoint(aX, aY);
538           feature()->execute();
539           PartSet_Tools::setConstraints(mySketch, feature(), attributeID(), aX, aY);
540         }
541         else if (aShape.ShapeType() == TopAbs_EDGE) {
542           // point is taken from mouse event and set in attribute. It should be done before setting
543           // coinident constraint to the external line. If a point is created, it should be in
544           // the mouse clicked point
545           gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
546           PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, aY);
547           setPoint(aX, aY);
548           setConstraintWith(aObject);
549           setValueState(Stored); // in case of edge selection, Apply state should also be updated
550           isAuxiliaryFeature = PartSet_Tools::isAuxiliarySketchEntity(aObject);
551         }
552         // it is important to perform updateObject() in order to the current value is
553         // processed by Sketch Solver. Test case: line is created from a previous point
554         // to some distance, but in the area of the highlighting of the point. Constraint
555         // coincidence is created, after the solver is performed, the distance between the
556         // points of the line becomes less than the tolerance. Validator of the line returns
557         // false, the line will be aborted, but sketch stays valid.
558         updateObject(feature());
559         if (!anOrphanPoint && !anExternal && !isAuxiliaryFeature)
560           emit vertexSelected();
561         emit focusOutWidget(this);
562       }
563     }
564   }
565   // End of Bug dependent fragment
566   else {
567     // A case when point is taken from mouse event
568     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
569     double aX, anY;
570     PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, anY);
571
572     // if the feature contains the point, focus is not switched
573     if (!setPoint(aX, anY) || isFeatureContainsPoint(myFeature, aX, anY))
574       return;
575
576     /// Start alternative code
577     //std::shared_ptr<GeomDataAPI_Point2D> aFeaturePoint = std::dynamic_pointer_cast<
578     //    GeomDataAPI_Point2D>(feature()->data()->attribute(attributeID()));
579     //QList<FeaturePtr> aIgnore;
580     //aIgnore.append(feature());
581
582     //double aTolerance = aView->Convert(7);
583     //std::shared_ptr<GeomDataAPI_Point2D> aAttrPnt =
584     //  PartSet_Tools::findAttributePoint(mySketch, aX, anY, aTolerance, aIgnore);
585     //if (aAttrPnt.get() != NULL) {
586     //  aFeaturePoint->setValue(aAttrPnt->pnt());
587     //  PartSet_Tools::createConstraint(mySketch, aAttrPnt, aFeaturePoint);
588     //  emit vertexSelected();
589     //}
590     /// End alternative code
591     emit focusOutWidget(this);
592   }
593 }
594
595 void PartSet_WidgetPoint2D::setPreSelection(
596   const std::shared_ptr<ModuleBase_ViewerPrs>& thePreSelected)
597 {
598   myPreSelected = thePreSelected;
599 }
600
601 void PartSet_WidgetPoint2D::mouseMoved(ModuleBase_IViewWindow* theWindow, QMouseEvent* theEvent)
602 {
603   PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
604
605   if (isEditingMode() || aModule->sketchReentranceMgr()->isInternalEditStarted())
606     return;
607
608   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
609
610   double aX, anY;
611   PartSet_Tools::convertTo2D(aPoint, mySketch, theWindow->v3dView(), aX, anY);
612   if (myState != ModifiedInViewer)
613     storeCurentValue();
614   // we need to block the value state change
615   bool isBlocked = blockValueState(true);
616   setPoint(aX, anY);
617   blockValueState(isBlocked);
618   setValueState(ModifiedInViewer);
619 }
620
621 double PartSet_WidgetPoint2D::x() const
622 {
623   return myXSpin->value();
624 }
625
626 double PartSet_WidgetPoint2D::y() const
627 {
628   return myYSpin->value();
629 }
630
631
632 bool PartSet_WidgetPoint2D::isFeatureContainsPoint(const FeaturePtr& theFeature,
633                                                    double theX, double theY)
634 {
635   bool aPointIsFound = false;
636
637   if (feature()->getKind() != SketchPlugin_Line::ID())
638     return aPointIsFound;
639
640   AttributePtr aWidgetAttribute = myFeature->attribute(attributeID());
641
642   std::shared_ptr<GeomAPI_Pnt2d> aPnt2d =
643                                     std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(theX, theY));
644   std::list<AttributePtr> anAttributes =
645                                 myFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
646   std::list<AttributePtr>::iterator anIter = anAttributes.begin();
647   for(; anIter != anAttributes.end() && !aPointIsFound; anIter++) {
648     AttributePoint2DPtr aPoint2DAttribute =
649       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
650     if (aPoint2DAttribute == aWidgetAttribute)
651       continue;
652     if (aPoint2DAttribute.get() && aPoint2DAttribute->isInitialized()) {
653       aPointIsFound = aPoint2DAttribute->pnt()->isEqual(aPnt2d);
654     }
655   }
656   return aPointIsFound;
657 }
658
659 void PartSet_WidgetPoint2D::initializeValueByActivate()
660 {
661 }
662
663 /*void PartSet_WidgetPoint2D::onValuesChanged()
664 {
665   emit valuesChanged();
666 }*/
667
668 bool PartSet_WidgetPoint2D::processEnter()
669 {
670   bool isModified = getValueState() == ModifiedInPP;
671   if (isModified) {
672     bool isXModified = myXSpin->hasFocus();
673     emit valuesChanged();
674     if (isXModified)
675       myXSpin->selectAll();
676     else
677       myYSpin->selectAll();
678   }
679   return isModified;
680 }
681
682 bool PartSet_WidgetPoint2D::useSelectedShapes() const
683 {
684   return true;
685 }
686
687 bool PartSet_WidgetPoint2D::isOrphanPoint(const FeaturePtr& theFeature,
688                                           const CompositeFeaturePtr& theSketch,
689                                           double theX, double theY)
690 {
691   bool anOrphanPoint = false;
692   if (theFeature.get()) {
693     std::shared_ptr<GeomDataAPI_Point2D> aPointAttr;
694     std::string aFeatureKind = theFeature->getKind();
695     if (aFeatureKind == SketchPlugin_Point::ID())
696       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
697                                        theFeature->attribute(SketchPlugin_Point::COORD_ID()));
698     else if (aFeatureKind == SketchPlugin_Circle::ID())
699       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
700                                        theFeature->attribute(SketchPlugin_Circle::CENTER_ID()));
701
702     else if (aFeatureKind == SketchPlugin_Arc::ID())
703       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
704                                        theFeature->attribute(SketchPlugin_Arc::CENTER_ID()));
705
706     /// check that the geometry point with the given coordinates is the checked point
707     /// e.g. in arc the (x,y) point can not coicide to the center point and it automatically
708     /// means that this point is not an orphant one.
709     if (aPointAttr.get()) {
710       std::shared_ptr<GeomAPI_Pnt2d> aCheckedPoint = std::shared_ptr<GeomAPI_Pnt2d>(
711                                                     new GeomAPI_Pnt2d(theX, theY));
712       if (!aCheckedPoint->isEqual(aPointAttr->pnt()))
713         return anOrphanPoint;
714     }
715
716     if (aPointAttr.get()) {
717       std::shared_ptr<GeomAPI_Pnt2d> aPoint = aPointAttr->pnt();
718       // we need to find coincidence features in results also, because external object(point)
719       // uses refs to me in another feature.
720       FeaturePtr aCoincidence = PartSet_Tools::findFirstCoincidence(theFeature, aPoint);
721       anOrphanPoint = true;
722       // if there is at least one concident line to the point, the point is not an orphant
723       if (aCoincidence.get()) {
724         QList<FeaturePtr> aCoinsideLines;
725         QList<FeaturePtr> aCoins;
726         PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines, aCoins,
727                                         SketchPlugin_ConstraintCoincidence::ENTITY_A());
728         PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines, aCoins,
729                                         SketchPlugin_ConstraintCoincidence::ENTITY_B());
730         QList<FeaturePtr>::const_iterator anIt = aCoinsideLines.begin(),
731                                           aLast = aCoinsideLines.end();
732         for (; anIt != aLast && anOrphanPoint; anIt++) {
733           anOrphanPoint = (*anIt)->getKind() != SketchPlugin_Line::ID();
734         }
735       }
736     }
737   }
738   return anOrphanPoint;
739 }
740
741 bool PartSet_WidgetPoint2D::shapeContainsPoint(const GeomShapePtr& theShape,
742                                                const std::shared_ptr<GeomAPI_Pnt2d>& thePoint,
743                                                const CompositeFeaturePtr& theSketch)
744 {
745   std::shared_ptr<GeomAPI_Pnt> aPoint = PartSet_Tools::point3D(thePoint, theSketch);
746
747   bool aContainPoint = false;
748   GeomAPI_ShapeExplorer anExp(theShape, GeomAPI_Shape::VERTEX);
749   for(; anExp.more() && !aContainPoint; anExp.next()) {
750     std::shared_ptr<GeomAPI_Shape> aVertexInCompSolid = anExp.current();
751     std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex(aVertexInCompSolid));
752     if (aVertex.get())
753       aContainPoint = aPoint->isEqual(aVertex->point());
754   }
755   return aContainPoint;
756 }