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