Salome HOME
updated copyright message
[modules/shaper.git] / src / ModuleBase / ModuleBase_ParamSpinBox.cpp
index f559eb68ae905e635206739f874b6c9a1fc10958..9c9cc761329f1a34dc7c03becabc4e3864fabac0 100644 (file)
@@ -1,13 +1,25 @@
-#include "ModuleBase_ParamSpinBox.h"
+// Copyright (C) 2014-2023  CEA, EDF
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
 
-#include <ModelAPI_Session.h>
-#include <ModelAPI_Document.h>
-#include <ModelAPI_ResultParameter.h>
-#include <ModelAPI_AttributeDouble.h>
-#include <ModelAPI_Tools.h>
+#include "ModuleBase_ParamSpinBox.h"
 
 #include <QKeyEvent>
-#include <QLineEdit>
 #include <QLocale>
 #include <QRegExp>
 #include <QToolTip>
 
 #include <QStringListModel>
 #include <QCompleter>
+#include <QAbstractItemView>
 #include <QShortcut>
 
 #include <string>
 #include <iostream>
+#include <cfloat>
 
-//#define DEBUG_COMPLETE_WITH_PARAMETERS
+
+bool isVariableSymbol(const QChar& theChar) {
+  if (theChar.isLetterOrNumber())
+    return true;
+  if (theChar == '_')
+    return true;
+  return false;
+}
 
 ModuleBase_ParamSpinBox::ModuleBase_ParamSpinBox(QWidget* theParent, int thePrecision)
-    : ModuleBase_DoubleSpinBox(theParent, thePrecision),
-      myAcceptVariables(true)
+  : QAbstractSpinBox(theParent),
+  myIsEquation(false),
+  myAcceptVariables(true),
+  myMinimum(-DBL_MAX),
+  myMaximum(DBL_MAX),
+  mySingleStep(1)
 {
-#ifdef DEBUG_COMPLETE_WITH_PARAMETERS
   myCompleter = new QCompleter(this);
-  myCompleter->setWidget(this);
+  myCompleter->setWidget(lineEdit());
   myCompleter->setCompletionMode(QCompleter::PopupCompletion);
 
   myCompleterModel = new QStringListModel(this);
   myCompleter->setModel(myCompleterModel);
-  // Use sorted model to accelerate completion (QCompleter will use binary search)
-  myCompleter->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
-  myCompleter->setCaseSensitivity(Qt::CaseInsensitive);
+  connect(myCompleter, SIGNAL(highlighted(const QString&)),
+    this, SLOT(insertCompletion(const QString&)));
+
+  QAbstractItemView* aPopup = myCompleter->popup();
+  aPopup->installEventFilter(this);
 
-  lineEdit()->setCompleter(myCompleter);
-#endif
+  //  connectSignalsAndSlots();
+  myEnabledBaseColor = palette().color(QPalette::Active, QPalette::Base);
+  connect(lineEdit(), SIGNAL(textChanged(const QString&)),
+    this, SLOT(onTextChanged(const QString&)));
 
-  connectSignalsAndSlots();
+  setLocale(QLocale::c());
+
+  myValidator = new QDoubleValidator(this);
+  myValidator->setLocale(locale());
+  myValidator->setRange(myMinimum, myMaximum);
+  myValidator->setDecimals(thePrecision);
 }
 
 void ModuleBase_ParamSpinBox::setCompletionList(QStringList& theList)
 {
-#ifdef DEBUG_COMPLETE_WITH_PARAMETERS
-  theList.sort();
   theList.removeDuplicates();
+  theList.sort();
   myCompleterModel->setStringList(theList);
-#endif
+
+  QAbstractItemView* aPopup = myCompleter->popup();
+  QFontMetrics aMetric = aPopup->fontMetrics();
+  int aWidth = 0;
+  QRect aRect;
+  foreach(QString aStr, theList) {
+    aRect = aMetric.boundingRect(aStr);
+    if (aRect.width() > aWidth)
+      aWidth = aRect.width();
+  }
+  aPopup->setMinimumWidth(aWidth + 25);
 }
 
 /*!
@@ -59,6 +101,7 @@ ModuleBase_ParamSpinBox::~ModuleBase_ParamSpinBox()
 {
 }
 
+
 /*!
  \brief Perform \a steps increment/decrement steps.
 
@@ -70,42 +113,21 @@ ModuleBase_ParamSpinBox::~ModuleBase_ParamSpinBox()
  */
 void ModuleBase_ParamSpinBox::stepBy(int steps)
 {
-  if ((!myTextValue.isEmpty()) && hasVariable())
+  if (hasVariable())
     return;
 
-  ModuleBase_DoubleSpinBox::stepBy(steps);
+  double aVal = lineEdit()->text().toDouble();
+  aVal += steps * mySingleStep;
+  setValue(aVal);
+  //QAbstractSpinBox::stepBy(steps);
 }
 
-/*!
- \brief Connect signals and slots.
- */
-void ModuleBase_ParamSpinBox::connectSignalsAndSlots()
+void ModuleBase_ParamSpinBox::onTextChanged(const QString& theText)
 {
-  connect(this, SIGNAL(valueChanged(const QString&)),
-          this, SLOT(onTextChanged(const QString&)));
+  myIsEquation = hasVariable(theText);
+  emit textChanged(theText);
 }
 
-void ModuleBase_ParamSpinBox::onTextChanged(const QString& text)
-{
-  myTextValue = text;
-}
-
-double ModuleBase_ParamSpinBox::valueFromText(const QString& theText) const
-{
-  if (!hasVariable(theText))
-    return ModuleBase_DoubleSpinBox::valueFromText(theText);
-
-  // small hack: return hash of the string to initiate valuesChanged signal
-  return qHash(theText);
-}
-
-QString ModuleBase_ParamSpinBox::textFromValue (double theValue) const
-{
-  if ((!myTextValue.isEmpty()) && hasVariable(myTextValue)){
-    return myTextValue;
-  }
-  return ModuleBase_DoubleSpinBox::textFromValue(theValue);
-}
 
 /*!
  \brief This function is used to determine whether input is valid.
@@ -116,14 +138,14 @@ QString ModuleBase_ParamSpinBox::textFromValue (double theValue) const
 QValidator::State ModuleBase_ParamSpinBox::validate(QString& str, int& pos) const
 {
   // Trying to interpret the current input text as a numeric value
-  if (!hasVariable(str))
-    return ModuleBase_DoubleSpinBox::validate(str, pos);
-
-  QValidator::State res = QValidator::Invalid;
-  if (isAcceptVariables()) {
-    res = QValidator::Acceptable;
+  if (!hasVariable(str)) {
+    /// If decimals = 0 do not accept '.' (interpret as int)
+    if ((myValidator->decimals() == 0) && str.endsWith('.'))
+      return QValidator::Invalid;
+    return myValidator->validate(str, pos);
   }
-  return res;
+
+  return isAcceptVariables() ? QValidator::Acceptable : QValidator::Invalid;
 }
 
 /*!
@@ -132,13 +154,25 @@ QValidator::State ModuleBase_ParamSpinBox::validate(QString& str, int& pos) cons
 
  The new value is ignored if the spinbox has a variable.
  */
-void ModuleBase_ParamSpinBox::setValue(const double value)
+void ModuleBase_ParamSpinBox::setValue(double value)
 {
-  if (hasVariable())
-    return;
+  myIsEquation = false;
+  double aVal = value;
+  if (aVal < myMinimum)
+    aVal = myMinimum;
+  else if (aVal > myMaximum)
+    aVal = myMaximum;
+  QString aText = (myValidator->decimals() == 0) ? QString::number((int)aVal) :
+    QString::number(aVal, 'g', decimals());
+  lineEdit()->blockSignals(true);
+  lineEdit()->setText(aText);
+  lineEdit()->blockSignals(false);
+  emit textChanged(aText);
+}
 
-  myTextValue = ModuleBase_DoubleSpinBox::textFromValue(value);
-  ModuleBase_DoubleSpinBox::setValue(value);
+double ModuleBase_ParamSpinBox::value() const
+{
+  return lineEdit()->text().toDouble();
 }
 
 /*!
@@ -147,8 +181,17 @@ void ModuleBase_ParamSpinBox::setValue(const double value)
  */
 void ModuleBase_ParamSpinBox::setText(const QString& value)
 {
-  myTextValue = value;
-  lineEdit()->setText(value);
+  myIsEquation = hasVariable(value);
+  if (myAcceptVariables && myIsEquation) {
+    lineEdit()->setText(value);
+    emit textChanged(value);
+  }
+  else {
+    bool isConv = false;
+    double aVal = value.toDouble(&isConv);
+    if (isConv)
+      setValue(aVal);
+  }
 }
 
 /*!
@@ -159,6 +202,9 @@ void ModuleBase_ParamSpinBox::setText(const QString& value)
 void ModuleBase_ParamSpinBox::setAcceptVariables(const bool flag)
 {
   myAcceptVariables = flag;
+  if ((!myAcceptVariables) && myIsEquation) {
+    setValue(0);
+  }
 }
 
 /*!
@@ -171,100 +217,137 @@ bool ModuleBase_ParamSpinBox::isAcceptVariables() const
 
 bool ModuleBase_ParamSpinBox::hasVariable() const
 {
-  if (myTextValue.isEmpty())
-    return false;
-  return hasVariable(myTextValue);
+  return myIsEquation;
 }
 
 bool ModuleBase_ParamSpinBox::hasVariable(const QString& theText) const
 {
-  //const QString aDigitPattern = QString("[-+]?[0-9]*[%1]?[0-9]*([eE][-+]?[0-9]+)?");
-
-  //bool aHasDigit = false;
-  //{
-  //  QRegExp varNameMask(aDigitPattern.arg("."));
-  //  aHasDigit = varNameMask.exactMatch(theText);
-  //}
-  //if (!aHasDigit)
-  //{
-  //  QRegExp varNameMask(aDigitPattern.arg(","));
-  //  aHasDigit = varNameMask.exactMatch(theText);
-  //}
   bool isDouble = false;
   QLocale::c().toDouble(theText, &isDouble);
-
-//  theText.toDouble(&isDouble);
-//  if (isDouble) {
-//    QLocale aLoc; // create default locale
-//    QChar aDecPnt = aLoc.decimalPoint();
-//    if (aDecPnt == '.')
-//      isDouble = theText.contains(aDecPnt) || (!theText.contains(','));
-//    else if (aDecPnt == ',')
-//      isDouble = theText.contains(aDecPnt) || (!theText.contains('.'));
-//  }
   return !isDouble;
 }
 
-/*!
- \brief This function is used to determine whether input is valid.
- \return validating operation result
- */
-ModuleBase_ParamSpinBox::State ModuleBase_ParamSpinBox::isValid(const QString& theText,
-                                                                double& theValue) const
+void ModuleBase_ParamSpinBox::showCompletion(bool checkPrefix)
 {
-  if (hasVariable() && !findVariable(theText, theValue)) {
-    bool ok = false;
-    theValue = locale().toDouble(theText, &ok);
-    if (!ok) {
-      return NoVariable;
+  myCompletePos = lineEdit()->cursorPosition();
+  int aStart, aEnd;
+  QString aPrefix;
+  aPrefix = getPrefix(aStart, aEnd);
+  if (checkPrefix) {
+    if (aPrefix.length() > 0) {
+      myCompleter->setCompletionPrefix(aPrefix);
+      myCompleter->complete();
     }
+  } else {
+    myCompleter->setCompletionPrefix(aPrefix);
+    myCompleter->complete();
   }
-  if (!checkRange(theValue)) {
-    return Invalid;
-  }
+}
+
+void ModuleBase_ParamSpinBox::keyReleaseEvent(QKeyEvent* e)
+{
+  QString aText;
 
-  return Acceptable;
+  switch (e->key()) {
+  case Qt::Key_Backspace:
+    if (myCompleter->popup()->isVisible()) {
+      myCompleter->popup()->hide();
+    }
+    showCompletion(true);
+    break;
+  case Qt::Key_Return:
+  case Qt::Key_Enter:
+    if (myCompleter->popup()->isVisible()) {
+      myCompleter->popup()->hide();
+      myIsEquation = true;
+    }
+    emit textChanged(lineEdit()->text());
+    break;
+  case Qt::Key_Space:
+    if (e->modifiers() & Qt::ControlModifier) {
+      showCompletion(false);
+    }
+    break;  default:
+    aText = e->text();
+    if (aText.length() == 1) {
+      QChar aChar = aText.at(0);
+      if (isVariableSymbol(aChar)) {
+        showCompletion(true);
+      }
+    }
+  }
+  QAbstractSpinBox::keyReleaseEvent(e);
 }
 
-/*!
- \brief This function is used to check that string value lies within predefined range.
- \return check status
- */
-bool ModuleBase_ParamSpinBox::checkRange(const double theValue) const
+bool ModuleBase_ParamSpinBox::eventFilter(QObject* theObj, QEvent* theEvent)
 {
-  return theValue >= minimum() && theValue <= maximum();
+  if (theEvent->type() == QEvent::KeyRelease) {
+    keyReleaseEvent((QKeyEvent*)theEvent);
+  }
+  return QAbstractSpinBox::eventFilter(theObj, theEvent);
 }
 
-/*!
- \brief This function is used to determine whether input is a variable name and to get its value.
- \return status of search operation
- */
-bool ModuleBase_ParamSpinBox::findVariable(const QString& theName,
-                                           double& outValue) const
+
+QString ModuleBase_ParamSpinBox::getPrefix(int& theStart, int& theEnd) const
 {
-  ResultParameterPtr aParam;
-  return ModelAPI_Tools::findVariable(theName.toStdString(), outValue, aParam);
+  QString aPrefix;
+  QString aText = lineEdit()->text();
+  theStart = theEnd = myCompletePos;
+  const int aLen = aText.length();
+  if (aLen > 0) {
+    if (myCompletePos > 0) {
+      int aLastChar = myCompletePos - 1;
+      QChar aChar = aText.at(aLastChar);
+      while (isVariableSymbol(aChar)) {
+        aPrefix.prepend(aText.at(aLastChar));
+        aLastChar--;
+        if (aLastChar < 0)
+          break;
+        aChar = aText.at(aLastChar);
+      }
+      theStart = aLastChar + 1;
+    }
+    if (myCompletePos < aLen) {
+      int aLastChar = myCompletePos;
+      QChar aChar = aText.at(aLastChar);
+      while (isVariableSymbol(aChar)) {
+        aPrefix.append(aText.at(aLastChar));
+        aLastChar++;
+        if (aLastChar >= aLen)
+          break;
+        aChar = aText.at(aLastChar);
+      }
+      theEnd = aLastChar;
+    }
+  }
+  return aPrefix;
 }
 
-/*!
- \brief This function is called when the spinbox receives key press event.
- */
-//void ModuleBase_ParamSpinBox::keyPressEvent(QKeyEvent* e)
-//{
-//  if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {
-//    QWidget::keyPressEvent(e);
-//  } else {
-//    ModuleBase_DoubleSpinBox::keyPressEvent(e);
-//  }
-//}
 
-/*!
- \brief This function is called when the spinbox receives show event.
- */
-void ModuleBase_ParamSpinBox::showEvent(QShowEvent* theEvent)
+void ModuleBase_ParamSpinBox::insertCompletion(const QString& theText)
 {
-  ModuleBase_DoubleSpinBox::showEvent(theEvent);
-  if ((!myTextValue.isEmpty()) && hasVariable(myTextValue)) {
-    setText(myTextValue);
+  QString aText = lineEdit()->text();
+  int aStart, aEnd;
+  QString aPrefix = getPrefix(aStart, aEnd);
+
+  QString aResult;
+  int aPrefLen = aPrefix.length();
+  if (aPrefLen == 0)
+    aResult = aText.insert(myCompletePos, theText);
+  else {
+    aResult = aText.left(aStart) + theText + aText.right(aText.length() - aEnd);
   }
+  lineEdit()->setText(aResult);
+  myIsEquation = true;
+}
+
+
+void ModuleBase_ParamSpinBox::setValueEnabled(bool theEnable)
+{
+  setReadOnly(!theEnable);
+
+  QPalette aPal = palette();
+  aPal.setColor(QPalette::All, QPalette::Base,
+    theEnable ? myEnabledBaseColor : aPal.color(QPalette::Disabled, QPalette::Base));
+  setPalette(aPal);
 }