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