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