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