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 setting
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(), theWindow->v3dView());
600             PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, aY);
601             setPoint(aX, aY);
602           }
603           setValueState(Stored); // in case of edge selection, Apply state should also be updated
604         }
605         bool anOrphanPoint = aShape.ShapeType() == TopAbs_VERTEX ||
606                               isOrphanPoint(aSelectedFeature, mySketch, aX, aY);
607         if (anExternal) {
608           // we should not stop reentrant operation on external objects because
609           anOrphanPoint = true;
610           // they are not participate in the contour creation excepting external vertices
611           if (aShape.ShapeType() == TopAbs_VERTEX) {
612             FeaturePtr aFixedFeature = ModelAPI_Feature::feature(aFixedObject);
613             if (aFixedFeature.get() && aFixedFeature->getKind() == SketchPlugin_Point::ID()) {
614               anOrphanPoint = isOrphanPoint(aFixedFeature, mySketch, aX, aY);
615             }
616           }
617         }
618         if (aFixedObject.get())
619           setConstraintToObject(aFixedObject);
620         // fignal updated should be flushed in order to visualize possible created
621         // external objects e.g. selection of trihedron axis when input end arc point
622         updateObject(feature());
623
624         if (!anOrphanPoint)
625           emit vertexSelected(); // it stops the reentrant operation
626
627         emit focusOutWidget(this);
628       }
629     }
630     if (!anExternal) {
631       double aX, aY;
632       bool isProcessed = false;
633       if (getPoint2d(aView, aShape, aX, aY) && isFeatureContainsPoint(myFeature, aX, aY)) {
634         // when the point is selected, the coordinates of the point should be set into the attribute
635         // if the feature contains the point, focus is not switched
636         setPoint(aX, aY);
637       }
638       else {
639         bool anOrphanPoint = isOrphanPoint(aSelectedFeature, mySketch, aX, aY);
640         // do not set a coincidence constraint in the attribute if the feature contains a point
641         // with the same coordinates. It is important for line creation in order to do not set
642         // the same constraints for the same points, oterwise the result line has zero length.
643         bool isAuxiliaryFeature = false;
644         if (getPoint2d(aView, aShape, aX, aY)) {
645           setPoint(aX, aY);
646           setConstraintToPoint(aX, aY);
647         }
648         else if (aShape.ShapeType() == TopAbs_EDGE) {
649           // point is taken from mouse event and set in attribute. It should be done before setting
650           // coinident constraint to the external line. If a point is created, it should be in
651           // the mouse clicked point
652           gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
653           PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, aY);
654           setPoint(aX, aY);
655           setConstraintToObject(aObject);
656           setValueState(Stored); // in case of edge selection, Apply state should also be updated
657           isAuxiliaryFeature = PartSet_Tools::isAuxiliarySketchEntity(aObject);
658         }
659         // it is important to perform updateObject() in order to the current value is
660         // processed by Sketch Solver. Test case: line is created from a previous point
661         // to some distance, but in the area of the highlighting of the point. Constraint
662         // coincidence is created, after the solver is performed, the distance between the
663         // points of the line becomes less than the tolerance. Validator of the line returns
664         // false, the line will be aborted, but sketch stays valid.
665         updateObject(feature());
666         if (!anOrphanPoint && !anExternal && !isAuxiliaryFeature)
667           emit vertexSelected();
668         emit focusOutWidget(this);
669       }
670     }
671   }
672   // End of Bug dependent fragment
673   else {
674     // A case when point is taken from mouse event
675     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
676     double aX, anY;
677     PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, anY);
678
679     // if the feature contains the point, focus is not switched
680     if (!setPoint(aX, anY) || isFeatureContainsPoint(myFeature, aX, anY))
681       return;
682
683     emit focusOutWidget(this);
684   }
685 }
686
687 void PartSet_WidgetPoint2D::setPreSelection(
688                                const std::shared_ptr<ModuleBase_ViewerPrs>& thePreSelected,
689                                ModuleBase_IViewWindow* theWnd,
690                                QMouseEvent* theEvent)
691 {
692   myPreSelected = thePreSelected;
693   mouseReleased(theWnd, theEvent);
694   myPreSelected = ModuleBase_ViewerPrsPtr();
695 }
696
697 void PartSet_WidgetPoint2D::mouseMoved(ModuleBase_IViewWindow* theWindow, QMouseEvent* theEvent)
698 {
699   PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
700
701   if (isEditingMode() || aModule->sketchReentranceMgr()->isInternalEditActive())
702     return;
703
704   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
705
706   double aX, anY;
707   PartSet_Tools::convertTo2D(aPoint, mySketch, theWindow->v3dView(), aX, anY);
708   if (myState != ModifiedInViewer)
709     storeCurentValue();
710   // we need to block the value state change
711   bool isBlocked = blockValueState(true);
712   setPoint(aX, anY);
713   blockValueState(isBlocked);
714   setValueState(ModifiedInViewer);
715 }
716
717 double PartSet_WidgetPoint2D::x() const
718 {
719   return myXSpin->value();
720 }
721
722 double PartSet_WidgetPoint2D::y() const
723 {
724   return myYSpin->value();
725 }
726
727
728 bool PartSet_WidgetPoint2D::isFeatureContainsPoint(const FeaturePtr& theFeature,
729                                                    double theX, double theY)
730 {
731   bool aPointIsFound = false;
732
733   if (feature()->getKind() != SketchPlugin_Line::ID())
734     return aPointIsFound;
735
736   AttributePtr aWidgetAttribute = myFeature->attribute(attributeID());
737
738   std::shared_ptr<GeomAPI_Pnt2d> aPnt2d =
739                                     std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(theX, theY));
740   std::list<AttributePtr> anAttributes =
741                                 myFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
742   std::list<AttributePtr>::iterator anIter = anAttributes.begin();
743   for(; anIter != anAttributes.end() && !aPointIsFound; anIter++) {
744     AttributePoint2DPtr aPoint2DAttribute =
745       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
746     if (aPoint2DAttribute == aWidgetAttribute)
747       continue;
748     if (aPoint2DAttribute.get() && aPoint2DAttribute->isInitialized()) {
749       aPointIsFound = aPoint2DAttribute->pnt()->isEqual(aPnt2d);
750     }
751   }
752   return aPointIsFound;
753 }
754
755 void PartSet_WidgetPoint2D::initializeValueByActivate()
756 {
757 }
758
759 /*void PartSet_WidgetPoint2D::onValuesChanged()
760 {
761   emit valuesChanged();
762 }*/
763
764 bool PartSet_WidgetPoint2D::processEnter()
765 {
766   return false;
767   /*bool isModified = getValueState() == ModifiedInPP;
768   if (isModified) {
769     bool isXModified = myXSpin->hasFocus();
770     emit valuesChanged();
771     if (isXModified)
772       myXSpin->selectAll();
773     else
774       myYSpin->selectAll();
775   }
776   return isModified;*/
777 }
778
779 bool PartSet_WidgetPoint2D::useSelectedShapes() const
780 {
781   return true;
782 }
783
784 bool PartSet_WidgetPoint2D::isOrphanPoint(const FeaturePtr& theFeature,
785                                           const CompositeFeaturePtr& theSketch,
786                                           double theX, double theY)
787 {
788   bool anOrphanPoint = false;
789   if (theFeature.get()) {
790     AttributePoint2DPtr aPointAttr;
791     std::string aFeatureKind = theFeature->getKind();
792     if (aFeatureKind == SketchPlugin_Point::ID())
793       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
794                                        theFeature->attribute(SketchPlugin_Point::COORD_ID()));
795     else if (aFeatureKind == SketchPlugin_Circle::ID())
796       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
797                                        theFeature->attribute(SketchPlugin_Circle::CENTER_ID()));
798
799     else if (aFeatureKind == SketchPlugin_Arc::ID())
800       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
801                                        theFeature->attribute(SketchPlugin_Arc::CENTER_ID()));
802
803     /// check that the geometry point with the given coordinates is the checked point
804     /// e.g. in arc the (x,y) point can not coicide to the center point and it automatically
805     /// means that this point is not an orphant one.
806     if (aPointAttr.get()) {
807       std::shared_ptr<GeomAPI_Pnt2d> aCheckedPoint = std::shared_ptr<GeomAPI_Pnt2d>(
808                                                     new GeomAPI_Pnt2d(theX, theY));
809       if (!aCheckedPoint->isEqual(aPointAttr->pnt()))
810         return anOrphanPoint;
811     }
812
813     if (aPointAttr.get()) {
814       std::shared_ptr<GeomAPI_Pnt2d> aPoint = aPointAttr->pnt();
815       // we need to find coincidence features in results also, because external object(point)
816       // uses refs to me in another feature.
817       FeaturePtr aCoincidence = PartSet_Tools::findFirstCoincidence(theFeature, aPoint);
818       anOrphanPoint = true;
819       // if there is at least one concident line to the point, the point is not an orphant
820       if (aCoincidence.get()) {
821         QList<FeaturePtr> aCoinsideLines;
822         QList<FeaturePtr> aCoins;
823         PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines, aCoins,
824                                         SketchPlugin_ConstraintCoincidence::ENTITY_A());
825         PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines, aCoins,
826                                         SketchPlugin_ConstraintCoincidence::ENTITY_B());
827         QList<FeaturePtr>::const_iterator anIt = aCoinsideLines.begin(),
828                                           aLast = aCoinsideLines.end();
829         for (; anIt != aLast && anOrphanPoint; anIt++) {
830           anOrphanPoint = (*anIt)->getKind() != SketchPlugin_Line::ID();
831         }
832       }
833     }
834   }
835   return anOrphanPoint;
836 }
837
838 bool PartSet_WidgetPoint2D::shapeExploreHasVertex(const GeomShapePtr& theShape,
839                                                   const std::shared_ptr<GeomAPI_Pnt2d>& thePoint,
840                                                   const CompositeFeaturePtr& theSketch)
841 {
842   std::shared_ptr<GeomAPI_Pnt> aPoint = PartSet_Tools::point3D(thePoint, theSketch);
843
844   bool aContainPoint = false;
845   GeomAPI_ShapeExplorer anExp(theShape, GeomAPI_Shape::VERTEX);
846   for(; anExp.more() && !aContainPoint; anExp.next()) {
847     std::shared_ptr<GeomAPI_Shape> aVertexInCompSolid = anExp.current();
848     std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex(aVertexInCompSolid));
849     if (aVertex.get())
850       aContainPoint = aPoint->isEqual(aVertex->point());
851   }
852   return aContainPoint;
853 }
854
855 AttributeRefAttrPtr PartSet_WidgetPoint2D::attributeRefAttr() const
856 {
857   AttributeRefAttrPtr anAttribute;
858   if (myRefAttribute.empty())
859     return anAttribute;
860
861   AttributePtr anAttributeRef = feature()->attribute(myRefAttribute);
862   if (!anAttributeRef.get())
863     return anAttribute;
864
865   return std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(anAttributeRef);
866 }
867
868 void PartSet_WidgetPoint2D::fillRefAttribute(double theClickedX, double theClickedY)
869 {
870   AttributeRefAttrPtr aRefAttr = attributeRefAttr();
871   if (!aRefAttr.get())
872     return;
873
874   FeaturePtr aFeature = feature();
875   std::string anAttribute = attributeID();
876
877   if (aFeature.get()) {
878     std::shared_ptr<GeomAPI_Pnt2d> aClickedPoint = std::shared_ptr<GeomAPI_Pnt2d>(
879                                       new GeomAPI_Pnt2d(theClickedX, theClickedY));
880     AttributePoint2DPtr aClickedFeaturePoint = findFirstEqualPointInSketch(mySketch,
881                                                             aFeature, aClickedPoint);
882     if (aClickedFeaturePoint.get())
883       aRefAttr->setAttr(aClickedFeaturePoint);
884   }
885 }
886
887 void PartSet_WidgetPoint2D::fillRefAttribute(const ObjectPtr& theObject)
888 {
889   AttributeRefAttrPtr aRefAttr = attributeRefAttr();
890   if (aRefAttr.get())
891     aRefAttr->setObject(theObject);
892 }
893
894 std::shared_ptr<GeomDataAPI_Point2D> PartSet_WidgetPoint2D::findFirstEqualPointInArgumentFeatures(
895                   const FeaturePtr& theFeature, const std::shared_ptr<GeomAPI_Pnt2d>& thePoint)
896 {
897   std::shared_ptr<GeomDataAPI_Point2D> aFeaturePoint;
898
899   // may be feature is not updated yet, execute is not performed and references features
900   // are not created. Case: rectangle macro feature
901   ModuleBase_Tools::flushUpdated(theFeature);
902
903   std::list<AttributePtr> anAttributes = theFeature->data()->attributes(
904                                           ModelAPI_AttributeRefList::typeId());
905   std::list<AttributePtr>::const_iterator anIt = anAttributes.begin(), aLast = anAttributes.end();
906   for (; anIt != aLast && !aFeaturePoint.get(); anIt++) {
907     std::shared_ptr<ModelAPI_AttributeRefList> aCurSelList =
908                                       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(*anIt);
909     for (int i = 0, aNb = aCurSelList->size(); i < aNb && !aFeaturePoint.get(); i++) {
910       ObjectPtr anObject = aCurSelList->object(i);
911       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
912       if (aFeature.get())
913         aFeaturePoint = findFirstEqualPoint(aFeature, thePoint);
914     }
915   }
916   return aFeaturePoint;
917 }
918
919 std::shared_ptr<GeomDataAPI_Point2D> PartSet_WidgetPoint2D::findFirstEqualPoint(
920                                               const FeaturePtr& theFeature,
921                                               const std::shared_ptr<GeomAPI_Pnt2d>& thePoint)
922 {
923   std::shared_ptr<GeomDataAPI_Point2D> aFPoint;
924
925   // find the given point in the feature attributes
926   std::list<std::shared_ptr<ModelAPI_Attribute> > anAttiributes =
927                                     theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
928   std::list<std::shared_ptr<ModelAPI_Attribute> >::const_iterator anIt = anAttiributes.begin(),
929       aLast = anAttiributes.end();
930   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
931
932   for (; anIt != aLast && !aFPoint; anIt++) {
933     std::shared_ptr<GeomDataAPI_Point2D> aCurPoint =
934                                              std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIt);
935     if (aCurPoint && aCurPoint->isInitialized() &&
936         aValidators->isCase(theFeature, aCurPoint->id()) &&
937         (aCurPoint->pnt()->distance(thePoint) < Precision::Confusion())) {
938       aFPoint = aCurPoint;
939       break;
940     }
941   }
942   return aFPoint;
943 }
944
945 std::shared_ptr<GeomDataAPI_Point2D> PartSet_WidgetPoint2D::findFirstEqualPointInSketch(
946                                     const CompositeFeaturePtr& theSketch,
947                                     const FeaturePtr& theSkipFeature,
948                                     const std::shared_ptr<GeomAPI_Pnt2d>& thePoint)
949 {
950   // get all sketch features. If the point with the given coordinates belong to any sketch feature,
951   // the constraint is created between the feature point and the found sketch point
952   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
953   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
954       ModelAPI_AttributeRefList>(aData->attribute(SketchPlugin_Sketch::FEATURES_ID()));
955
956   std::list<ObjectPtr> aFeatures = aRefList->list();
957   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
958   std::list<std::shared_ptr<ModelAPI_Attribute> > anAttiributes;
959
960   std::shared_ptr<GeomDataAPI_Point2D> aFPoint;
961   for (; anIt != aLast; anIt++) {
962     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
963     if (!aFeature.get() || (theSkipFeature.get() && theSkipFeature == aFeature))
964       continue;
965     aFPoint = PartSet_WidgetPoint2D::findFirstEqualPoint(aFeature, thePoint);
966     if (aFPoint.get())
967       break;
968   }
969   return aFPoint;
970 }