Salome HOME
1. Correction for perfomance problem by Apply button state update: do not listen...
[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& thePlaceHolder )
212 : ModuleBase_ModelWidget(theParent, theData)
213 {
214   QVBoxLayout* aMainLay = new QVBoxLayout(this);
215   ModuleBase_Tools::adjustMargins(aMainLay);
216
217   myResultLabel = new QLabel(this);
218   myResultLabel->setWordWrap(true);
219   QFontMetrics fm(myResultLabel->font());
220   myResultLabel->setMinimumHeight(fm.height() * 2); // set 2 line height as minimum
221   myResultLabel->setAlignment(Qt::AlignLeft|Qt::AlignBottom);
222   aMainLay->addWidget(myResultLabel);
223   myEditor = new ExpressionEditor(this);
224   myEditor->setMinimumHeight(20);
225   myEditor->setPlaceHolderText( QString::fromStdString( thePlaceHolder ) );
226   aMainLay->addWidget(myEditor);
227   this->setLayout(aMainLay);
228
229   connect(myEditor, SIGNAL(valueModified()), this, SIGNAL(valuesModified()));
230   connect(myEditor, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
231           this, SIGNAL(keyReleased(QObject*, QKeyEvent*)));
232 }
233
234 ModuleBase_WidgetExprEditor::~ModuleBase_WidgetExprEditor()
235 {
236 }
237
238 void ModuleBase_WidgetExprEditor::activateCustom()
239 {
240   ModuleBase_ModelWidget::activateCustom();
241
242   QStringList aParameters;
243   ModuleBase_Tools::getParameters(aParameters);
244   myEditor->setCompletionList(aParameters);
245 }
246
247 void ModuleBase_WidgetExprEditor::initializeValueByActivate()
248 {
249 }
250
251 bool ModuleBase_WidgetExprEditor::storeValueCustom()
252 {
253   // A rare case when plugin was not loaded. 
254   if(!myFeature)
255     return false;
256   DataPtr aData = myFeature->data();
257   AttributeStringPtr aStringAttr = aData->string(attributeID());
258
259   QString aWidgetValue = myEditor->toPlainText();
260   aStringAttr->setValue(aWidgetValue.toStdString());
261   updateObject(myFeature);
262
263   // Try to get the value
264   QString aStateMsg;
265   std::string anErrorMessage = myFeature->string("ExpressionError")->value();
266   if (anErrorMessage.empty()) {
267     ResultParameterPtr aParam =
268       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(myFeature->firstResult());
269     if(aParam.get()) {
270       AttributeDoublePtr aValueAttr =
271         aParam->data()->real(ModelAPI_ResultParameter::VALUE());
272       if (aValueAttr.get()) {
273         double aValue = aValueAttr->value();
274         aStateMsg = "Result: " + QString::number(aValue);
275       }
276     }
277   } else {
278     aStateMsg = "Error: " + QString::fromStdString(anErrorMessage);
279   }
280   myResultLabel->setText(aStateMsg);
281   return true;
282 }
283
284 bool ModuleBase_WidgetExprEditor::restoreValueCustom()
285 {
286   // A rare case when plugin was not loaded. 
287   if(!myFeature)
288     return false;
289   DataPtr aData = myFeature->data();
290   AttributeStringPtr aStringAttr = aData->string(attributeID());
291
292   bool isBlocked = myEditor->blockSignals(true);
293   QTextCursor aCursor = myEditor->textCursor();
294   int pos = aCursor.position();
295   std::string aRestoredStr = aStringAttr->value();
296   myEditor->setPlainText(QString::fromStdString(aRestoredStr));
297   aCursor.setPosition(pos);
298   myEditor->setTextCursor(aCursor);
299   myEditor->blockSignals(isBlocked);
300
301   return true;
302 }
303
304 QList<QWidget*> ModuleBase_WidgetExprEditor::getControls() const
305 {
306   QList<QWidget*> result;
307   result << myEditor;
308   return result;
309 }
310
311 bool ModuleBase_WidgetExprEditor::processEnter()
312 {
313   bool isModified = getValueState() == ModifiedInPP;
314   if (isModified) {
315     emit valuesChanged();
316     myEditor->selectAll();
317   }
318   return isModified;
319 }
320
321 void ModuleBase_WidgetExprEditor::onTextChanged()
322 {
323   emit valuesChanged();
324 }