Salome HOME
Issue #801: place holder for hint in input fields
[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)
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
57 ExpressionEditor::~ExpressionEditor()
58 {
59
60 }
61
62 void ExpressionEditor::setCompletionList(QStringList& theList)
63 {
64   theList.sort();
65   theList.removeDuplicates();
66   myCompleterModel->setStringList(theList);
67 }
68
69 void ExpressionEditor::insertCompletion(const QString& theCompletion, bool isSingleWord)
70 {
71   QTextCursor aCursor = textCursor();
72   int numberOfCharsToComplete = theCompletion.length() -
73       myCompleter->completionPrefix().length();
74   int insertionPosition = aCursor.position();
75   aCursor.insertText(theCompletion.right(numberOfCharsToComplete));
76   if (isSingleWord) {
77     aCursor.setPosition(insertionPosition);
78     aCursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
79     myCompletedAndSelected = true;
80   }
81   setTextCursor(aCursor);
82 }
83
84 void ExpressionEditor::performCompletion()
85 {
86   QTextCursor aCursor = textCursor();
87   aCursor.select(QTextCursor::WordUnderCursor);
88   const QString aPrefix = aCursor.selectedText();
89   if (!aPrefix.isEmpty() && aPrefix.at(aPrefix.length() - 1).isLetter()) {
90     performCompletion(aPrefix);
91   }
92 }
93
94 void ExpressionEditor::performCompletion(const QString& theCompletionPrefix)
95 {
96   //populate model?
97   if (theCompletionPrefix != myCompleter->completionPrefix()) {
98     myCompleter->setCompletionPrefix(theCompletionPrefix);
99     myCompleter->popup()->setCurrentIndex(myCompleter->completionModel()->index(0, 0));
100   }
101   if (myCompleter->completionCount() == 1) {
102     insertCompletion(myCompleter->currentCompletion(), true);
103   } else {
104     QRect aRect = cursorRect();
105     aRect.setWidth(myCompleter->popup()->sizeHintForColumn(0)
106                   + myCompleter->popup()->verticalScrollBar()->sizeHint().width());
107     myCompleter->complete(aRect);
108   }
109 }
110
111 void ExpressionEditor::keyPressEvent(QKeyEvent* theEvent)
112 {
113   if (myCompletedAndSelected && handledCompletedAndSelected(theEvent))
114     return;
115   myCompletedAndSelected = false;
116   if (myCompleter->popup()->isVisible()) {
117     switch (theEvent->key()) {
118       case Qt::Key_Up:
119       case Qt::Key_Down:
120       case Qt::Key_Enter:
121       case Qt::Key_Return:
122       case Qt::Key_Escape:
123         theEvent->ignore();
124         return;
125       default:
126         myCompleter->popup()->hide();
127         break;
128     }
129   }
130   QPlainTextEdit::keyPressEvent(theEvent);
131 }
132
133 bool ExpressionEditor::handledCompletedAndSelected(QKeyEvent* theEvent)
134 {
135   myCompletedAndSelected = false;
136   QTextCursor aCursor = textCursor();
137   switch (theEvent->key()) {
138     case Qt::Key_Enter:
139     case Qt::Key_Return: aCursor.clearSelection(); break;
140     case Qt::Key_Escape: aCursor.removeSelectedText(); break;
141     default: return false;
142   }
143   setTextCursor(aCursor);
144   theEvent->accept();
145   return true;
146 }
147
148 void ExpressionEditor::setPlaceHolderText( const QString& thePlaceHolderText )
149 {
150   myPlaceHolderText = thePlaceHolderText;
151 }
152
153 QString ExpressionEditor::placeHolderText() const
154 {
155   return myPlaceHolderText;
156 }
157
158 void ExpressionEditor::paintEvent( QPaintEvent* theEvent )
159 {
160   QPlainTextEdit::paintEvent( theEvent );
161
162   if( toPlainText().isEmpty() )
163   {
164     QPainter aPainter( viewport() );
165     QFontMetrics aFontMetrics = fontMetrics();
166
167     QPointF offset(contentOffset());
168     QRect r = rect();
169     int m = (int)document()->documentMargin();
170     QRect lineRect( r.x() + m + offset.x(), offset.y(),
171                     r.width() - 2*m, aFontMetrics.height() );
172
173     Qt::Alignment va = QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft );
174     int minLB = qMax( 0, -aFontMetrics.minLeftBearing() );
175
176     QColor aColor = palette().text().color();
177     aColor.setAlpha( 128 );
178     QPen anOldpen = aPainter.pen();
179     aPainter.setPen( aColor );
180     lineRect.adjust(minLB, 0, 0, 0);
181     QString elidedText = aFontMetrics.elidedText( myPlaceHolderText, Qt::ElideRight, lineRect.width() );
182     aPainter.drawText( lineRect, va, elidedText );
183     aPainter.setPen( anOldpen );
184   }
185 }
186
187
188
189 ModuleBase_WidgetExprEditor::ModuleBase_WidgetExprEditor( QWidget* theParent,
190                                                           const Config_WidgetAPI* theData,
191                                                           const std::string& theParentId,
192                                                           const std::string& thePlaceHolder )
193     : ModuleBase_ModelWidget(theParent, theData, theParentId)
194 {
195   QVBoxLayout* aMainLay = new QVBoxLayout(this);
196   ModuleBase_Tools::adjustMargins(aMainLay);
197
198   myResultLabel = new QLabel(this);
199   myResultLabel->setWordWrap(true);
200   QFontMetrics fm(myResultLabel->font());
201   myResultLabel->setMinimumHeight(fm.height() * 2); // set 2 line height as minimum
202   myResultLabel->setAlignment(Qt::AlignLeft|Qt::AlignBottom);
203   aMainLay->addWidget(myResultLabel);
204   myEditor = new ExpressionEditor(this);
205   myEditor->setMinimumHeight(20);
206   myEditor->setPlaceHolderText( QString::fromStdString( thePlaceHolder ) );
207   aMainLay->addWidget(myEditor);
208   this->setLayout(aMainLay);
209
210   connect(myEditor, SIGNAL(textChanged()), this, SLOT(onTextChanged()));
211 }
212
213 ModuleBase_WidgetExprEditor::~ModuleBase_WidgetExprEditor()
214 {
215 }
216
217 bool ModuleBase_WidgetExprEditor::storeValueCustom() const
218 {
219   // A rare case when plugin was not loaded. 
220   if(!myFeature)
221     return false;
222   DataPtr aData = myFeature->data();
223   AttributeStringPtr aStringAttr = aData->string(attributeID());
224   QString aWidgetValue = myEditor->toPlainText();
225   aStringAttr->setValue(aWidgetValue.toStdString());
226   updateObject(myFeature);
227
228   // Try to get the value
229   QString aStateMsg;
230   std::string anErrorMessage = myFeature->error();
231   if (anErrorMessage.empty()) {
232     ResultParameterPtr aParam =
233       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(myFeature->firstResult());
234     if(aParam.get()) {
235       AttributeDoublePtr aValueAttr =
236         aParam->data()->real(ModelAPI_ResultParameter::VALUE());
237       if (aValueAttr.get()) {
238         double aValue = aValueAttr->value();
239         aStateMsg = "Result: " + QString::number(aValue);
240       }
241     }
242   } else {
243     aStateMsg = QString::fromStdString(anErrorMessage);
244   }
245   myResultLabel->setText(aStateMsg);
246   return true;
247 }
248
249 bool ModuleBase_WidgetExprEditor::restoreValueCustom()
250 {
251   // A rare case when plugin was not loaded. 
252   if(!myFeature)
253     return false;
254   DataPtr aData = myFeature->data();
255   AttributeStringPtr aStringAttr = aData->string(attributeID());
256
257   bool isBlocked = myEditor->blockSignals(true);
258   QTextCursor aCursor = myEditor->textCursor();
259   int pos = aCursor.position();
260   std::string aRestoredStr = aStringAttr->value();
261   myEditor->setPlainText(QString::fromStdString(aRestoredStr));
262   aCursor.setPosition(pos);
263   myEditor->setTextCursor(aCursor);
264   myEditor->blockSignals(isBlocked);
265
266   return true;
267 }
268
269 QList<QWidget*> ModuleBase_WidgetExprEditor::getControls() const
270 {
271   QList<QWidget*> result;
272   result << myEditor;
273   return result;
274 }
275
276 void ModuleBase_WidgetExprEditor::onTextChanged()
277 {
278   storeValue();
279 }