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