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