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