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