Salome HOME
099669e63d8db9f830f8b5931ec9be777025c2b6
[modules/shaper.git] / src / ModuleBase / ModuleBase_WidgetExprEditor.cpp
1 // Copyright (C) 2014-2023  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <ModuleBase_WidgetExprEditor.h>
21 #include <ModuleBase_Tools.h>
22
23 #include <Locale_Convert.h>
24
25 #include <ModelAPI_Data.h>
26 #include <ModelAPI_Object.h>
27 #include <ModelAPI_Validator.h>
28 #include <ModelAPI_ResultParameter.h>
29 #include <ModelAPI_AttributeString.h>
30 #include <ModelAPI_AttributeDouble.h>
31
32 #include <Config_WidgetAPI.h>
33
34 #include <QVBoxLayout>
35 #include <QLabel>
36 #include <QLineEdit>
37 #include <QObject>
38 #include <QString>
39 #include <QStringListModel>
40 #include <QCompleter>
41 #include <QSize>
42 #include <QShortcut>
43 #include <QScrollBar>
44 #include <QFontMetrics>
45 #include <QPainter>
46 #include <QStyle>
47 #include <QAbstractItemView>
48
49 #include <memory>
50 #include <string>
51
52 ExpressionEditor::ExpressionEditor(QWidget* theParent)
53 : QPlainTextEdit(theParent), myCompletedAndSelected(false)
54 {
55   myCompleter = new QCompleter(this);
56   myCompleter->setWidget(this);
57   myCompleter->setCompletionMode(QCompleter::PopupCompletion);
58
59   myCompleterModel = new QStringListModel(this);
60   myCompleter->setModel(myCompleterModel);
61   // Use sorted model to accelerate completion (QCompleter will use binary search)
62   myCompleter->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
63   myCompleter->setCaseSensitivity(Qt::CaseInsensitive);
64
65   connect(myCompleter, SIGNAL(activated(const QString&)),
66           this,        SLOT(insertCompletion(const QString&)));
67   (void) new QShortcut(QKeySequence(tr("Ctrl+Space", "Complete")),
68                        this, SLOT(performCompletion()));
69
70   connect(this, SIGNAL(textChanged()), this, SLOT(onTextChanged()));
71
72   setTabChangesFocus(true);
73 }
74
75 ExpressionEditor::~ExpressionEditor()
76 {
77
78 }
79
80 void ExpressionEditor::setCompletionList(QStringList& theList)
81 {
82   theList.sort();
83   theList.removeDuplicates();
84   myCompleterModel->setStringList(theList);
85 }
86
87 void ExpressionEditor::insertCompletion(const QString& theCompletion, bool isSingleWord)
88 {
89   QTextCursor aCursor = textCursor();
90   int numberOfCharsToComplete = theCompletion.length() -
91       myCompleter->completionPrefix().length();
92   int insertionPosition = aCursor.position();
93   aCursor.insertText(theCompletion.right(numberOfCharsToComplete));
94   if (isSingleWord) {
95     aCursor.setPosition(insertionPosition);
96     aCursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
97     myCompletedAndSelected = true;
98   }
99   setTextCursor(aCursor);
100 }
101
102 void ExpressionEditor::performCompletion()
103 {
104   QTextCursor aCursor = textCursor();
105   aCursor.select(QTextCursor::WordUnderCursor);
106   const QString aPrefix = aCursor.selectedText();
107   performCompletion(aPrefix);
108 }
109
110 void ExpressionEditor::performCompletion(const QString& theCompletionPrefix)
111 {
112   //populate model?
113   if (theCompletionPrefix != myCompleter->completionPrefix()) {
114     myCompleter->setCompletionPrefix(theCompletionPrefix);
115     myCompleter->popup()->setCurrentIndex(myCompleter->completionModel()->index(0, 0));
116   }
117   if (myCompleter->completionCount() == 1) {
118     insertCompletion(myCompleter->currentCompletion(), true);
119   } else {
120     QRect aRect = cursorRect();
121     aRect.setWidth(myCompleter->popup()->sizeHintForColumn(0)
122                   + myCompleter->popup()->verticalScrollBar()->sizeHint().width());
123     myCompleter->complete(aRect);
124   }
125 }
126
127 void ExpressionEditor::keyPressEvent(QKeyEvent* theEvent)
128 {
129   if (myCompletedAndSelected && handledCompletedAndSelected(theEvent))
130     return;
131   myCompletedAndSelected = false;
132   if (myCompleter->popup()->isVisible()) {
133     switch (theEvent->key()) {
134       case Qt::Key_Up:
135       case Qt::Key_Down:
136       case Qt::Key_Escape:
137       case Qt::Key_Enter:
138       case Qt::Key_Return:
139         theEvent->ignore();
140       return;
141       default:
142         myCompleter->popup()->hide();
143         break;
144     }
145   }
146   else {
147     switch (theEvent->key()) {
148       case Qt::Key_Enter:
149       case Qt::Key_Return:
150         emit keyReleased(this, theEvent);
151         // do not react to the Enter key, the property panel processes it
152         return;
153       break;
154       default:
155         break;
156     }
157   }
158   QPlainTextEdit::keyPressEvent(theEvent);
159 }
160
161 bool ExpressionEditor::handledCompletedAndSelected(QKeyEvent* theEvent)
162 {
163   myCompletedAndSelected = false;
164   QTextCursor aCursor = textCursor();
165   switch (theEvent->key()) {
166     case Qt::Key_Enter:
167     case Qt::Key_Return: aCursor.clearSelection(); break;
168     case Qt::Key_Escape: aCursor.removeSelectedText(); break;
169     default: return false;
170   }
171   setTextCursor(aCursor);
172   theEvent->accept();
173   return true;
174 }
175
176 void ExpressionEditor::setPlaceHolderText( const QString& thePlaceHolderText )
177 {
178   myPlaceHolderText = thePlaceHolderText;
179 }
180
181 QString ExpressionEditor::placeHolderText() const
182 {
183   return myPlaceHolderText;
184 }
185
186 void ExpressionEditor::paintEvent( QPaintEvent* theEvent )
187 {
188   QPlainTextEdit::paintEvent( theEvent );
189
190   if( toPlainText().isEmpty() )
191   {
192     QPainter aPainter( viewport() );
193     QFontMetrics aFontMetrics = fontMetrics();
194
195     QPointF offset(contentOffset());
196     QRect r = rect();
197     int m = (int)document()->documentMargin();
198     QRect lineRect( r.x() + m + offset.x(), offset.y(),
199                     r.width() - 2*m, aFontMetrics.height() );
200
201     Qt::Alignment va = QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft );
202     int minLB = qMax( 0, -aFontMetrics.minLeftBearing() );
203
204     QColor aColor = palette().text().color();
205     aColor.setAlpha( 128 );
206     QPen anOldpen = aPainter.pen();
207     aPainter.setPen( aColor );
208     lineRect.adjust(minLB, 0, 0, 0);
209     QString elidedText =
210       aFontMetrics.elidedText( myPlaceHolderText, Qt::ElideRight, lineRect.width() );
211     aPainter.drawText( lineRect, va, elidedText );
212     aPainter.setPen( anOldpen );
213   }
214 }
215
216 void ExpressionEditor::onTextChanged()
217 {
218   emit valueModified();
219 }
220
221
222 ModuleBase_WidgetExprEditor::ModuleBase_WidgetExprEditor( QWidget* theParent,
223                                                           const Config_WidgetAPI* theData,
224                                                           const std::string& thePlaceHolder )
225 : ModuleBase_ModelWidget(theParent, theData)
226 {
227   QVBoxLayout* aMainLay = new QVBoxLayout(this);
228   ModuleBase_Tools::adjustMargins(aMainLay);
229
230   myResultLabel = new QLabel(this);
231   myResultLabel->setWordWrap(true);
232   QFontMetrics fm(myResultLabel->font());
233   myResultLabel->setMinimumHeight(fm.height() * 2); // set 2 line height as minimum
234   myResultLabel->setAlignment(Qt::AlignLeft|Qt::AlignBottom);
235   aMainLay->addWidget(myResultLabel);
236   myEditor = new ExpressionEditor(this);
237   myEditor->setMinimumHeight(20);
238   myEditor->setPlaceHolderText( translate( thePlaceHolder ) );
239   aMainLay->addWidget(myEditor);
240   this->setLayout(aMainLay);
241
242   connect(myEditor, SIGNAL(valueModified()), this, SIGNAL(valuesModified()));
243   connect(myEditor, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
244           this, SIGNAL(keyReleased(QObject*, QKeyEvent*)));
245 }
246
247 ModuleBase_WidgetExprEditor::~ModuleBase_WidgetExprEditor()
248 {
249 }
250
251 void ModuleBase_WidgetExprEditor::activateCustom()
252 {
253   ModuleBase_ModelWidget::activateCustom();
254
255   QStringList aParameters;
256   ModuleBase_Tools::getParameters(aParameters);
257   myEditor->setCompletionList(aParameters);
258 }
259
260 void ModuleBase_WidgetExprEditor::initializeValueByActivate()
261 {
262 }
263
264 bool ModuleBase_WidgetExprEditor::storeValueCustom()
265 {
266   // A rare case when plugin was not loaded.
267   if(!myFeature)
268     return false;
269   DataPtr aData = myFeature->data();
270   AttributeStringPtr aStringAttr = aData->string(attributeID());
271
272   QString aWidgetValue = myEditor->toPlainText();
273   aStringAttr->setValue(aWidgetValue.toStdWString());
274   updateObject(myFeature);
275
276   // Try to get the value
277   QString aStateMsg;
278   std::string anErrorMessage = myFeature->string("ExpressionError")->value();
279   if (anErrorMessage.empty()) {
280     ResultParameterPtr aParam =
281       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(myFeature->firstResult());
282     if(aParam.get()) {
283       AttributeDoublePtr aValueAttr =
284         aParam->data()->real(ModelAPI_ResultParameter::VALUE());
285       if (aValueAttr.get()) {
286         double aValue = aValueAttr->value();
287         aStateMsg = "Result: " + QString::number(aValue);
288       }
289     }
290   } else {
291     aStateMsg = "Error: " + QString::fromStdString(anErrorMessage);
292   }
293   myResultLabel->setText(aStateMsg);
294   return true;
295 }
296
297 bool ModuleBase_WidgetExprEditor::restoreValueCustom()
298 {
299   // A rare case when plugin was not loaded.
300   if(!myFeature)
301     return false;
302   DataPtr aData = myFeature->data();
303   AttributeStringPtr aStringAttr = aData->string(attributeID());
304
305   bool isBlocked = myEditor->blockSignals(true);
306   QTextCursor aCursor = myEditor->textCursor();
307   int pos = aCursor.position();
308   QString aRestoredStr;
309   if (aStringAttr->isUValue())
310     aRestoredStr = QString::fromStdWString(Locale::Convert::toWString(aStringAttr->valueU()));
311   else
312     aRestoredStr = QString::fromStdString(aStringAttr->value());
313   myEditor->setPlainText(aRestoredStr);
314   aCursor.setPosition(pos);
315   myEditor->setTextCursor(aCursor);
316   myEditor->blockSignals(isBlocked);
317
318   return true;
319 }
320
321 QList<QWidget*> ModuleBase_WidgetExprEditor::getControls() const
322 {
323   QList<QWidget*> result;
324   result << myEditor;
325   return result;
326 }
327
328 bool ModuleBase_WidgetExprEditor::processEnter()
329 {
330   bool isModified = getValueState() == ModifiedInPP;
331   if (isModified) {
332     emit valuesChanged();
333     myEditor->selectAll();
334   }
335   return isModified;
336 }
337
338 void ModuleBase_WidgetExprEditor::onTextChanged()
339 {
340   emit valuesChanged();
341 }