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