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