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