Salome HOME
Merge branch 'SALOME-8.2.0_porting'
[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 #include <QStyle>
35 #include <QAbstractItemView>
36
37 #include <memory>
38 #include <string>
39
40 ExpressionEditor::ExpressionEditor(QWidget* theParent)
41 : QPlainTextEdit(theParent), myCompletedAndSelected(false)
42 {
43   myCompleter = new QCompleter(this);
44   myCompleter->setWidget(this);
45   myCompleter->setCompletionMode(QCompleter::PopupCompletion);
46
47   myCompleterModel = new QStringListModel(this);
48   myCompleter->setModel(myCompleterModel);
49   // Use sorted model to accelerate completion (QCompleter will use binary search)
50   myCompleter->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
51   myCompleter->setCaseSensitivity(Qt::CaseInsensitive);
52
53   connect(myCompleter, SIGNAL(activated(const QString&)),
54           this,        SLOT(insertCompletion(const QString&)));
55   (void) new QShortcut(QKeySequence(tr("Ctrl+Space", "Complete")),
56                        this, SLOT(performCompletion()));
57
58   connect(this, SIGNAL(textChanged()), this, SLOT(onTextChanged()));
59
60   setTabChangesFocus(true);
61 }
62
63 ExpressionEditor::~ExpressionEditor()
64 {
65
66 }
67
68 void ExpressionEditor::setCompletionList(QStringList& theList)
69 {
70   theList.sort();
71   theList.removeDuplicates();
72   myCompleterModel->setStringList(theList);
73 }
74
75 void ExpressionEditor::insertCompletion(const QString& theCompletion, bool isSingleWord)
76 {
77   QTextCursor aCursor = textCursor();
78   int numberOfCharsToComplete = theCompletion.length() -
79       myCompleter->completionPrefix().length();
80   int insertionPosition = aCursor.position();
81   aCursor.insertText(theCompletion.right(numberOfCharsToComplete));
82   if (isSingleWord) {
83     aCursor.setPosition(insertionPosition);
84     aCursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
85     myCompletedAndSelected = true;
86   }
87   setTextCursor(aCursor);
88 }
89
90 void ExpressionEditor::performCompletion()
91 {
92   QTextCursor aCursor = textCursor();
93   aCursor.select(QTextCursor::WordUnderCursor);
94   const QString aPrefix = aCursor.selectedText();
95   if (!aPrefix.isEmpty() && aPrefix.at(aPrefix.length() - 1).isLetter()) {
96     performCompletion(aPrefix);
97   }
98 }
99
100 void ExpressionEditor::performCompletion(const QString& theCompletionPrefix)
101 {
102   //populate model?
103   if (theCompletionPrefix != myCompleter->completionPrefix()) {
104     myCompleter->setCompletionPrefix(theCompletionPrefix);
105     myCompleter->popup()->setCurrentIndex(myCompleter->completionModel()->index(0, 0));
106   }
107   if (myCompleter->completionCount() == 1) {
108     insertCompletion(myCompleter->currentCompletion(), true);
109   } else {
110     QRect aRect = cursorRect();
111     aRect.setWidth(myCompleter->popup()->sizeHintForColumn(0)
112                   + myCompleter->popup()->verticalScrollBar()->sizeHint().width());
113     myCompleter->complete(aRect);
114   }
115 }
116
117 void ExpressionEditor::keyPressEvent(QKeyEvent* theEvent)
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(this, 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 void ExpressionEditor::paintEvent( QPaintEvent* theEvent )
177 {
178   QPlainTextEdit::paintEvent( theEvent );
179
180   if( toPlainText().isEmpty() )
181   {
182     QPainter aPainter( viewport() );
183     QFontMetrics aFontMetrics = fontMetrics();
184
185     QPointF offset(contentOffset());
186     QRect r = rect();
187     int m = (int)document()->documentMargin();
188     QRect lineRect( r.x() + m + offset.x(), offset.y(),
189                     r.width() - 2*m, aFontMetrics.height() );
190
191     Qt::Alignment va = QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft );
192     int minLB = qMax( 0, -aFontMetrics.minLeftBearing() );
193
194     QColor aColor = palette().text().color();
195     aColor.setAlpha( 128 );
196     QPen anOldpen = aPainter.pen();
197     aPainter.setPen( aColor );
198     lineRect.adjust(minLB, 0, 0, 0);
199     QString elidedText =
200       aFontMetrics.elidedText( myPlaceHolderText, Qt::ElideRight, lineRect.width() );
201     aPainter.drawText( lineRect, va, elidedText );
202     aPainter.setPen( anOldpen );
203   }
204 }
205
206 void ExpressionEditor::onTextChanged()
207 {
208   emit valueModified();
209 }
210
211
212 ModuleBase_WidgetExprEditor::ModuleBase_WidgetExprEditor( QWidget* theParent,
213                                                           const Config_WidgetAPI* theData,
214                                                           const std::string& thePlaceHolder )
215 : ModuleBase_ModelWidget(theParent, theData)
216 {
217   QVBoxLayout* aMainLay = new QVBoxLayout(this);
218   ModuleBase_Tools::adjustMargins(aMainLay);
219
220   myResultLabel = new QLabel(this);
221   myResultLabel->setWordWrap(true);
222   QFontMetrics fm(myResultLabel->font());
223   myResultLabel->setMinimumHeight(fm.height() * 2); // set 2 line height as minimum
224   myResultLabel->setAlignment(Qt::AlignLeft|Qt::AlignBottom);
225   aMainLay->addWidget(myResultLabel);
226   myEditor = new ExpressionEditor(this);
227   myEditor->setMinimumHeight(20);
228   myEditor->setPlaceHolderText( QString::fromStdString( thePlaceHolder ) );
229   aMainLay->addWidget(myEditor);
230   this->setLayout(aMainLay);
231
232   connect(myEditor, SIGNAL(valueModified()), this, SIGNAL(valuesModified()));
233   connect(myEditor, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
234           this, SIGNAL(keyReleased(QObject*, QKeyEvent*)));
235 }
236
237 ModuleBase_WidgetExprEditor::~ModuleBase_WidgetExprEditor()
238 {
239 }
240
241 void ModuleBase_WidgetExprEditor::activateCustom()
242 {
243   ModuleBase_ModelWidget::activateCustom();
244
245   QStringList aParameters;
246   ModuleBase_Tools::getParameters(aParameters);
247   myEditor->setCompletionList(aParameters);
248 }
249
250 void ModuleBase_WidgetExprEditor::initializeValueByActivate()
251 {
252 }
253
254 bool ModuleBase_WidgetExprEditor::storeValueCustom()
255 {
256   // A rare case when plugin was not loaded.
257   if(!myFeature)
258     return false;
259   DataPtr aData = myFeature->data();
260   AttributeStringPtr aStringAttr = aData->string(attributeID());
261
262   QString aWidgetValue = myEditor->toPlainText();
263   aStringAttr->setValue(aWidgetValue.toStdString());
264   updateObject(myFeature);
265
266   // Try to get the value
267   QString aStateMsg;
268   std::string anErrorMessage = myFeature->string("ExpressionError")->value();
269   if (anErrorMessage.empty()) {
270     ResultParameterPtr aParam =
271       std::dynamic_pointer_cast<ModelAPI_ResultParameter>(myFeature->firstResult());
272     if(aParam.get()) {
273       AttributeDoublePtr aValueAttr =
274         aParam->data()->real(ModelAPI_ResultParameter::VALUE());
275       if (aValueAttr.get()) {
276         double aValue = aValueAttr->value();
277         aStateMsg = "Result: " + QString::number(aValue);
278       }
279     }
280   } else {
281     aStateMsg = "Error: " + QString::fromStdString(anErrorMessage);
282   }
283   myResultLabel->setText(aStateMsg);
284   return true;
285 }
286
287 bool ModuleBase_WidgetExprEditor::restoreValueCustom()
288 {
289   // A rare case when plugin was not loaded.
290   if(!myFeature)
291     return false;
292   DataPtr aData = myFeature->data();
293   AttributeStringPtr aStringAttr = aData->string(attributeID());
294
295   bool isBlocked = myEditor->blockSignals(true);
296   QTextCursor aCursor = myEditor->textCursor();
297   int pos = aCursor.position();
298   std::string aRestoredStr = aStringAttr->value();
299   myEditor->setPlainText(QString::fromStdString(aRestoredStr));
300   aCursor.setPosition(pos);
301   myEditor->setTextCursor(aCursor);
302   myEditor->blockSignals(isBlocked);
303
304   return true;
305 }
306
307 QList<QWidget*> ModuleBase_WidgetExprEditor::getControls() const
308 {
309   QList<QWidget*> result;
310   result << myEditor;
311   return result;
312 }
313
314 bool ModuleBase_WidgetExprEditor::processEnter()
315 {
316   bool isModified = getValueState() == ModifiedInPP;
317   if (isModified) {
318     emit valuesChanged();
319     myEditor->selectAll();
320   }
321   return isModified;
322 }
323
324 void ModuleBase_WidgetExprEditor::onTextChanged()
325 {
326   emit valuesChanged();
327 }