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