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