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