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