Salome HOME
a7e7878e65d52e34722b4cf43f88c2a758e09006
[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), myIsModified(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   bool anIsModified = myIsModified;
118
119   if (myCompletedAndSelected && handledCompletedAndSelected(theEvent))
120     return;
121   myCompletedAndSelected = false;
122   if (myCompleter->popup()->isVisible()) {
123     switch (theEvent->key()) {
124       case Qt::Key_Up:
125       case Qt::Key_Down:
126       case Qt::Key_Escape:
127       case Qt::Key_Enter:
128       case Qt::Key_Return:
129         theEvent->ignore();
130       return;
131       default:
132         myCompleter->popup()->hide();
133         break;
134     }
135   }
136   else {
137     switch (theEvent->key()) {
138       case Qt::Key_Enter:
139       case Qt::Key_Return:
140         emit keyReleased(theEvent);
141         // do not react to the Enter key, the property panel processes it
142         return;
143       break;
144       default:
145         break;
146     }
147   }
148   QPlainTextEdit::keyPressEvent(theEvent);
149 }
150
151 bool ExpressionEditor::handledCompletedAndSelected(QKeyEvent* theEvent)
152 {
153   myCompletedAndSelected = false;
154   QTextCursor aCursor = textCursor();
155   switch (theEvent->key()) {
156     case Qt::Key_Enter:
157     case Qt::Key_Return: aCursor.clearSelection(); break;
158     case Qt::Key_Escape: aCursor.removeSelectedText(); break;
159     default: return false;
160   }
161   setTextCursor(aCursor);
162   theEvent->accept();
163   return true;
164 }
165
166 void ExpressionEditor::setPlaceHolderText( const QString& thePlaceHolderText )
167 {
168   myPlaceHolderText = thePlaceHolderText;
169 }
170
171 QString ExpressionEditor::placeHolderText() const
172 {
173   return myPlaceHolderText;
174 }
175
176 bool ExpressionEditor::isModified() const
177 {
178   return myIsModified;
179 }
180
181 void ExpressionEditor::clearModified()
182 {
183   myIsModified = false;
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 = aFontMetrics.elidedText( myPlaceHolderText, Qt::ElideRight, lineRect.width() );
210     aPainter.drawText( lineRect, va, elidedText );
211     aPainter.setPen( anOldpen );
212   }
213 }
214
215 bool ExpressionEditor::focusNextPrevChild(bool theIsNext)
216 {
217   if (myIsModified)
218     emit editingFinished();
219   emit valueStored();
220   emit focusNextPrev();
221   return QPlainTextEdit::focusNextPrevChild(theIsNext);
222 }
223
224 void ExpressionEditor::onTextChanged()
225 {
226   myIsModified = true;
227   emit valueModified();
228 }
229
230
231 ModuleBase_WidgetExprEditor::ModuleBase_WidgetExprEditor( QWidget* theParent,
232                                                           const Config_WidgetAPI* theData,
233                                                           const std::string& theParentId,
234                                                           const std::string& thePlaceHolder )
235     : ModuleBase_ModelWidget(theParent, theData, theParentId)
236 {
237   QVBoxLayout* aMainLay = new QVBoxLayout(this);
238   ModuleBase_Tools::adjustMargins(aMainLay);
239
240   myResultLabel = new QLabel(this);
241   myResultLabel->setWordWrap(true);
242   QFontMetrics fm(myResultLabel->font());
243   myResultLabel->setMinimumHeight(fm.height() * 2); // set 2 line height as minimum
244   myResultLabel->setAlignment(Qt::AlignLeft|Qt::AlignBottom);
245   aMainLay->addWidget(myResultLabel);
246   myEditor = new ExpressionEditor(this);
247   myEditor->setMinimumHeight(20);
248   myEditor->setPlaceHolderText( QString::fromStdString( thePlaceHolder ) );
249   aMainLay->addWidget(myEditor);
250   this->setLayout(aMainLay);
251
252   connect(myEditor, SIGNAL(valueModified()), this, SIGNAL(valuesModified()));
253   //connect(myEditor, SIGNAL(editingFinished()), this, SLOT(onTextChanged()));
254   connect(myEditor, SIGNAL(valueStored()), this, SLOT(onTextChanged()));
255   connect(myEditor, SIGNAL(focusNextPrev()), this, SIGNAL(focusNextPrev()));
256
257   connect(myEditor, SIGNAL(keyReleased(QKeyEvent*)), this, SIGNAL(keyReleased(QKeyEvent*)));
258     /// The signal about key release on the control, that corresponds to the attribute
259   /// \param theEvent key release event
260 }
261
262 ModuleBase_WidgetExprEditor::~ModuleBase_WidgetExprEditor()
263 {
264 }
265
266 bool ModuleBase_WidgetExprEditor::storeValueCustom() const
267 {
268   // A rare case when plugin was not loaded. 
269   if(!myFeature)
270     return false;
271   DataPtr aData = myFeature->data();
272   AttributeStringPtr aStringAttr = aData->string(attributeID());
273   QString aWidgetValue = myEditor->toPlainText();
274   aStringAttr->setValue(aWidgetValue.toStdString());
275   updateObject(myFeature);
276
277   // Try to get the value
278   QString aStateMsg;
279   std::string anErrorMessage = myFeature->string("ExpressionError")->value();
280   if (anErrorMessage.empty()) {
281     ResultParameterPtr aParam =
282       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(myFeature->firstResult());
283     if(aParam.get()) {
284       AttributeDoublePtr aValueAttr =
285         aParam->data()->real(ModelAPI_ResultParameter::VALUE());
286       if (aValueAttr.get()) {
287         double aValue = aValueAttr->value();
288         aStateMsg = "Result: " + QString::number(aValue);
289       }
290     }
291   } else {
292     aStateMsg = "Error: " + QString::fromStdString(anErrorMessage);
293   }
294   myResultLabel->setText(aStateMsg);
295   return true;
296 }
297
298 bool ModuleBase_WidgetExprEditor::restoreValueCustom()
299 {
300   // A rare case when plugin was not loaded. 
301   if(!myFeature)
302     return false;
303   DataPtr aData = myFeature->data();
304   AttributeStringPtr aStringAttr = aData->string(attributeID());
305
306   bool isBlocked = myEditor->blockSignals(true);
307   QTextCursor aCursor = myEditor->textCursor();
308   int pos = aCursor.position();
309   std::string aRestoredStr = aStringAttr->value();
310   myEditor->setPlainText(QString::fromStdString(aRestoredStr));
311   aCursor.setPosition(pos);
312   myEditor->setTextCursor(aCursor);
313   myEditor->blockSignals(isBlocked);
314
315   return true;
316 }
317
318 QList<QWidget*> ModuleBase_WidgetExprEditor::getControls() const
319 {
320   QList<QWidget*> result;
321   result << myEditor;
322   return result;
323 }
324
325 bool ModuleBase_WidgetExprEditor::processEnter()
326 {
327   bool isModified = myEditor->isModified();
328   if (isModified) {
329     emit valuesChanged();
330     myEditor->clearModified();
331     myEditor->selectAll();
332   }
333   return isModified;
334 }
335
336 void ModuleBase_WidgetExprEditor::onTextChanged()
337 {
338   emit valuesChanged();
339 }