]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_WidgetPoint2d.cpp
Salome HOME
Merge remote-tracking branch 'remotes/origin/master' into Dev_2.8.0
[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   // if we have selection and use it
597   if (aFirstValue.get() && isValidSelectionCustom(aFirstValue) &&
598       aFirstValue->shape().get()) { /// Trihedron Axis may be selected, but shape is empty
599     GeomShapePtr aGeomShape = aFirstValue->shape();
600     TopoDS_Shape aShape = aGeomShape->impl<TopoDS_Shape>();
601     ObjectPtr aObject = aFirstValue->object();
602
603     FeaturePtr aSelectedFeature = ModelAPI_Feature::feature(aObject);
604     bool anExternal = false;
605     std::shared_ptr<SketchPlugin_Feature> aSPFeature;
606     if (aSelectedFeature.get() != NULL)
607       aSPFeature = std::dynamic_pointer_cast<SketchPlugin_Feature>(aSelectedFeature);
608
609     ResultPtr aFixedObject;
610     bool aSketchExternalFeature = aSPFeature.get() && aSPFeature->isExternal();
611     if ((!aSPFeature && !aShape.IsNull()) || aSketchExternalFeature) {
612       aFixedObject = PartSet_Tools::findFixedObjectByExternal(aShape, aObject, mySketch);
613       if (aSketchExternalFeature && !aFixedObject.get()) {/// local selection on external feature
614         anExternal = false;
615       }
616       else {
617         anExternal = true;
618         if (!aFixedObject.get())
619           aFixedObject = PartSet_Tools::createFixedObjectByExternal(aShape, aObject, mySketch);
620       }
621     }
622     if (anExternal) {
623       double aX, aY;
624       if (getPoint2d(aView, aShape, aX, aY) && isFeatureContainsPoint(myFeature, aX, aY)) {
625         // do not create a constraint to the point, which already used by the feature
626         // if the feature contains the point, focus is not switched
627         setPoint(aX, aY);
628       }
629       else {
630         if (getPoint2d(aView, aShape, aX, aY))
631           setPoint(aX, aY);
632         else {
633           if (aShape.ShapeType() == TopAbs_EDGE) {
634             // point is taken from mouse event and set in attribute. It should be done before set
635             // coinident constraint to the external line. If a point is created, it should be in
636             // the mouse clicked point
637             gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(),
638                                                                theWindow->v3dView());
639             PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, aY);
640             setPoint(aX, aY);
641           }
642           setValueState(Stored); // in case of edge selection, Apply state should also be updated
643         }
644         bool anOrphanPoint = aShape.ShapeType() == TopAbs_VERTEX ||
645                               isOrphanPoint(aSelectedFeature, mySketch, aX, aY);
646         if (anExternal) {
647           // we should not stop reentrant operation on external objects because
648           anOrphanPoint = true;
649           // they are not participate in the contour creation excepting external vertices
650           if (aShape.ShapeType() == TopAbs_VERTEX) {
651             FeaturePtr aFixedFeature = ModelAPI_Feature::feature(aFixedObject);
652             if (aFixedFeature.get() && aFixedFeature->getKind() == SketchPlugin_Point::ID()) {
653               anOrphanPoint = isOrphanPoint(aFixedFeature, mySketch, aX, aY);
654             }
655           }
656         }
657         if (aFixedObject.get())
658           setConstraintToObject(aFixedObject);
659         // fignal updated should be flushed in order to visualize possible created
660         // external objects e.g. selection of trihedron axis when input end arc point
661         updateObject(feature());
662
663         if (!anOrphanPoint)
664           emit vertexSelected(); // it stops the reentrant operation
665
666         emit focusOutWidget(this);
667       }
668     }
669     if (!anExternal) {
670       double aX, aY;
671       bool isProcessed = false;
672       if (getPoint2d(aView, aShape, aX, aY) && isFeatureContainsPoint(myFeature, aX, aY)) {
673         // when the point is selected, the coordinates of the point should be set into the attribute
674         // if the feature contains the point, focus is not switched
675         setPoint(aX, aY);
676       }
677       else {
678         bool anOrphanPoint = isOrphanPoint(aSelectedFeature, mySketch, aX, aY);
679         // do not set a coincidence constraint in the attribute if the feature contains a point
680         // with the same coordinates. It is important for line creation in order to do not set
681         // the same constraints for the same points, oterwise the result line has zero length.
682         bool isAuxiliaryFeature = false;
683         if (getPoint2d(aView, aShape, aX, aY)) {
684           setPoint(aX, aY);
685           setConstraintToPoint(aX, aY, aFirstValue);
686         }
687         else if (aShape.ShapeType() == TopAbs_EDGE) {
688           // point is taken from mouse event and set in attribute. It should be done before setting
689           // coinident constraint to the external line. If a point is created, it should be in
690           // the mouse clicked point
691           gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
692           PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, aY);
693           setPoint(aX, aY);
694           setConstraintToObject(aObject);
695           setValueState(Stored); // in case of edge selection, Apply state should also be updated
696           isAuxiliaryFeature = PartSet_Tools::isAuxiliarySketchEntity(aObject);
697         }
698         // it is important to perform updateObject() in order to the current value is
699         // processed by Sketch Solver. Test case: line is created from a previous point
700         // to some distance, but in the area of the highlighting of the point. Constraint
701         // coincidence is created, after the solver is performed, the distance between the
702         // points of the line becomes less than the tolerance. Validator of the line returns
703         // false, the line will be aborted, but sketch stays valid.
704         updateObject(feature());
705         if (!anOrphanPoint && !anExternal && !isAuxiliaryFeature)
706           emit vertexSelected();
707         emit focusOutWidget(this);
708       }
709     }
710   }
711   // The selection could be a center of an external circular object
712   else if (aFirstValue.get() && (!aFirstValue->interactive().IsNull())) {
713     Handle(PartSet_CenterPrs) aAIS =
714         Handle(PartSet_CenterPrs)::DownCast(aFirstValue->interactive());
715     if (!aAIS.IsNull()) {
716       gp_Pnt aPntComp = aAIS->Component()->Pnt();
717       GeomVertexPtr aVertPtr(new GeomAPI_Vertex(aPntComp.X(), aPntComp.Y(), aPntComp.Z()));
718       TopoDS_Shape aShape = aVertPtr->impl<TopoDS_Shape>();
719
720       ResultPtr aFixedObject =
721           PartSet_Tools::findFixedObjectByExternal(aShape, aAIS->object(), mySketch);
722       if (!aFixedObject.get())
723         aFixedObject = PartSet_Tools::createFixedByExternalCenter(aAIS->object(), aAIS->edge(),
724                                                                   aAIS->centerType(), mySketch);
725       if (aFixedObject.get())
726         setConstraintToObject(aFixedObject);
727       // fignal updated should be flushed in order to visualize possible created
728       // external objects e.g. selection of trihedron axis when input end arc point
729       updateObject(feature());
730
731       double aX, aY;
732       if (getPoint2d(aView, aShape, aX, aY)) {
733         // do not create a constraint to the point, which already used by the feature
734         // if the feature contains the point, focus is not switched
735         setPoint(aX, aY);
736       }
737       emit vertexSelected(); // it stops the reentrant operation
738       emit focusOutWidget(this);
739     }
740   }
741   else {
742     // A case when point is taken from mouse event
743     gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
744     double aX, anY;
745     PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, anY);
746
747     // if the feature contains the point, focus is not switched
748     if (!setPoint(aX, anY) || isFeatureContainsPoint(myFeature, aX, anY))
749       return;
750
751     emit focusOutWidget(this);
752   }
753 }
754
755 void PartSet_WidgetPoint2D::setPreSelection(
756                                const std::shared_ptr<ModuleBase_ViewerPrs>& thePreSelected,
757                                ModuleBase_IViewWindow* theWnd,
758                                QMouseEvent* theEvent)
759 {
760   myPreSelected = thePreSelected;
761   mouseReleased(theWnd, theEvent);
762   myPreSelected = ModuleBase_ViewerPrsPtr();
763 }
764
765 void PartSet_WidgetPoint2D::getGeomSelection_(const std::shared_ptr<ModuleBase_ViewerPrs>& theValue,
766                                               ObjectPtr& theObject,
767                                               GeomShapePtr& theShape)
768 {
769   myExternalObjectMgr->getGeomSelection(theValue, theObject, theShape, myWorkshop, sketch(), true);
770 }
771
772 void PartSet_WidgetPoint2D::mouseMoved(ModuleBase_IViewWindow* theWindow, QMouseEvent* theEvent)
773 {
774   PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
775
776   if (isEditingMode() || aModule->sketchReentranceMgr()->isInternalEditActive())
777     return;
778
779   gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
780
781   double aX, anY;
782   PartSet_Tools::convertTo2D(aPoint, mySketch, theWindow->v3dView(), aX, anY);
783   if (myState != ModifiedInViewer)
784     storeCurentValue();
785   // we need to block the value state change
786   bool isBlocked = blockValueState(true);
787   setPoint(aX, anY);
788   blockValueState(isBlocked);
789   setValueState(ModifiedInViewer);
790 }
791
792 double PartSet_WidgetPoint2D::x() const
793 {
794   return myXSpin->value();
795 }
796
797 double PartSet_WidgetPoint2D::y() const
798 {
799   return myYSpin->value();
800 }
801
802
803 bool PartSet_WidgetPoint2D::isFeatureContainsPoint(const FeaturePtr& theFeature,
804                                                    double theX, double theY)
805 {
806   bool aPointIsFound = false;
807
808   if (feature()->getKind() != SketchPlugin_Line::ID())
809     return aPointIsFound;
810
811   AttributePtr aWidgetAttribute = myFeature->attribute(attributeID());
812
813   std::shared_ptr<GeomAPI_Pnt2d> aPnt2d =
814                                     std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(theX, theY));
815   std::list<AttributePtr> anAttributes =
816                                 myFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
817   std::list<AttributePtr>::iterator anIter = anAttributes.begin();
818   for(; anIter != anAttributes.end() && !aPointIsFound; anIter++) {
819     AttributePoint2DPtr aPoint2DAttribute =
820       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIter);
821     if (aPoint2DAttribute == aWidgetAttribute)
822       continue;
823     if (aPoint2DAttribute.get() && aPoint2DAttribute->isInitialized()) {
824       aPointIsFound = aPoint2DAttribute->pnt()->isEqual(aPnt2d);
825     }
826   }
827   return aPointIsFound;
828 }
829
830 void PartSet_WidgetPoint2D::initializeValueByActivate()
831 {
832 }
833
834 /*void PartSet_WidgetPoint2D::onValuesChanged()
835 {
836   emit valuesChanged();
837 }*/
838
839 bool PartSet_WidgetPoint2D::processEnter()
840 {
841   return false;
842   /*bool isModified = getValueState() == ModifiedInPP;
843   if (isModified) {
844     bool isXModified = myXSpin->hasFocus();
845     emit valuesChanged();
846     if (isXModified)
847       myXSpin->selectAll();
848     else
849       myYSpin->selectAll();
850   }
851   return isModified;*/
852 }
853
854 bool PartSet_WidgetPoint2D::useSelectedShapes() const
855 {
856   return true;
857 }
858
859 bool PartSet_WidgetPoint2D::isOrphanPoint(const FeaturePtr& theFeature,
860                                           const CompositeFeaturePtr& theSketch,
861                                           double theX, double theY)
862 {
863   bool anOrphanPoint = false;
864   if (theFeature.get()) {
865     AttributePoint2DPtr aPointAttr;
866     std::string aFeatureKind = theFeature->getKind();
867     if (aFeatureKind == SketchPlugin_Point::ID())
868       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
869                                        theFeature->attribute(SketchPlugin_Point::COORD_ID()));
870     else if (aFeatureKind == SketchPlugin_Circle::ID())
871       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
872                                        theFeature->attribute(SketchPlugin_Circle::CENTER_ID()));
873
874     else if (aFeatureKind == SketchPlugin_Arc::ID())
875       aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
876                                        theFeature->attribute(SketchPlugin_Arc::CENTER_ID()));
877
878     /// check that the geometry point with the given coordinates is the checked point
879     /// e.g. in arc the (x,y) point can not coicide to the center point and it automatically
880     /// means that this point is not an orphant one.
881     if (aPointAttr.get()) {
882       std::shared_ptr<GeomAPI_Pnt2d> aCheckedPoint = std::shared_ptr<GeomAPI_Pnt2d>(
883                                                     new GeomAPI_Pnt2d(theX, theY));
884       if (!aCheckedPoint->isEqual(aPointAttr->pnt()))
885         return anOrphanPoint;
886     }
887
888     if (aPointAttr.get()) {
889       std::shared_ptr<GeomAPI_Pnt2d> aPoint = aPointAttr->pnt();
890       // we need to find coincidence features in results also, because external object(point)
891       // uses refs to me in another feature.
892       FeaturePtr aCoincidence = PartSet_Tools::findFirstCoincidence(theFeature, aPoint);
893       anOrphanPoint = true;
894       // if there is at least one concident line to the point, the point is not an orphant
895       if (aCoincidence.get()) {
896         QList<FeaturePtr> aCoinsideLines;
897         QList<FeaturePtr> aCoins;
898         QList<bool> anIsAttributes;
899         PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines, aCoins,
900                                         SketchPlugin_ConstraintCoincidence::ENTITY_A(),
901                                         anIsAttributes);
902         PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines, aCoins,
903                                         SketchPlugin_ConstraintCoincidence::ENTITY_B(),
904                                         anIsAttributes);
905         QList<FeaturePtr>::const_iterator anIt = aCoinsideLines.begin(),
906                                           aLast = aCoinsideLines.end();
907         for (; anIt != aLast && anOrphanPoint; anIt++) {
908           anOrphanPoint = (*anIt)->getKind() != SketchPlugin_Line::ID();
909         }
910       }
911     }
912   }
913   return anOrphanPoint;
914 }
915
916 bool PartSet_WidgetPoint2D::shapeExploreHasVertex(const GeomShapePtr& theShape,
917                                                   const std::shared_ptr<GeomAPI_Pnt2d>& thePoint,
918                                                   const CompositeFeaturePtr& theSketch)
919 {
920   std::shared_ptr<GeomAPI_Pnt> aPoint = PartSet_Tools::point3D(thePoint, theSketch);
921
922   bool aContainPoint = false;
923   GeomAPI_ShapeExplorer anExp(theShape, GeomAPI_Shape::VERTEX);
924   for(; anExp.more() && !aContainPoint; anExp.next()) {
925     std::shared_ptr<GeomAPI_Shape> aVertexInCompSolid = anExp.current();
926     std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex(aVertexInCompSolid));
927     if (aVertex.get())
928       aContainPoint = aPoint->isEqual(aVertex->point());
929   }
930   return aContainPoint;
931 }
932
933 AttributeRefAttrPtr PartSet_WidgetPoint2D::attributeRefAttr() const
934 {
935   AttributeRefAttrPtr anAttribute;
936   if (myRefAttribute.empty())
937     return anAttribute;
938
939   AttributePtr anAttributeRef = feature()->attribute(myRefAttribute);
940   if (!anAttributeRef.get())
941     return anAttribute;
942
943   return std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(anAttributeRef);
944 }
945
946 void PartSet_WidgetPoint2D::fillRefAttribute(double theClickedX, double theClickedY,
947                               const std::shared_ptr<ModuleBase_ViewerPrs>& theValue)
948 {
949   AttributeRefAttrPtr aRefAttr = attributeRefAttr();
950   if (!aRefAttr.get())
951     return;
952
953   FeaturePtr aFeature = feature();
954   std::string anAttribute = attributeID();
955
956   if (aFeature.get()) {
957     std::shared_ptr<GeomAPI_Pnt2d> aClickedPoint = std::shared_ptr<GeomAPI_Pnt2d>(
958                                       new GeomAPI_Pnt2d(theClickedX, theClickedY));
959     AttributePoint2DPtr aClickedFeaturePoint = findFirstEqualPointInSketch(mySketch,
960                                                             aFeature, aClickedPoint);
961     if (aClickedFeaturePoint.get())
962       aRefAttr->setAttr(aClickedFeaturePoint);
963     else {
964       ObjectPtr anObject = getGeomSelection(theValue);
965       if (anObject.get())
966         aRefAttr->setObject(anObject);
967     }
968   }
969 }
970
971 void PartSet_WidgetPoint2D::fillRefAttribute(const ModuleBase_ViewerPrsPtr& theValue)
972 {
973   fillRefAttribute(getGeomSelection(theValue));
974 }
975
976 void PartSet_WidgetPoint2D::fillRefAttribute(const ObjectPtr& theObject)
977 {
978   AttributeRefAttrPtr aRefAttr = attributeRefAttr();
979   if (aRefAttr.get())
980     aRefAttr->setObject(theObject);
981 }
982
983 std::shared_ptr<GeomDataAPI_Point2D> PartSet_WidgetPoint2D::findFirstEqualPointInArgumentFeatures(
984                   const FeaturePtr& theFeature, const std::shared_ptr<GeomAPI_Pnt2d>& thePoint)
985 {
986   std::shared_ptr<GeomDataAPI_Point2D> aFeaturePoint;
987
988   // may be feature is not updated yet, execute is not performed and references features
989   // are not created. Case: rectangle macro feature
990   ModuleBase_Tools::flushUpdated(theFeature);
991
992   std::list<AttributePtr> anAttributes = theFeature->data()->attributes(
993                                           ModelAPI_AttributeRefList::typeId());
994   std::list<AttributePtr>::const_iterator anIt = anAttributes.begin(), aLast = anAttributes.end();
995   for (; anIt != aLast && !aFeaturePoint.get(); anIt++) {
996     std::shared_ptr<ModelAPI_AttributeRefList> aCurSelList =
997                                       std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(*anIt);
998     for (int i = 0, aNb = aCurSelList->size(); i < aNb && !aFeaturePoint.get(); i++) {
999       ObjectPtr anObject = aCurSelList->object(i);
1000       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anObject);
1001       if (aFeature.get())
1002         aFeaturePoint = findFirstEqualPoint(aFeature, thePoint);
1003     }
1004   }
1005   return aFeaturePoint;
1006 }
1007
1008 std::shared_ptr<GeomDataAPI_Point2D> PartSet_WidgetPoint2D::findFirstEqualPoint(
1009                                               const FeaturePtr& theFeature,
1010                                               const std::shared_ptr<GeomAPI_Pnt2d>& thePoint)
1011 {
1012   std::shared_ptr<GeomDataAPI_Point2D> aFPoint;
1013
1014   // find the given point in the feature attributes
1015   std::list<std::shared_ptr<ModelAPI_Attribute> > anAttiributes =
1016                                     theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
1017   std::list<std::shared_ptr<ModelAPI_Attribute> >::const_iterator anIt = anAttiributes.begin(),
1018       aLast = anAttiributes.end();
1019   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
1020
1021   for (; anIt != aLast && !aFPoint; anIt++) {
1022     std::shared_ptr<GeomDataAPI_Point2D> aCurPoint =
1023                                              std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anIt);
1024     if (aCurPoint && aCurPoint->isInitialized() &&
1025         aValidators->isCase(theFeature, aCurPoint->id()) &&
1026         (aCurPoint->pnt()->distance(thePoint) < Precision::Confusion())) {
1027       aFPoint = aCurPoint;
1028       break;
1029     }
1030   }
1031   return aFPoint;
1032 }
1033
1034 std::shared_ptr<GeomDataAPI_Point2D> PartSet_WidgetPoint2D::findFirstEqualPointInSketch(
1035                                     const CompositeFeaturePtr& theSketch,
1036                                     const FeaturePtr& theSkipFeature,
1037                                     const std::shared_ptr<GeomAPI_Pnt2d>& thePoint)
1038 {
1039   // get all sketch features. If the point with the given coordinates belong to any sketch feature,
1040   // the constraint is created between the feature point and the found sketch point
1041   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
1042   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
1043       ModelAPI_AttributeRefList>(aData->attribute(SketchPlugin_Sketch::FEATURES_ID()));
1044
1045   std::list<ObjectPtr> aFeatures = aRefList->list();
1046   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
1047   std::list<std::shared_ptr<ModelAPI_Attribute> > anAttiributes;
1048
1049   std::shared_ptr<GeomDataAPI_Point2D> aFPoint;
1050   for (; anIt != aLast; anIt++) {
1051     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
1052     if (!aFeature.get() || (theSkipFeature.get() && theSkipFeature == aFeature))
1053       continue;
1054     aFPoint = PartSet_WidgetPoint2D::findFirstEqualPoint(aFeature, thePoint);
1055     if (aFPoint.get())
1056       break;
1057   }
1058   return aFPoint;
1059 }
1060
1061 ObjectPtr PartSet_WidgetPoint2D::getGeomSelection(const ModuleBase_ViewerPrsPtr& theValue)
1062 {
1063   ObjectPtr anObject;
1064   GeomShapePtr aShape;
1065   ModuleBase_ISelection* aSelection = myWorkshop->selection();
1066   anObject = aSelection->getResult(theValue);
1067   aShape = aSelection->getShape(theValue);
1068   myExternalObjectMgr->getGeomSelection(theValue, anObject, aShape, myWorkshop, sketch(), true);
1069
1070   return anObject;
1071 }