Salome HOME
1. Correction for perfomance problem by Apply button state update: do not listen...
[modules/shaper.git] / src / PartSet / PartSet_WidgetPoint2d.cpp
index d34128d1643ab53de997642e8847f87117f56109..29b8cf03d4f4b677b9687c81defbe436884fda12 100644 (file)
@@ -7,18 +7,26 @@
 #include "PartSet_WidgetPoint2d.h"
 #include <PartSet_Tools.h>
 #include <PartSet_Module.h>
+#include <PartSet_SketcherReetntrantMgr.h>
+
+#include <XGUI_Tools.h>
+#include <XGUI_Workshop.h>
+#include <XGUI_Displayer.h>
 
 #include <ModuleBase_ParamSpinBox.h>
 #include <ModuleBase_Tools.h>
 #include <ModuleBase_IViewer.h>
 #include <ModuleBase_IViewWindow.h>
 #include <ModuleBase_ISelection.h>
+#include <ModuleBase_ViewerPrs.h>
+#include <ModuleBase_WidgetValidator.h>
 
 #include <Config_Keywords.h>
 #include <Config_WidgetAPI.h>
 
 #include <Events_Loop.h>
 #include <ModelAPI_Events.h>
+#include <ModelAPI_AttributeBoolean.h>
 
 #include <ModelAPI_Feature.h>
 #include <ModelAPI_Data.h>
@@ -26,6 +34,9 @@
 #include <GeomDataAPI_Point2D.h>
 #include <GeomAPI_Pnt2d.h>
 
+#include <GeomAPI_ShapeExplorer.h>
+#include <GeomAPI_Vertex.h>
+
 #include <SketchPlugin_Feature.h>
 #include <SketchPlugin_ConstraintCoincidence.h>
 #include <SketchPlugin_Line.h>
@@ -53,9 +64,10 @@ static QStringList MyFeaturesForCoincedence;
 
 PartSet_WidgetPoint2D::PartSet_WidgetPoint2D(QWidget* theParent, 
                                              ModuleBase_IWorkshop* theWorkshop,
-                                             const Config_WidgetAPI* theData,
-                                             const std::string& theParentId)
- : ModuleBase_ModelWidget(theParent, theData, theParentId), myWorkshop(theWorkshop)
+                                             const Config_WidgetAPI* theData)
+: ModuleBase_ModelWidget(theParent, theData), myWorkshop(theWorkshop),
+  myValueIsCashed(false), myIsFeatureVisibleInCash(true),
+  myXValueInCash(0), myYValueInCash(0)
 {
   if (MyFeaturesForCoincedence.isEmpty()) {
     MyFeaturesForCoincedence << SketchPlugin_Line::ID().c_str()
@@ -109,6 +121,58 @@ PartSet_WidgetPoint2D::PartSet_WidgetPoint2D(QWidget* theParent,
   ModuleBase_Tools::zeroMargins(aLayout);
   aLayout->addWidget(myGroupBox);
   setLayout(aLayout);
+
+  myWidgetValidator = new ModuleBase_WidgetValidator(this, myWorkshop);
+}
+
+bool PartSet_WidgetPoint2D::isValidSelectionCustom(const ModuleBase_ViewerPrsPtr& theValue)
+{
+  bool aValid = true;
+
+  PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(myWorkshop->module());
+  if (aModule->sketchReentranceMgr()->isInternalEditActive()) 
+    return true; /// when internal edit is started a new feature is created. I has not results, AIS
+
+  // workaround for feature, where there is no results
+  //if (myFeature->getKind() == "SketchRectangle")
+  //  return true;
+
+  /// the selection is not possible if the current feature has no presentation for the current
+  /// attribute not in AIS not in results. If so, no object in current feature where make
+  /// coincidence, so selection is not necessary
+  std::shared_ptr<ModelAPI_Data> aData = myFeature->data();
+  std::shared_ptr<GeomDataAPI_Point2D> aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
+      aData->attribute(attributeID()));
+  std::shared_ptr<GeomAPI_Pnt2d> aPoint = aPointAttr->pnt();
+
+  bool aFoundPoint = false;
+  GeomShapePtr anAISShape;
+  GeomPresentablePtr aPrs = std::dynamic_pointer_cast<GeomAPI_IPresentable>(myFeature);
+  if (aPrs.get()) {
+    AISObjectPtr anAIS;
+    anAIS = aPrs->getAISObject(anAIS);
+    if (anAIS.get()) {
+      anAISShape = anAIS->getShape();
+    }
+  }
+  const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = myFeature->results();
+  if (!anAISShape.get() && aResults.empty())
+    return true;
+
+  /// analysis of AIS
+  if (anAISShape.get())
+    aFoundPoint = shapeContainsPoint(anAISShape, aPoint, mySketch);
+
+  /// analysis of results
+  std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
+  for (; aRIter != aResults.cend() && !aFoundPoint; aRIter++) {
+    ResultPtr aResult = *aRIter;
+    if (aResult.get() && aResult->shape().get()) {
+      GeomShapePtr aShape = aResult->shape();
+      aFoundPoint = shapeContainsPoint(aShape, aPoint, mySketch);
+    }
+  }
+  return aFoundPoint;
 }
 
 bool PartSet_WidgetPoint2D::resetCustom()
@@ -118,14 +182,21 @@ bool PartSet_WidgetPoint2D::resetCustom()
     aDone = false;
   }
   else {
-    bool isOk;
-    double aDefValue = QString::fromStdString(getDefaultValue()).toDouble(&isOk);
-    // it is important to block the spin box control in order to do not through out the
-    // locking of the validating state.
-    ModuleBase_Tools::setSpinValue(myXSpin, isOk ? aDefValue : 0.0);
-    ModuleBase_Tools::setSpinValue(myYSpin, isOk ? aDefValue : 0.0);
-    storeValueCustom();
-    aDone = true;
+    if (myValueIsCashed) {
+      // if the restored value should be hidden, aDone = true to set
+      // reset state for the widget in the parent
+      aDone = restoreCurentValue();
+    }
+    else {
+      bool isOk;
+      double aDefValue = QString::fromStdString(getDefaultValue()).toDouble(&isOk);
+      // it is important to block the spin box control in order to do not through out the
+      // locking of the validating state.
+      ModuleBase_Tools::setSpinValue(myXSpin, isOk ? aDefValue : 0.0);
+      ModuleBase_Tools::setSpinValue(myYSpin, isOk ? aDefValue : 0.0);
+      storeValueCustom();
+      aDone = true;
+    }
   }
   return aDone;
 }
@@ -134,26 +205,27 @@ PartSet_WidgetPoint2D::~PartSet_WidgetPoint2D()
 {
 }
 
-bool PartSet_WidgetPoint2D::setSelection(QList<ModuleBase_ViewerPrs>& theValues,
+bool PartSet_WidgetPoint2D::setSelection(QList<ModuleBase_ViewerPrsPtr>& theValues,
                                          const bool theToValidate)
 {
   bool isDone = false;
   if (theValues.empty())
     return isDone;
 
-  ModuleBase_ViewerPrs aValue = theValues.takeFirst();
-  TopoDS_Shape aShape = aValue.shape();
-  if (!aShape.IsNull()) {
+  ModuleBase_ViewerPrsPtr aValue = theValues.takeFirst();
+  GeomShapePtr aShape = aValue->shape();
+  if (aShape.get() && !aShape->isNull()) {
     Handle(V3d_View) aView = myWorkshop->viewer()->activeView();
     double aX, aY;
-    if (getPoint2d(aView, aShape, aX, aY)) {
+    const TopoDS_Shape& aTDShape = aShape->impl<TopoDS_Shape>();
+    if (getPoint2d(aView, aTDShape, aX, aY)) {
       isDone = setPoint(aX, aY);
       PartSet_Tools::setConstraints(mySketch, feature(), attributeID(), aX, aY);
     }
   }
   else if (canBeActivatedByMove()) {
     if (feature()->getKind() == SketchPlugin_Line::ID()) {
-      FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aValue.object());
+      FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aValue->object());
       // Initialize new line with first point equal to end of previous
       if (aFeature.get()) {
         std::shared_ptr<ModelAPI_Data> aData = aFeature->data();
@@ -191,7 +263,7 @@ bool PartSet_WidgetPoint2D::setPoint(double theX, double theY)
   return true;
 }
 
-bool PartSet_WidgetPoint2D::storeValueCustom() const
+bool PartSet_WidgetPoint2D::storeValueCustom()
 {
   std::shared_ptr<ModelAPI_Data> aData = myFeature->data();
   if (!aData) // can be on abort of sketcher element
@@ -256,6 +328,43 @@ bool PartSet_WidgetPoint2D::restoreValueCustom()
   return true;
 }
 
+void PartSet_WidgetPoint2D::storeCurentValue()
+{
+  // do not use cash if a variable is used
+  if (myXSpin->hasVariable() || myYSpin->hasVariable())
+    return;
+
+  myValueIsCashed = true;
+  myIsFeatureVisibleInCash = XGUI_Displayer::isVisible(
+                       XGUI_Tools::workshop(myWorkshop)->displayer(), myFeature);
+  myXValueInCash = myXSpin->value();
+  myYValueInCash = myYSpin->value();
+}
+
+bool PartSet_WidgetPoint2D::restoreCurentValue()
+{
+  bool aRestoredAndHidden = true;
+
+  bool isVisible = myIsFeatureVisibleInCash;
+  // fill the control widgets by the cashed value
+
+  myValueIsCashed = false;
+  myIsFeatureVisibleInCash = true;
+  ModuleBase_Tools::setSpinValue(myXSpin, myXValueInCash);
+  ModuleBase_Tools::setSpinValue(myYSpin, myYValueInCash);
+
+  // store value to the model
+  storeValueCustom();
+  if (isVisible) {
+    setValueState(Stored);
+    aRestoredAndHidden = false;
+  }
+  else
+    aRestoredAndHidden = true;
+
+  return aRestoredAndHidden;
+}
+
 QList<QWidget*> PartSet_WidgetPoint2D::getControls() const
 {
   QList<QWidget*> aControls;
@@ -277,6 +386,12 @@ void PartSet_WidgetPoint2D::activateCustom()
   aModes << TopAbs_VERTEX;
   aModes << TopAbs_EDGE;
   myWorkshop->activateSubShapesSelection(aModes);
+
+  if (!isEditingMode()) {
+    FeaturePtr aFeature = feature();
+    if (aFeature.get() && aFeature->getKind() == SketchPlugin_Point::ID())
+      storeValue();
+  }
 }
 
 bool PartSet_WidgetPoint2D::canBeActivatedByMove()
@@ -327,24 +442,44 @@ bool PartSet_WidgetPoint2D::getPoint2d(const Handle(V3d_View)& theView,
   return false;
 }
 
-void PartSet_WidgetPoint2D::setConstraintWith(const ObjectPtr& theObject)
+bool PartSet_WidgetPoint2D::setConstraintWith(const ObjectPtr& theObject)
 {
+  std::shared_ptr<GeomDataAPI_Point2D> aFeaturePoint;
+  if (feature()->isMacro()) {
+    AttributePtr aThisAttr = feature()->data()->attribute(attributeID());
+    std::shared_ptr<GeomDataAPI_Point2D> anAttrPoint =
+                               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aThisAttr);
+    if (anAttrPoint.get()) {
+      // the macro feature will be removed after the operation is stopped, so we need to build
+      // coicidence to possible sub-features
+      aFeaturePoint = PartSet_Tools::findFirstEqualPointInArgumentFeatures(feature(),
+                                                                 anAttrPoint->pnt());
+    }
+  }
+  else {
+    AttributePtr aThisAttr = feature()->data()->attribute(attributeID());
+    aFeaturePoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aThisAttr);
+  }
+  if (!aFeaturePoint.get())
+    return false;
+
   // Create point-edge coincedence
   FeaturePtr aFeature = mySketch->addFeature(SketchPlugin_ConstraintCoincidence::ID());
   std::shared_ptr<ModelAPI_Data> aData = aFeature->data();
 
   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef1 = std::dynamic_pointer_cast<
       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
-  AttributePtr aThisAttr = feature()->data()->attribute(attributeID());
-  std::shared_ptr<GeomDataAPI_Point2D> aThisPoint = 
-    std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aThisAttr);
-  aRef1->setAttr(aThisPoint);
+
+  aRef1->setAttr(aFeaturePoint);
 
   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef2 = std::dynamic_pointer_cast<
       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
   aRef2->setObject(theObject);
 
-  aFeature->execute();
+  // we need to flush created signal in order to coincidence is processed by solver
+  Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
+
+  return true;
 }
 
 void PartSet_WidgetPoint2D::onMouseRelease(ModuleBase_IViewWindow* theWnd, QMouseEvent* theEvent)
@@ -355,25 +490,27 @@ void PartSet_WidgetPoint2D::onMouseRelease(ModuleBase_IViewWindow* theWnd, QMous
 
   ModuleBase_ISelection* aSelection = myWorkshop->selection();
   Handle(V3d_View) aView = theWnd->v3dView();
-  // TODO: This fragment doesn't work because bug in OCC Viewer. It can be used after fixing.
-  NCollection_List<TopoDS_Shape> aShapes;
-  std::list<ObjectPtr> aObjects;
-  aSelection->selectedShapes(aShapes, aObjects);
+
+  QList<ModuleBase_ViewerPrsPtr> aList = aSelection->getSelected(ModuleBase_ISelection::Viewer);
+  ModuleBase_ViewerPrsPtr aFirstValue = aList.size() > 0 ? aList.first() : ModuleBase_ViewerPrsPtr();
   // if we have selection and use it
-  if (aShapes.Extent() > 0 && useSelectedShapes()) {
-    TopoDS_Shape aShape = aShapes.First();
-    ObjectPtr aObject = aObjects.front();
+  if (aFirstValue.get() && isValidSelectionCustom(aFirstValue)) {
+    GeomShapePtr aGeomShape = aFirstValue->shape();
+    TopoDS_Shape aShape = aGeomShape->impl<TopoDS_Shape>();
+    ObjectPtr aObject = aFirstValue->object();
+
     FeaturePtr aSelectedFeature = ModelAPI_Feature::feature(aObject);
     bool anExternal = false;
-      std::shared_ptr<SketchPlugin_Feature> aSPFeature;
-      if (aSelectedFeature.get() != NULL)
-        aSPFeature = std::dynamic_pointer_cast<SketchPlugin_Feature>(aSelectedFeature);
-      if ((!aSPFeature) && (!aShape.IsNull())) {
+    std::shared_ptr<SketchPlugin_Feature> aSPFeature;
+    if (aSelectedFeature.get() != NULL)
+      aSPFeature = std::dynamic_pointer_cast<SketchPlugin_Feature>(aSelectedFeature);
+      if ((!aSPFeature && !aShape.IsNull()) ||
+          (aSPFeature.get() && aSPFeature->isExternal())) {
+        ResultPtr aFixedObject;
         anExternal = true;
-        ResultPtr aFixedObject = PartSet_Tools::findFixedObjectByExternal(aShape, aObject, mySketch);
+        aFixedObject = PartSet_Tools::findFixedObjectByExternal(aShape, aObject, mySketch);
         if (!aFixedObject.get())
-          aObject = PartSet_Tools::createFixedObjectByExternal(aShape, aObject, mySketch);
-
+          aFixedObject = PartSet_Tools::createFixedObjectByExternal(aShape, aObject, mySketch);
         double aX, aY;
         if (getPoint2d(aView, aShape, aX, aY) && isFeatureContainsPoint(myFeature, aX, aY)) {
           // do not create a constraint to the point, which already used by the feature
@@ -387,12 +524,24 @@ void PartSet_WidgetPoint2D::onMouseRelease(ModuleBase_IViewWindow* theWnd, QMous
             setValueState(Stored); // in case of edge selection, Apply state should also be updated
           bool anOrphanPoint = aShape.ShapeType() == TopAbs_VERTEX ||
                                isOrphanPoint(aSelectedFeature, mySketch, aX, aY);
-          setConstraintWith(aObject);
+          if (anExternal) {
+            anOrphanPoint = true; // we should not stop reentrant operation on external objects because
+            // they are not participate in the contour creation excepting external vertices
+            if (aShape.ShapeType() == TopAbs_VERTEX) {
+              FeaturePtr aFixedFeature = ModelAPI_Feature::feature(aFixedObject);
+              if (aFixedFeature.get() && aFixedFeature->getKind() == SketchPlugin_Point::ID()) {
+                anOrphanPoint = isOrphanPoint(aFixedFeature, mySketch, aX, aY);
+              }
+            }
+          }
+          if (aFixedObject.get())
+            setConstraintWith(aFixedObject);
           // fignal updated should be flushed in order to visualize possible created external objects
           // e.g. selection of trihedron axis when input end arc point
           updateObject(feature());
-          if (!anOrphanPoint && !anExternal)
-            emit vertexSelected();
+
+          if (!anOrphanPoint)
+            emit vertexSelected(); // it stops the reentrant operation
 
           emit focusOutWidget(this);
         }
@@ -410,15 +559,20 @@ void PartSet_WidgetPoint2D::onMouseRelease(ModuleBase_IViewWindow* theWnd, QMous
         // do not set a coincidence constraint in the attribute if the feature contains a point
         // with the same coordinates. It is important for line creation in order to do not set
         // the same constraints for the same points, oterwise the result line has zero length.
+        bool isAuxiliaryFeature = false;
         if (getPoint2d(aView, aShape, aX, aY)) {
           setPoint(aX, aY);
+          feature()->execute();
           PartSet_Tools::setConstraints(mySketch, feature(), attributeID(), aX, aY);
         }
         else if (aShape.ShapeType() == TopAbs_EDGE) {
-          if (MyFeaturesForCoincedence.contains(myFeature->getKind().c_str())) {
-            setConstraintWith(aObject);
-            setValueState(Stored); // in case of edge selection, Apply state should also be updated
+          if (!setConstraintWith(aObject)) {
+            gp_Pnt aPoint = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWnd->v3dView());
+            PartSet_Tools::convertTo2D(aPoint, mySketch, aView, aX, aY);
+            setPoint(aX, aY);
           }
+          setValueState(Stored); // in case of edge selection, Apply state should also be updated
+          isAuxiliaryFeature = PartSet_Tools::isAuxiliarySketchEntity(aObject);
         }
         // it is important to perform updateObject() in order to the current value is 
         // processed by Sketch Solver. Test case: line is created from a previous point
@@ -427,7 +581,7 @@ void PartSet_WidgetPoint2D::onMouseRelease(ModuleBase_IViewWindow* theWnd, QMous
         // points of the line becomes less than the tolerance. Validator of the line returns
         // false, the line will be aborted, but sketch stays valid.
         updateObject(feature());
-        if (!anOrphanPoint && !anExternal)
+        if (!anOrphanPoint && !anExternal && !isAuxiliaryFeature)
           emit vertexSelected();
         emit focusOutWidget(this);
       }
@@ -473,6 +627,8 @@ void PartSet_WidgetPoint2D::onMouseMove(ModuleBase_IViewWindow* theWnd, QMouseEv
 
   double aX, anY;
   PartSet_Tools::convertTo2D(aPoint, mySketch, theWnd->v3dView(), aX, anY);
+  if (myState != ModifiedInViewer)
+    storeCurentValue();
   // we need to block the value state change 
   bool isBlocked = blockValueState(true);
   setPoint(aX, anY);
@@ -577,14 +733,17 @@ bool PartSet_WidgetPoint2D::isOrphanPoint(const FeaturePtr& theFeature,
 
     if (aPointAttr.get()) {
       std::shared_ptr<GeomAPI_Pnt2d> aPoint = aPointAttr->pnt();
+      // we need to find coincidence features in results also, because external object(point)
+      // uses refs to me in another feature.
       FeaturePtr aCoincidence = PartSet_Tools::findFirstCoincidence(theFeature, aPoint);
       anOrphanPoint = true;
       // if there is at least one concident line to the point, the point is not an orphant
       if (aCoincidence.get()) {
         QList<FeaturePtr> aCoinsideLines;
-        PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines,
+        QList<FeaturePtr> aCoins;
+        PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines, aCoins,
                                         SketchPlugin_ConstraintCoincidence::ENTITY_A());
-        PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines,
+        PartSet_Tools::findCoincidences(aCoincidence, aCoinsideLines, aCoins,
                                         SketchPlugin_ConstraintCoincidence::ENTITY_B());
         QList<FeaturePtr>::const_iterator anIt = aCoinsideLines.begin(),
                                           aLast = aCoinsideLines.end();
@@ -596,3 +755,20 @@ bool PartSet_WidgetPoint2D::isOrphanPoint(const FeaturePtr& theFeature,
   }
   return anOrphanPoint;
 }
+
+bool PartSet_WidgetPoint2D::shapeContainsPoint(const GeomShapePtr& theShape,
+                                               const std::shared_ptr<GeomAPI_Pnt2d>& thePoint,
+                                               const CompositeFeaturePtr& theSketch)
+{
+  std::shared_ptr<GeomAPI_Pnt> aPoint = PartSet_Tools::point3D(thePoint, theSketch);
+
+  bool aContainPoint = false;
+  GeomAPI_ShapeExplorer anExp(theShape, GeomAPI_Shape::VERTEX);
+  for(; anExp.more() && !aContainPoint; anExp.next()) {
+    std::shared_ptr<GeomAPI_Shape> aVertexInCompSolid = anExp.current();
+    std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex(aVertexInCompSolid));
+    if (aVertex.get())
+      aContainPoint = aPoint->isEqual(aVertex->point());
+  }
+  return aContainPoint;
+}