Salome HOME
#1404 Random crash with Shaper: AIS presentations: operation prs, result sketch prs...
[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_SketcherReetntrantMgr.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
24 #include <Config_Keywords.h>
25 #include <Config_WidgetAPI.h>
26
27 #include <Events_Loop.h>
28 #include <ModelAPI_Events.h>
29 #include <ModelAPI_AttributeBoolean.h>
30
31 #include <ModelAPI_Feature.h>
32 #include <ModelAPI_Data.h>
33 #include <ModelAPI_Object.h>
34 #include <GeomDataAPI_Point2D.h>
35 #include <GeomAPI_Pnt2d.h>
36
37 #include <GeomAPI_ShapeExplorer.h>
38 #include <GeomAPI_Vertex.h>
39
40 #include <SketchPlugin_Feature.h>
41 #include <SketchPlugin_ConstraintCoincidence.h>
42 #include <SketchPlugin_Line.h>
43 #include <SketchPlugin_Arc.h>
44 #include <SketchPlugin_Circle.h>
45 #include <SketchPlugin_Point.h>
46
47 #include <QGroupBox>
48 #include <QGridLayout>
49 #include <QLabel>
50 #include <QEvent>
51 #include <QMouseEvent>
52 #include <QApplication>
53
54 #include <TopoDS.hxx>
55 #include <TopoDS_Vertex.hxx>
56 #include <BRep_Tool.hxx>
57
58 #include <cfloat>
59 #include <climits>
60
61 const double MaxCoordinate = 1e12;
62
63 static QStringList MyFeaturesForCoincedence;
64
65 PartSet_WidgetPoint2D::PartSet_WidgetPoint2D(QWidget* theParent, 
66                                              ModuleBase_IWorkshop* theWorkshop,
67                                              const Config_WidgetAPI* theData)
68 : ModuleBase_ModelWidget(theParent, theData), myWorkshop(theWorkshop),
69   myValueIsCashed(false), myIsFeatureVisibleInCash(true),
70   myXValueInCash(0), myYValueInCash(0)
71 {
72   if (MyFeaturesForCoincedence.isEmpty()) {
73     MyFeaturesForCoincedence << SketchPlugin_Line::ID().c_str()
74       << SketchPlugin_Arc::ID().c_str()
75       << SketchPlugin_Point::ID().c_str()
76       << SketchPlugin_Circle::ID().c_str();
77   }
78
79   // the control should accept the focus, so the boolean flag is corrected to be true
80   myIsObligatory = true;
81   //myOptionParam = theData->getProperty(PREVIOUS_FEATURE_PARAM);
82   QString aPageName = QString::fromStdString(theData->getProperty(CONTAINER_PAGE_NAME));
83   myGroupBox = new QGroupBox(aPageName, theParent);
84   myGroupBox->setFlat(false);
85
86   bool aAcceptVariables = theData->getBooleanAttribute(DOUBLE_WDG_ACCEPT_EXPRESSIONS, true);
87
88   QGridLayout* aGroupLay = new QGridLayout(myGroupBox);
89   ModuleBase_Tools::adjustMargins(aGroupLay);
90   aGroupLay->setSpacing(2);
91   aGroupLay->setColumnStretch(1, 1);
92   {
93     QLabel* aLabel = new QLabel(myGroupBox);
94     aLabel->setText(tr("X "));
95     aGroupLay->addWidget(aLabel, 0, 0);
96
97     myXSpin = new ModuleBase_ParamSpinBox(myGroupBox);
98     myXSpin->setAcceptVariables(aAcceptVariables);
99     myXSpin->setMinimum(-DBL_MAX);
100     myXSpin->setMaximum(DBL_MAX);
101     myXSpin->setToolTip(tr("X"));
102     aGroupLay->addWidget(myXSpin, 0, 1);
103
104     connect(myXSpin, SIGNAL(valueChanged(const QString&)), this, SIGNAL(valuesModified()));
105   }
106   {
107     QLabel* aLabel = new QLabel(myGroupBox);
108     aLabel->setText(tr("Y "));
109     aGroupLay->addWidget(aLabel, 1, 0);
110
111     myYSpin = new ModuleBase_ParamSpinBox(myGroupBox);
112     myYSpin->setAcceptVariables(aAcceptVariables);
113     myYSpin->setMinimum(-DBL_MAX);
114     myYSpin->setMaximum(DBL_MAX);
115     myYSpin->setToolTip(tr("Y"));
116     aGroupLay->addWidget(myYSpin, 1, 1);
117
118     connect(myYSpin, SIGNAL(valueChanged(const QString&)), this, SIGNAL(valuesModified()));
119   }
120   QVBoxLayout* aLayout = new QVBoxLayout(this);
121   ModuleBase_Tools::zeroMargins(aLayout);
122   aLayout->addWidget(myGroupBox);
123   setLayout(aLayout);
124
125   myWidgetValidator = new ModuleBase_WidgetValidator(this, myWorkshop);
126 }
127
128 bool PartSet_WidgetPoint2D::isValidSelectionCustom(const ModuleBase_ViewerPrsPtr& theValue)
129 {
130   bool aValid = true;
131
132   PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
133   if (aModule->sketchReentranceMgr()->isInternalEditActive()) 
134     return true; /// when internal edit is started a new feature is created. I has not results, AIS
135
136   // workaround for feature, where there is no results
137   //if (myFeature->getKind() == "SketchRectangle")
138   //  return true;
139
140   /// the selection is not possible if the current feature has no presentation for the current
141   /// attribute not in AIS not in results. If so, no object in current feature where make
142   /// coincidence, so selection is not necessary
143   std::shared_ptr<ModelAPI_Data> aData = myFeature->data();
144   std::shared_ptr<GeomDataAPI_Point2D> aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
145       aData->attribute(attributeID()));
146   std::shared_ptr<GeomAPI_Pnt2d> aPoint = aPointAttr->pnt();
147
148   bool aFoundPoint = false;
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   /// analysis of AIS
163   if (anAISShape.get())
164     aFoundPoint = shapeContainsPoint(anAISShape, aPoint, mySketch);
165
166   /// analysis of results
167   std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
168   for (; aRIter != aResults.cend() && !aFoundPoint; aRIter++) {
169     ResultPtr aResult = *aRIter;
170     if (aResult.get() && aResult->shape().get()) {
171       GeomShapePtr aShape = aResult->shape();
172       aFoundPoint = shapeContainsPoint(aShape, aPoint, mySketch);
173     }
174   }
175   return aFoundPoint;
176 }
177
178 bool PartSet_WidgetPoint2D::resetCustom()
179 {
180   bool aDone = false;
181   if (!isUseReset() || isComputedDefault() || myXSpin->hasVariable() || myYSpin->hasVariable()) {
182     aDone = false;
183   }
184   else {
185     if (myValueIsCashed) {
186       // if the restored value should be hidden, aDone = true to set
187       // reset state for the widget in the parent
188       aDone = restoreCurentValue();
189       emit objectUpdated();
190     }
191     else {
192       bool isOk;
193       double aDefValue = QString::fromStdString(getDefaultValue()).toDouble(&isOk);
194       // it is important to block the spin box control in order to do not through out the
195       // locking of the validating state.
196       ModuleBase_Tools::setSpinValue(myXSpin, isOk ? aDefValue : 0.0);
197       ModuleBase_Tools::setSpinValue(myYSpin, isOk ? aDefValue : 0.0);
198       storeValueCustom();
199       aDone = true;
200     }
201   }
202   return aDone;
203 }
204
205 PartSet_WidgetPoint2D::~PartSet_WidgetPoint2D()
206 {
207 }
208
209 bool PartSet_WidgetPoint2D::setSelection(QList<ModuleBase_ViewerPrsPtr>& theValues,
210                                          const bool theToValidate)
211 {
212   bool isDone = false;
213   if (theValues.empty())
214     return isDone;
215
216   ModuleBase_ViewerPrsPtr aValue = theValues.takeFirst();
217   GeomShapePtr aShape = aValue->shape();
218   if (aShape.get() && !aShape->isNull()) {
219     Handle(V3d_View) aView = myWorkshop->viewer()->activeView();
220     double aX, aY;
221     const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
222     if (getPoint2d(aView, aTDShape, aX, aY)) {
223       isDone = setPoint(aX, aY);
224       PartSet_Tools::setConstraints(mySketch, feature(), attributeID(), aX, aY);
225     }
226   }
227   else if (canBeActivatedByMove()) {
228     if (feature()->getKind() == SketchPlugin_Line::ID()) {
229       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aValue->object());
230       // Initialize new line with first point equal to end of previous
231       if (aFeature.get()) {
232         std::shared_ptr<ModelAPI_Data> aData = aFeature->data();
233         std::shared_ptr<GeomDataAPI_Point2D> aPoint = 
234           std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
235                                        aData->attribute(SketchPlugin_Line::END_ID()));
236         if (aPoint) {
237           setPoint(aPoint->x(), aPoint->y());
238           PartSet_Tools::setConstraints(mySketch, feature(), attributeID(), aPoint->x(),
239                                         aPoint->y());
240           isDone = true;
241         }
242       }
243     }
244   }
245   return isDone;
246 }
247
248 void PartSet_WidgetPoint2D::selectContent()
249 {
250   myXSpin->selectAll();
251 }
252
253 bool PartSet_WidgetPoint2D::setPoint(double theX, double theY)
254 {
255   if (fabs(theX) >= MaxCoordinate)
256     return false;
257   if (fabs(theY) >= MaxCoordinate)
258     return false;
259
260   ModuleBase_Tools::setSpinValue(myXSpin, theX);
261   ModuleBase_Tools::setSpinValue(myYSpin, theY);
262
263   storeValue();
264   return true;
265 }
266
267 bool PartSet_WidgetPoint2D::storeValueCustom()
268 {
269   std::shared_ptr<ModelAPI_Data> aData = myFeature->data();
270   if (!aData) // can be on abort of sketcher element
271     return false;
272   std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
273       aData->attribute(attributeID()));
274
275   PartSet_WidgetPoint2D* that = (PartSet_WidgetPoint2D*) this;
276   bool isBlocked = that->blockSignals(true);
277   bool isImmutable = aPoint->setImmutable(true);
278
279   // if text is not empty then setValue will be ignored
280   // so we should set the text at first
281   aPoint->setText(myXSpin->hasVariable() ? myXSpin->text().toStdString() : "",
282                   myYSpin->hasVariable() ? myYSpin->text().toStdString() : "");
283   aPoint->setValue(!myXSpin->hasVariable() ? myXSpin->value() : aPoint->x(),
284                    !myYSpin->hasVariable() ? myYSpin->value() : aPoint->y());
285
286   // after movement the solver will call the update event: optimization
287   moveObject(myFeature);
288   aPoint->setImmutable(isImmutable);
289   that->blockSignals(isBlocked);
290
291   return true;
292 }
293
294 bool PartSet_WidgetPoint2D::restoreValueCustom()
295 {
296   std::shared_ptr<ModelAPI_Data> aData = myFeature->data();
297   std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
298       aData->attribute(attributeID()));
299   QString aTextX = QString::fromStdString(aPoint->textX());
300   QString aTextY = QString::fromStdString(aPoint->textY());
301
302   bool isDouble = false;
303   double aVal = 0;
304   if (aTextX.isEmpty()) {
305     ModuleBase_Tools::setSpinValue(myXSpin, aPoint->x());
306   } else {
307     aVal = aTextX.toDouble(&isDouble);
308     if (isDouble)
309       ModuleBase_Tools::setSpinValue(myXSpin, aVal);
310     else
311       ModuleBase_Tools::setSpinText(myXSpin, aTextX);
312   }
313   if (aTextY.isEmpty()) {
314     ModuleBase_Tools::setSpinValue(myYSpin, aPoint->y());
315   } else {
316     aVal = aTextY.toDouble(&isDouble);
317     if (isDouble)
318       ModuleBase_Tools::setSpinValue(myYSpin, aVal);
319     else
320       ModuleBase_Tools::setSpinText(myYSpin, aTextY);
321   }
322   //if (aTextX.empty() || aTextY.empty()) {
323   //  ModuleBase_Tools::setSpinValue(myXSpin, aPoint->x());
324   //  ModuleBase_Tools::setSpinValue(myYSpin, aPoint->y());
325   //} else {
326   //  ModuleBase_Tools::setSpinText(myXSpin, QString::fromStdString(aTextX));
327   //  ModuleBase_Tools::setSpinText(myYSpin, QString::fromStdString(aTextY));
328   //}
329   return true;
330 }
331
332 void PartSet_WidgetPoint2D::storeCurentValue()
333 {
334   // do not use cash if a variable is used
335   if (myXSpin->hasVariable() || myYSpin->hasVariable())
336     return;
337
338   myValueIsCashed = true;
339   myIsFeatureVisibleInCash = XGUI_Displayer::isVisible(
340                        XGUI_Tools::workshop(myWorkshop)->displayer(), myFeature);
341   myXValueInCash = myXSpin->value();
342   myYValueInCash = myYSpin->value();
343 }
344
345 bool PartSet_WidgetPoint2D::restoreCurentValue()
346 {
347   bool aRestoredAndHidden = true;
348
349   bool isVisible = myIsFeatureVisibleInCash;
350   // fill the control widgets by the cashed value
351
352   myValueIsCashed = false;
353   myIsFeatureVisibleInCash = true;
354   ModuleBase_Tools::setSpinValue(myXSpin, myXValueInCash);
355   ModuleBase_Tools::setSpinValue(myYSpin, myYValueInCash);
356
357   // store value to the model
358   storeValueCustom();
359   if (isVisible) {
360     setValueState(Stored);
361     aRestoredAndHidden = false;
362   }
363   else
364     aRestoredAndHidden = true;
365
366   return aRestoredAndHidden;
367 }
368
369 QList<QWidget*> PartSet_WidgetPoint2D::getControls() const
370 {
371   QList<QWidget*> aControls;
372   aControls.append(myXSpin);
373   aControls.append(myYSpin);
374   return aControls;
375 }
376
377
378 void PartSet_WidgetPoint2D::activateCustom()
379 {
380   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
381   connect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)), 
382           this, SLOT(onMouseMove(ModuleBase_IViewWindow*, QMouseEvent*)));
383   connect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)), 
384           this, SLOT(onMouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)));
385
386   QIntList aModes;
387   aModes << TopAbs_VERTEX;
388   aModes << TopAbs_EDGE;
389   myWorkshop->activateSubShapesSelection(aModes);
390
391   if (!isEditingMode()) {
392     FeaturePtr aFeature = feature();
393     if (aFeature.get() && aFeature->getKind() == SketchPlugin_Point::ID())
394       storeValue();
395   }
396 }
397
398 bool PartSet_WidgetPoint2D::canBeActivatedByMove()
399 {
400   bool aCanBeActivated = false;
401   if (feature()->getKind() == SketchPlugin_Line::ID() &&
402       attributeID() == SketchPlugin_Line::START_ID())
403     aCanBeActivated = true;
404
405   return aCanBeActivated;
406 }
407
408 void PartSet_WidgetPoint2D::deactivate()
409 {
410   // the value of the control should be stored to model if it was not
411   // initialized yet. It is important when we leave this control by Tab key.
412   // It should not be performed by the widget activation as the preview
413   // is visualized with default value. Line point is moved to origin.
414   AttributePtr anAttribute = myFeature->data()->attribute(attributeID());
415   if (anAttribute && !anAttribute->isInitialized())
416     storeValue();
417
418   ModuleBase_ModelWidget::deactivate();
419   ModuleBase_IViewer* aViewer = myWorkshop->viewer();
420   disconnect(aViewer, SIGNAL(mouseMove(ModuleBase_IViewWindow*, QMouseEvent*)),
421              this, SLOT(onMouseMove(ModuleBase_IViewWindow*, QMouseEvent*)));
422   disconnect(aViewer, SIGNAL(mouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)), 
423              this, SLOT(onMouseRelease(ModuleBase_IViewWindow*, QMouseEvent*)));
424
425   myWorkshop->deactivateSubShapesSelection();
426 }
427
428 bool PartSet_WidgetPoint2D::getPoint2d(const Handle(V3d_View)& theView, 
429                                        const TopoDS_Shape& theShape, 
430                                        double& theX, double& theY) const
431 {
432   if (!theShape.IsNull()) {
433     if (theShape.ShapeType() == TopAbs_VERTEX) {
434       const TopoDS_Vertex& aVertex = TopoDS::Vertex(theShape);
435       if (!aVertex.IsNull()) {
436         // A case when point is taken from existing vertex
437         gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
438         PartSet_Tools::convertTo2D(aPoint, mySketch, theView, theX, theY);
439         return true;
440       }
441     }
442   }
443   return false;
444 }
445
446 bool PartSet_WidgetPoint2D::setConstraintWith(const ObjectPtr& theObject)
447 {
448   std::shared_ptr<GeomDataAPI_Point2D> aFeaturePoint;
449   if (feature()->isMacro()) {
450     AttributePtr aThisAttr = feature()->data()->attribute(attributeID());
451     std::shared_ptr<GeomDataAPI_Point2D> anAttrPoint =
452                                std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aThisAttr);
453     if (anAttrPoint.get()) {
454       // the macro feature will be removed after the operation is stopped, so we need to build
455       // coicidence to possible sub-features
456       aFeaturePoint = PartSet_Tools::findFirstEqualPointInArgumentFeatures(feature(),
457                                                                  anAttrPoint->pnt());
458     }
459   }
460   else {
461     AttributePtr aThisAttr = feature()->data()->attribute(attributeID());
462     aFeaturePoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aThisAttr);
463   }
464   if (!aFeaturePoint.get())
465     return false;
466
467   // Create point-edge coincedence
468   FeaturePtr aFeature = mySketch->addFeature(SketchPlugin_ConstraintCoincidence::ID());
469   std::shared_ptr<ModelAPI_Data> aData = aFeature->data();
470
471   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef1 = std::dynamic_pointer_cast<
472       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
473
474   aRef1->setAttr(aFeaturePoint);
475
476   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef2 = std::dynamic_pointer_cast<
477       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
478   aRef2->setObject(theObject);
479
480   // we need to flush created signal in order to coincidence is processed by solver
481   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
482
483   return true;
484 }
485
486 void PartSet_WidgetPoint2D::onMouseRelease(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
487 {
488   // the contex menu release by the right button should not be processed by this widget
489   if (theEvent->button() != Qt::LeftButton)
490     return;
491
492   ModuleBase_ISelection* aSelection = myWorkshop->selection();
493   Handle(V3d_View) aView = theWnd->v3dView();
494
495   QList<ModuleBase_ViewerPrsPtr> aList = aSelection->getSelected(ModuleBase_ISelection::Viewer);
496   ModuleBase_ViewerPrsPtr aFirstValue = aList.size() > 0 ? aList.first() : ModuleBase_ViewerPrsPtr();
497   // if we have selection and use it
498   if (aFirstValue.get() && isValidSelectionCustom(aFirstValue)) {
499     GeomShapePtr aGeomShape = aFirstValue->shape();
500     TopoDS_Shape aShape = aGeomShape->impl<TopoDS_Shape>();
501     ObjectPtr aObject = aFirstValue->object();
502
503     FeaturePtr aSelectedFeature = ModelAPI_Feature::feature(aObject);
504     bool anExternal = false;
505     std::shared_ptr<SketchPlugin_Feature> aSPFeature;
506     if (aSelectedFeature.get() != NULL)
507       aSPFeature = std::dynamic_pointer_cast<SketchPlugin_Feature>(aSelectedFeature);
508       if ((!aSPFeature && !aShape.IsNull()) ||
509           (aSPFeature.get() && aSPFeature->isExternal())) {
510         ResultPtr aFixedObject;
511         anExternal = true;
512         aFixedObject = PartSet_Tools::findFixedObjectByExternal(aShape, aObject, mySketch);
513         if (!aFixedObject.get())
514           aFixedObject = PartSet_Tools::createFixedObjectByExternal(aShape, aObject, mySketch);
515         double aX, aY;
516         if (getPoint2d(aView, aShape, aX, aY) && isFeatureContainsPoint(myFeature, aX, aY)) {
517           // do not create a constraint to the point, which already used by the feature
518           // if the feature contains the point, focus is not switched
519           setPoint(aX, aY);
520         }
521         else {
522           if (getPoint2d(aView, aShape, aX, aY))
523             setPoint(aX, aY);
524           else
525             setValueState(Stored); // in case of edge selection, Apply state should also be updated
526           bool anOrphanPoint = aShape.ShapeType() == TopAbs_VERTEX ||
527                                isOrphanPoint(aSelectedFeature, mySketch, aX, aY);
528           if (anExternal) {
529             anOrphanPoint = true; // we should not stop reentrant operation on external objects because
530             // they are not participate in the contour creation excepting external vertices
531             if (aShape.ShapeType() == TopAbs_VERTEX) {
532               FeaturePtr aFixedFeature = ModelAPI_Feature::feature(aFixedObject);
533               if (aFixedFeature.get() && aFixedFeature->getKind() == SketchPlugin_Point::ID()) {
534                 anOrphanPoint = isOrphanPoint(aFixedFeature, mySketch, aX, aY);
535               }
536             }
537           }
538           if (aFixedObject.get())
539             setConstraintWith(aFixedObject);
540           // fignal updated should be flushed in order to visualize possible created external objects
541           // e.g. selection of trihedron axis when input end arc point
542           updateObject(feature());
543
544           if (!anOrphanPoint)
545             emit vertexSelected(); // it stops the reentrant operation
546
547           emit focusOutWidget(this);
548         }
549       }
550     if (!anExternal) {
551       double aX, aY;
552       bool isProcessed = false;
553       if (getPoint2d(aView, aShape, aX, aY) && isFeatureContainsPoint(myFeature, aX, aY)) {
554         // when the point is selected, the coordinates of the point should be set into the attribute
555         // if the feature contains the point, focus is not switched
556         setPoint(aX, aY);
557       }
558       else {
559         bool anOrphanPoint = isOrphanPoint(aSelectedFeature, mySketch, aX, aY);
560         // do not set a coincidence constraint in the attribute if the feature contains a point
561         // with the same coordinates. It is important for line creation in order to do not set
562         // the same constraints for the same points, oterwise the result line has zero length.
563         bool isAuxiliaryFeature = false;
564         if (getPoint2d(aView, aShape, aX, aY)) {
565           setPoint(aX, aY);
566           feature()->execute();
567           PartSet_Tools::setConstraints(mySketch, feature(), attributeID(), aX, aY);
568         }
569         else if (aShape.ShapeType() == TopAbs_EDGE) {
570           if (!setConstraintWith(aObject)) {
571             gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWnd->v3dView());
572             PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, aY);
573             setPoint(aX, aY);
574           }
575           setValueState(Stored); // in case of edge selection, Apply state should also be updated
576           isAuxiliaryFeature = PartSet_Tools::isAuxiliarySketchEntity(aObject);
577         }
578         // it is important to perform updateObject() in order to the current value is 
579         // processed by Sketch Solver. Test case: line is created from a previous point
580         // to some distance, but in the area of the highlighting of the point. Constraint
581         // coincidence is created, after the solver is performed, the distance between the
582         // points of the line becomes less than the tolerance. Validator of the line returns
583         // false, the line will be aborted, but sketch stays valid.
584         updateObject(feature());
585         if (!anOrphanPoint && !anExternal && !isAuxiliaryFeature)
586           emit vertexSelected();
587         emit focusOutWidget(this);
588       }
589     }
590   }
591   // End of Bug dependent fragment
592   else {
593     // A case when point is taken from mouse event
594     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWnd->v3dView());
595     double aX, anY;
596     PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, anY);
597
598     // if the feature contains the point, focus is not switched
599     if (!setPoint(aX, anY) || isFeatureContainsPoint(myFeature, aX, anY))
600       return;
601
602     /// Start alternative code
603     //std::shared_ptr<GeomDataAPI_Point2D> aFeaturePoint = std::dynamic_pointer_cast<
604     //    GeomDataAPI_Point2D>(feature()->data()->attribute(attributeID()));
605     //QList<FeaturePtr> aIgnore;
606     //aIgnore.append(feature());
607
608     //double aTolerance = aView->Convert(7);
609     //std::shared_ptr<GeomDataAPI_Point2D> aAttrPnt = 
610     //  PartSet_Tools::findAttributePoint(mySketch, aX, anY, aTolerance, aIgnore);
611     //if (aAttrPnt.get() != NULL) {
612     //  aFeaturePoint->setValue(aAttrPnt->pnt());
613     //  PartSet_Tools::createConstraint(mySketch, aAttrPnt, aFeaturePoint);
614     //  emit vertexSelected();
615     //}
616     /// End alternative code
617     emit focusOutWidget(this);
618   }
619 }
620
621
622 void PartSet_WidgetPoint2D::onMouseMove(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
623 {
624   if (isEditingMode())
625     return;
626
627   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWnd->v3dView());
628
629   double aX, anY;
630   PartSet_Tools::convertTo2D(aPoint, mySketch, theWnd->v3dView(), aX, anY);
631   if (myState != ModifiedInViewer)
632     storeCurentValue();
633   // we need to block the value state change 
634   bool isBlocked = blockValueState(true);
635   setPoint(aX, anY);
636   blockValueState(isBlocked);
637   setValueState(ModifiedInViewer);
638 }
639
640 double PartSet_WidgetPoint2D::x() const
641 {
642   return myXSpin->value();
643 }
644
645 double PartSet_WidgetPoint2D::y() const
646 {
647   return myYSpin->value();
648 }
649
650
651 bool PartSet_WidgetPoint2D::isFeatureContainsPoint(const FeaturePtr& theFeature,
652                                                    double theX, double theY)
653 {
654   bool aPointIsFound = false;
655
656   if (feature()->getKind() != SketchPlugin_Line::ID())
657     return aPointIsFound;
658
659   AttributePtr aWidgetAttribute = myFeature->attribute(attributeID());
660
661   std::shared_ptr<GeomAPI_Pnt2d> aPnt2d = 
662                                     std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(theX, theY));
663   std::list<AttributePtr> anAttributes =
664                                 myFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
665   std::list<AttributePtr>::iterator anIter = anAttributes.begin();
666   for(; anIter != anAttributes.end() && !aPointIsFound; anIter++) {
667     AttributePoint2DPtr aPoint2DAttribute =
668       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
669     if (aPoint2DAttribute == aWidgetAttribute)
670       continue;
671     if (aPoint2DAttribute.get() && aPoint2DAttribute->isInitialized()) {
672       aPointIsFound = aPoint2DAttribute->pnt()->isEqual(aPnt2d);
673     }
674   }
675   return aPointIsFound;
676 }
677
678 void PartSet_WidgetPoint2D::initializeValueByActivate()
679 {
680 }
681
682 /*void PartSet_WidgetPoint2D::onValuesChanged()
683 {
684   emit valuesChanged();
685 }*/
686
687 bool PartSet_WidgetPoint2D::processEnter()
688 {
689   bool isModified = getValueState() == ModifiedInPP;
690   if (isModified) {
691     bool isXModified = myXSpin->hasFocus();
692     emit valuesChanged();
693     if (isXModified)
694       myXSpin->selectAll();
695     else
696       myYSpin->selectAll();
697   }
698   return isModified;
699 }
700
701 bool PartSet_WidgetPoint2D::useSelectedShapes() const
702 {
703   return true;
704 }
705
706 bool PartSet_WidgetPoint2D::isOrphanPoint(const FeaturePtr& theFeature,
707                                           const CompositeFeaturePtr& theSketch,
708                                           double theX, double theY)
709 {
710   bool anOrphanPoint = false;
711   if (theFeature.get()) {
712     std::shared_ptr<GeomDataAPI_Point2D> aPointAttr;
713     std::string aFeatureKind = theFeature->getKind();
714     if (aFeatureKind == SketchPlugin_Point::ID())
715       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
716                                        theFeature->attribute(SketchPlugin_Point::COORD_ID()));
717     else if (aFeatureKind == SketchPlugin_Circle::ID())
718       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
719                                        theFeature->attribute(SketchPlugin_Circle::CENTER_ID()));
720
721     else if (aFeatureKind == SketchPlugin_Arc::ID())
722       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
723                                        theFeature->attribute(SketchPlugin_Arc::CENTER_ID()));
724
725     /// check that the geometry point with the given coordinates is the checked point
726     /// e.g. in arc the (x,y) point can not coicide to the center point and it automatically
727     /// means that this point is not an orphant one.
728     if (aPointAttr.get()) {
729       std::shared_ptr<GeomAPI_Pnt2d> aCheckedPoint = std::shared_ptr<GeomAPI_Pnt2d>(
730                                                     new GeomAPI_Pnt2d(theX, theY));
731       if (!aCheckedPoint->isEqual(aPointAttr->pnt()))
732         return anOrphanPoint;
733     }
734
735     if (aPointAttr.get()) {
736       std::shared_ptr<GeomAPI_Pnt2d> aPoint = aPointAttr->pnt();
737       // we need to find coincidence features in results also, because external object(point)
738       // uses refs to me in another feature.
739       FeaturePtr aCoincidence = PartSet_Tools::findFirstCoincidence(theFeature, aPoint);
740       anOrphanPoint = true;
741       // if there is at least one concident line to the point, the point is not an orphant
742       if (aCoincidence.get()) {
743         QList<FeaturePtr> aCoinsideLines;
744         QList<FeaturePtr> aCoins;
745         PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines, aCoins,
746                                         SketchPlugin_ConstraintCoincidence::ENTITY_A());
747         PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines, aCoins,
748                                         SketchPlugin_ConstraintCoincidence::ENTITY_B());
749         QList<FeaturePtr>::const_iterator anIt = aCoinsideLines.begin(),
750                                           aLast = aCoinsideLines.end();
751         for (; anIt != aLast && anOrphanPoint; anIt++) {
752           anOrphanPoint = (*anIt)->getKind() != SketchPlugin_Line::ID();
753         }
754       }
755     }
756   }
757   return anOrphanPoint;
758 }
759
760 bool PartSet_WidgetPoint2D::shapeContainsPoint(const GeomShapePtr& theShape,
761                                                const std::shared_ptr<GeomAPI_Pnt2d>& thePoint,
762                                                const CompositeFeaturePtr& theSketch)
763 {
764   std::shared_ptr<GeomAPI_Pnt> aPoint = PartSet_Tools::point3D(thePoint, theSketch);
765
766   bool aContainPoint = false;
767   GeomAPI_ShapeExplorer anExp(theShape, GeomAPI_Shape::VERTEX);
768   for(; anExp.more() && !aContainPoint; anExp.next()) {
769     std::shared_ptr<GeomAPI_Shape> aVertexInCompSolid = anExp.current();
770     std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex(aVertexInCompSolid));
771     if (aVertex.get())
772       aContainPoint = aPoint->isEqual(aVertex->point());
773   }
774   return aContainPoint;
775 }