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