Salome HOME
Merge branch 'master' into cgt/devCEA
[modules/shaper.git] / src / ModuleBase / ModuleBase_WidgetExprEditor.cpp
1 // Copyright (C) 2014-2017  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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <ModuleBase_WidgetExprEditor.h>
22 #include <ModuleBase_Tools.h>
23
24 #include <ModelAPI_Data.h>
25 #include <ModelAPI_Object.h>
26 #include <ModelAPI_Validator.h>
27 #include <ModelAPI_ResultParameter.h>
28 #include <ModelAPI_AttributeString.h>
29 #include <ModelAPI_AttributeDouble.h>
30
31 #include <Config_WidgetAPI.h>
32
33 #include <QVBoxLayout>
34 #include <QLabel>
35 #include <QLineEdit>
36 #include <QObject>
37 #include <QString>
38 #include <QStringListModel>
39 #include <QCompleter>
40 #include <QSize>
41 #include <QShortcut>
42 #include <QScrollBar>
43 #include <QFontMetrics>
44 #include <QPainter>
45 #include <QStyle>
46 #include <QAbstractItemView>
47
48 #include <memory>
49 #include <string>
50
51 ExpressionEditor::ExpressionEditor(QWidget* theParent)
52 : QPlainTextEdit(theParent), myCompletedAndSelected(false)
53 {
54   myCompleter = new QCompleter(this);
55   myCompleter->setWidget(this);
56   myCompleter->setCompletionMode(QCompleter::PopupCompletion);
57
58   myCompleterModel = new QStringListModel(this);
59   myCompleter->setModel(myCompleterModel);
60   // Use sorted model to accelerate completion (QCompleter will use binary search)
61   myCompleter->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
62   myCompleter->setCaseSensitivity(Qt::CaseInsensitive);
63
64   connect(myCompleter, SIGNAL(activated(const QString&)),
65           this,        SLOT(insertCompletion(const QString&)));
66   (void) new QShortcut(QKeySequence(tr("Ctrl+Space", "Complete")),
67                        this, SLOT(performCompletion()));
68
69   connect(this, SIGNAL(textChanged()), this, SLOT(onTextChanged()));
70
71   setTabChangesFocus(true);
72 }
73
74 ExpressionEditor::~ExpressionEditor()
75 {
76
77 }
78
79 void ExpressionEditor::setCompletionList(QStringList& theList)
80 {
81   theList.sort();
82   theList.removeDuplicates();
83   myCompleterModel->setStringList(theList);
84 }
85
86 void ExpressionEditor::insertCompletion(const QString& theCompletion, bool isSingleWord)
87 {
88   QTextCursor aCursor = textCursor();
89   int numberOfCharsToComplete = theCompletion.length() -
90       myCompleter->completionPrefix().length();
91   int insertionPosition = aCursor.position();
92   aCursor.insertText(theCompletion.right(numberOfCharsToComplete));
93   if (isSingleWord) {
94     aCursor.setPosition(insertionPosition);
95     aCursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
96     myCompletedAndSelected = true;
97   }
98   setTextCursor(aCursor);
99 }
100
101 void ExpressionEditor::performCompletion()
102 {
103   QTextCursor aCursor = textCursor();
104   aCursor.select(QTextCursor::WordUnderCursor);
105   const QString aPrefix = aCursor.selectedText();
106   if (!aPrefix.isEmpty() && aPrefix.at(aPrefix.length() - 1).isLetter()) {
107     performCompletion(aPrefix);
108   }
109 }
110
111 void ExpressionEditor::performCompletion(const QString& theCompletionPrefix)
112 {
113   //populate model?
114   if (theCompletionPrefix != myCompleter->completionPrefix()) {
115     myCompleter->setCompletionPrefix(theCompletionPrefix);
116     myCompleter->popup()->setCurrentIndex(myCompleter->completionModel()->index(0, 0));
117   }
118   if (myCompleter->completionCount() == 1) {
119     insertCompletion(myCompleter->currentCompletion(), true);
120   } else {
121     QRect aRect = cursorRect();
122     aRect.setWidth(myCompleter->popup()->sizeHintForColumn(0)
123                   + myCompleter->popup()->verticalScrollBar()->sizeHint().width());
124     myCompleter->complete(aRect);
125   }
126 }
127
128 void ExpressionEditor::keyPressEvent(QKeyEvent* theEvent)
129 {
130   if (myCompletedAndSelected && handledCompletedAndSelected(theEvent))
131     return;
132   myCompletedAndSelected = false;
133   if (myCompleter->popup()->isVisible()) {
134     switch (theEvent->key()) {
135       case Qt::Key_Up:
136       case Qt::Key_Down:
137       case Qt::Key_Escape:
138       case Qt::Key_Enter:
139       case Qt::Key_Return:
140         theEvent->ignore();
141       return;
142       default:
143         myCompleter->popup()->hide();
144         break;
145     }
146   }
147   else {
148     switch (theEvent->key()) {
149       case Qt::Key_Enter:
150       case Qt::Key_Return:
151         emit keyReleased(this, theEvent);
152         // do not react to the Enter key, the property panel processes it
153         return;
154       break;
155       default:
156         break;
157     }
158   }
159   QPlainTextEdit::keyPressEvent(theEvent);
160 }
161
162 bool ExpressionEditor::handledCompletedAndSelected(QKeyEvent* theEvent)
163 {
164   myCompletedAndSelected = false;
165   QTextCursor aCursor = textCursor();
166   switch (theEvent->key()) {
167     case Qt::Key_Enter:
168     case Qt::Key_Return: aCursor.clearSelection(); break;
169     case Qt::Key_Escape: aCursor.removeSelectedText(); break;
170     default: return false;
171   }
172   setTextCursor(aCursor);
173   theEvent->accept();
174   return true;
175 }
176
177 void ExpressionEditor::setPlaceHolderText( const QString& thePlaceHolderText )
178 {
179   myPlaceHolderText = thePlaceHolderText;
180 }
181
182 QString ExpressionEditor::placeHolderText() const
183 {
184   return myPlaceHolderText;
185 }
186
187 void ExpressionEditor::paintEvent( QPaintEvent* theEvent )
188 {
189   QPlainTextEdit::paintEvent( theEvent );
190
191   if( toPlainText().isEmpty() )
192   {
193     QPainter aPainter( viewport() );
194     QFontMetrics aFontMetrics = fontMetrics();
195
196     QPointF offset(contentOffset());
197     QRect r = rect();
198     int m = (int)document()->documentMargin();
199     QRect lineRect( r.x() + m + offset.x(), offset.y(),
200                     r.width() - 2*m, aFontMetrics.height() );
201
202     Qt::Alignment va = QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft );
203     int minLB = qMax( 0, -aFontMetrics.minLeftBearing() );
204
205     QColor aColor = palette().text().color();
206     aColor.setAlpha( 128 );
207     QPen anOldpen = aPainter.pen();
208     aPainter.setPen( aColor );
209     lineRect.adjust(minLB, 0, 0, 0);
210     QString elidedText =
211       aFontMetrics.elidedText( myPlaceHolderText, Qt::ElideRight, lineRect.width() );
212     aPainter.drawText( lineRect, va, elidedText );
213     aPainter.setPen( anOldpen );
214   }
215 }
216
217 void ExpressionEditor::onTextChanged()
218 {
219   emit valueModified();
220 }
221
222
223 ModuleBase_WidgetExprEditor::ModuleBase_WidgetExprEditor( QWidget* theParent,
224                                                           const Config_WidgetAPI* theData,
225                                                           const std::string& thePlaceHolder )
226 : ModuleBase_ModelWidget(theParent, theData)
227 {
228   QVBoxLayout* aMainLay = new QVBoxLayout(this);
229   ModuleBase_Tools::adjustMargins(aMainLay);
230
231   myResultLabel = new QLabel(this);
232   myResultLabel->setWordWrap(true);
233   QFontMetrics fm(myResultLabel->font());
234   myResultLabel->setMinimumHeight(fm.height() * 2); // set 2 line height as minimum
235   myResultLabel->setAlignment(Qt::AlignLeft|Qt::AlignBottom);
236   aMainLay->addWidget(myResultLabel);
237   myEditor = new ExpressionEditor(this);
238   myEditor->setMinimumHeight(20);
239   myEditor->setPlaceHolderText( QString::fromStdString( thePlaceHolder ) );
240   aMainLay->addWidget(myEditor);
241   this->setLayout(aMainLay);
242
243   connect(myEditor, SIGNAL(valueModified()), this, SIGNAL(valuesModified()));
244   connect(myEditor, SIGNAL(keyReleased(QObject*, QKeyEvent*)),
245           this, SIGNAL(keyReleased(QObject*, QKeyEvent*)));
246 }
247
248 ModuleBase_WidgetExprEditor::~ModuleBase_WidgetExprEditor()
249 {
250 }
251
252 void ModuleBase_WidgetExprEditor::activateCustom()
253 {
254   ModuleBase_ModelWidget::activateCustom();
255
256   QStringList aParameters;
257   ModuleBase_Tools::getParameters(aParameters);
258   myEditor->setCompletionList(aParameters);
259 }
260
261 void ModuleBase_WidgetExprEditor::initializeValueByActivate()
262 {
263 }
264
265 bool ModuleBase_WidgetExprEditor::storeValueCustom()
266 {
267   // A rare case when plugin was not loaded.
268   if(!myFeature)
269     return false;
270   DataPtr aData = myFeature->data();
271   AttributeStringPtr aStringAttr = aData->string(attributeID());
272
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 = getValueState() == ModifiedInPP;
328   if (isModified) {
329     emit valuesChanged();
330     myEditor->selectAll();
331   }
332   return isModified;
333 }
334
335 void ModuleBase_WidgetExprEditor::onTextChanged()
336 {
337   emit valuesChanged();
338 }