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