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