Debian Codegraph @

src/Gui/InputField.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2013 Jürgen Riegel <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <limits>
24 #include <QContextMenuEvent>
25 #include <QMenu>
26 #include <QPixmapCache>
27 #include <QRegularExpression>
28 #include <QRegularExpressionMatch>
29
30 #include <App/Application.h>
31 #include <App/DocumentObject.h>
32 #include <App/ExpressionParser.h>
33 #include <App/PropertyUnits.h>
34 #include <Base/Exception.h>
35 #include <Base/Quantity.h>
36
37 #include "InputField.h"
38 #include "BitmapFactory.h"
39 #include "Command.h"
40 #include "QuantitySpinBox_p.h"
41
42
43 using namespace Gui;
44 using namespace App;
45 using namespace Base;
46
47 // --------------------------------------------------------------------
48
49 namespace Gui
50 {
51 class InputValidator: public QValidator
52 {
53 public:
54 explicit InputValidator(InputField* parent);
55 ~InputValidator() override;
56
57 void fixup(QString& input) const override;
58 State validate(QString& input, int& pos) const override;
59
60 private:
61 InputField* dptr;
62 };
63 } // namespace Gui
64
65 // --------------------------------------------------------------------
66
67 InputField::InputField(QWidget* parent)
68 : ExpressionLineEdit(parent)
69 , ExpressionWidget()
70 , validInput(true)
71 , actUnitValue(0)
72 , Maximum(std::numeric_limits<double>::max())
73 , Minimum(-std::numeric_limits<double>::max())
74 , StepSize(1.0)
75 , HistorySize(5)
76 , SaveSize(5)
77 {
78 setValidator(new InputValidator(this));
79 if (!App::GetApplication()
80 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
81 ->GetBool("ComboBoxWheelEventFilter", false)) {
82 setFocusPolicy(Qt::WheelFocus);
83 }
84 else {
85 setFocusPolicy(Qt::StrongFocus);
86 }
87 iconLabel = new ExpressionLabel(this);
88 iconLabel->setCursor(Qt::ArrowCursor);
89 QFontMetrics fm(font());
90 int iconSize = fm.height();
91 QPixmap pixmap = getValidationIcon(":/icons/button_invalid.svg", QSize(iconSize, iconSize));
92 iconLabel->setPixmap(pixmap);
93 iconLabel->hide();
94 connect(this, &QLineEdit::textChanged, this, &InputField::updateIconLabel);
95
96 // Set Margins
97 // vertical margin, such that `,` won't be clipped to a `.` and similar font descents. Relevant
98 // on some OSX versions horizontal margin, such that text will not be behind `fx` icon
99 int margin = getMargin();
100 setTextMargins(margin, margin, margin + iconSize, margin);
101
102 this->setContextMenuPolicy(Qt::DefaultContextMenu);
103
104 connect(this, &QLineEdit::textChanged, this, &InputField::newInput);
105 }
106
107 int InputField::getMargin()
108 {
109 #if QT_VERSION >= QT_VERSION_CHECK(6, 3, 0)
110 return style()->pixelMetric(QStyle::PM_LineEditIconMargin, nullptr, this) / 2;
111 #else
112 return style()->pixelMetric(QStyle::PM_FocusFrameHMargin, nullptr, this);
113 #endif
114 }
115
116 InputField::~InputField() = default;
117
118 void InputField::bind(const App::ObjectIdentifier& _path)
119 {
120 ExpressionBinding::bind(_path);
121
122 auto* prop = freecad_cast<PropertyQuantity*>(getPath().getProperty());
123
124 if (prop) {
125 actQuantity = Base::Quantity(prop->getValue());
126 }
127
128 DocumentObject* docObj = getPath().getDocumentObject();
129
130 if (docObj) {
131 std::shared_ptr<const Expression> expr(docObj->getExpression(getPath()).expression);
132
133 if (expr) {
134 newInput(QString::fromStdString(expr->toString()));
135 }
136 }
137
138 // Create document object, to initialize completer
139 setDocumentObject(docObj);
140 }
141
142 bool InputField::apply(const std::string& propName)
143 {
144 if (!ExpressionBinding::apply(propName)) {
145 Gui::Command::doCommand(Gui::Command::Doc, "%s = %f", propName.c_str(), getQuantity().getValue());
146 return true;
147 }
148 else {
149 return false;
150 }
151 }
152
153 bool InputField::apply()
154 {
155 return ExpressionBinding::apply();
156 }
157
158 QPixmap InputField::getValidationIcon(const char* name, const QSize& size) const
159 {
160 QString key
161 = QStringLiteral("%1_%2x%3").arg(QString::fromLatin1(name)).arg(size.width()).arg(size.height());
162 QPixmap icon;
163 if (QPixmapCache::find(key, &icon)) {
164 return icon;
165 }
166
167 icon = BitmapFactory().pixmapFromSvg(name, size);
168 if (!icon.isNull()) {
169 QPixmapCache::insert(key, icon);
170 }
171 return icon;
172 }
173
174 void InputField::updateText(const Base::Quantity& quant)
175 {
176 if (isBound()) {
177 std::shared_ptr<const Expression> e(
178 getPath().getDocumentObject()->getExpression(getPath()).expression
179 );
180
181 if (e) {
182 setText(QString::fromStdString(e->toString()));
183 return;
184 }
185 }
186
187 double dFactor;
188 std::string unitStr;
189 std::string txt = quant.getUserString(dFactor, unitStr);
190 actUnitValue = quant.getValue() / dFactor;
191 setText(QString::fromStdString(txt));
192 }
193
194 void InputField::resizeEvent(QResizeEvent* /*event*/)
195 {
196 QSize iconSize = iconLabel->sizeHint();
197 iconLabel->move(width() - (iconSize.width() + 2 * getMargin()), (height() - iconSize.height()) / 2);
198 }
199
200 void InputField::updateIconLabel(const QString& text)
201 {
202 iconLabel->setVisible(text.isEmpty());
203 }
204
205 void InputField::contextMenuEvent(QContextMenuEvent* event)
206 {
207 QMenu* editMenu = createStandardContextMenu();
208 editMenu->setTitle(tr("Edit"));
209 auto menu = new QMenu(QStringLiteral("InputFieldContextmenu"));
210
211 menu->addMenu(editMenu);
212 menu->addSeparator();
213
214 // datastructure to remember actions for values
215 std::vector<QString> values;
216 std::vector<QAction*> actions;
217
218 // add the history menu part...
219 std::vector<QString> history = getHistory();
220
221 for (const auto& it : history) {
222 actions.push_back(menu->addAction(it));
223 values.push_back(it);
224 }
225
226 // add the save value portion of the menu
227 menu->addSeparator();
228 QAction* SaveValueAction = menu->addAction(tr("Save Value"));
229 std::vector<QString> savedValues = getSavedValues();
230
231 for (const auto& savedValue : savedValues) {
232 actions.push_back(menu->addAction(savedValue));
233 values.push_back(savedValue);
234 }
235
236 // call the menu and wait until its back
237 QAction* saveAction = menu->exec(event->globalPos());
238
239 // look what the user has chosen
240 if (saveAction == SaveValueAction) {
241 pushToSavedValues();
242 }
243 else {
244 int i = 0;
245 for (auto it = actions.begin(); it != actions.end(); ++it, i++) {
246 if (*it == saveAction) {
247 this->setText(values[i]);
248 }
249 }
250 }
251
252 delete menu;
253 }
254
255 void InputField::newInput(const QString& text)
256 {
257 Quantity res;
258 try {
259 QString input = text;
260 fixup(input);
261
262 if (isBound()) {
263 std::shared_ptr<Expression> e(
264 ExpressionParser::parse(getPath().getDocumentObject(), input.toUtf8())
265 );
266
267 setExpression(e);
268
269 std::unique_ptr<Expression> evalRes(getExpression()->eval());
270
271 auto* value = freecad_cast<NumberExpression*>(evalRes.get());
272 if (value) {
273 res.setValue(value->getValue());
274 res.setUnit(value->getUnit());
275 }
276 }
277 else {
278 res = Quantity::parse(input.toStdString());
279 }
280 }
281 catch (Base::Exception& e) {
282 QString errorText = QString::fromLatin1(e.what());
283 if (iconLabel->isHidden()) {
284 iconLabel->setVisible(true);
285 }
286 Q_EMIT parseError(errorText);
287 validInput = false;
288 return;
289 }
290
291 if (res.isDimensionless()) {
292 res.setUnit(this->actUnit);
293 }
294
295 // check if unit fits!
296 if (actUnit != Unit::One && !res.isDimensionless() && actUnit != res.getUnit()) {
297 if (iconLabel->isHidden()) {
298 iconLabel->setVisible(true);
299 }
300 Q_EMIT parseError(QStringLiteral("Wrong unit"));
301 validInput = false;
302 return;
303 }
304
305 if (iconLabel->isVisible()) {
306 iconLabel->setVisible(false);
307 }
308 validInput = true;
309
310 if (res.getValue() > Maximum) {
311 res.setValue(Maximum);
312 }
313 if (res.getValue() < Minimum) {
314 res.setValue(Minimum);
315 }
316
317 double dFactor;
318 std::string unitStr;
319 res.getUserString(dFactor, unitStr);
320 actUnitValue = res.getValue() / dFactor;
321 // Preserve previous format
322 res.setFormat(this->actQuantity.getFormat());
323 actQuantity = res;
324
325 // signaling
326 Q_EMIT valueChanged(res);
327 Q_EMIT valueChanged(res.getValue());
328 }
329
330 void InputField::pushToHistory(const QString& valueq)
331 {
332 QString val;
333 if (valueq.isEmpty()) {
334 val = this->text();
335 }
336 else {
337 val = valueq;
338 }
339
340 // check if already in:
341 std::vector<QString> hist = InputField::getHistory();
342 for (const auto& it : hist) {
343 if (it == val) {
344 return;
345 }
346 }
347
348 std::string value(val.toUtf8());
349 if (_handle.isValid()) {
350 char hist1[21];
351 char hist0[21];
352 for (int i = HistorySize - 1; i >= 0; i--) {
353 snprintf(hist1, 20, "Hist%i", i + 1);
354 snprintf(hist0, 20, "Hist%i", i);
355 std::string tHist = _handle->GetASCII(hist0, "");
356 if (!tHist.empty()) {
357 _handle->SetASCII(hist1, tHist.c_str());
358 }
359 }
360 _handle->SetASCII("Hist0", value.c_str());
361 }
362 }
363
364 std::vector<QString> InputField::getHistory()
365 {
366 std::vector<QString> res;
367
368 if (_handle.isValid()) {
369 std::string tmp;
370 char hist[21];
371 for (int i = 0; i < HistorySize; i++) {
372 snprintf(hist, 20, "Hist%i", i);
373 tmp = _handle->GetASCII(hist, "");
374 if (!tmp.empty()) {
375 res.push_back(QString::fromUtf8(tmp.c_str()));
376 }
377 else {
378 break; // end of history reached
379 }
380 }
381 }
382 return res;
383 }
384
385 void InputField::setToLastUsedValue()
386 {
387 std::vector<QString> hist = getHistory();
388 if (!hist.empty()) {
389 this->setText(hist[0]);
390 }
391 }
392
393 void InputField::pushToSavedValues(const QString& valueq)
394 {
395 std::string value;
396 if (valueq.isEmpty()) {
397 value = this->text().toUtf8().constData();
398 }
399 else {
400 value = valueq.toUtf8().constData();
401 }
402
403 if (_handle.isValid()) {
404 char hist1[21];
405 char hist0[21];
406 for (int i = SaveSize - 1; i >= 0; i--) {
407 snprintf(hist1, 20, "Save%i", i + 1);
408 snprintf(hist0, 20, "Save%i", i);
409 std::string tHist = _handle->GetASCII(hist0, "");
410 if (!tHist.empty()) {
411 _handle->SetASCII(hist1, tHist.c_str());
412 }
413 }
414 _handle->SetASCII("Save0", value.c_str());
415 }
416 }
417
418 std::vector<QString> InputField::getSavedValues()
419 {
420 std::vector<QString> res;
421
422 if (_handle.isValid()) {
423 std::string tmp;
424 char hist[21];
425 for (int i = 0; i < SaveSize; i++) {
426 snprintf(hist, 20, "Save%i", i);
427 tmp = _handle->GetASCII(hist, "");
428 if (!tmp.empty()) {
429 res.push_back(QString::fromUtf8(tmp.c_str()));
430 }
431 else {
432 break; // end of history reached
433 }
434 }
435 }
436 return res;
437 }
438
439 /** Sets the preference path to \a path. */
440 void InputField::setParamGrpPath(const QByteArray& path)
441 {
442 _handle = App::GetApplication().GetParameterGroupByPath(path);
443 if (_handle.isValid()) {
444 sGroupString = (const char*)path;
445 }
446 }
447
448 /** Returns the widget's preferences path. */
449 QByteArray InputField::paramGrpPath() const
450 {
451 if (_handle.isValid()) {
452 return sGroupString.c_str();
453 }
454 return {};
455 }
456
457 /// sets the field with a quantity
458 void InputField::setValue(const Base::Quantity& quant)
459 {
460 actQuantity = quant;
461 // check limits
462 if (actQuantity.getValue() > Maximum) {
463 actQuantity.setValue(Maximum);
464 }
465 if (actQuantity.getValue() < Minimum) {
466 actQuantity.setValue(Minimum);
467 }
468
469 actUnit = quant.getUnit();
470
471 updateText(quant);
472 }
473
474 void InputField::setValue(const double& value)
475 {
476 setValue(Base::Quantity(value, actUnit));
477 }
478
479 double InputField::rawValue() const
480 {
481 return this->actQuantity.getValue();
482 }
483
484 void InputField::setUnit(const Base::Unit& unit)
485 {
486 actUnit = unit;
487 actQuantity.setUnit(unit);
488 updateText(actQuantity);
489 }
490
491 const Base::Unit& InputField::getUnit() const
492 {
493 return actUnit;
494 }
495
496 /// get stored, valid quantity as a string
497 QString InputField::getQuantityString() const
498 {
499 return QString::fromStdString(actQuantity.getUserString());
500 }
501
502 /// set, validate and display quantity from a string. Must match existing units.
503 void InputField::setQuantityString(const QString& text)
504 {
505 // Input and then format the quantity
506 newInput(text);
507 updateText(actQuantity);
508 }
509
510 /// return the quantity in C locale, i.e. decimal separator is a dot.
511 QString InputField::rawText() const
512 {
513 double factor;
514 std::string unit;
515 double value = actQuantity.getValue();
516 actQuantity.getUserString(factor, unit);
517 return QStringLiteral("%1 %2").arg(value / factor).arg(QString::fromStdString(unit));
518 }
519
520 /// expects the string in C locale and internally converts it into the OS-specific locale
521 void InputField::setRawText(const QString& text)
522 {
523 Base::Quantity quant = Base::Quantity::parse(text.toStdString());
524 // Input and then format the quantity
525 newInput(QString::fromStdString(quant.getUserString()));
526 updateText(actQuantity);
527 }
528
529 /// get the value of the singleStep property
530 double InputField::singleStep() const
531 {
532 return StepSize;
533 }
534
535 /// set the value of the singleStep property
536 void InputField::setSingleStep(double s)
537 {
538 StepSize = s;
539 }
540
541 /// get the value of the maximum property
542 double InputField::maximum() const
543 {
544 return Maximum;
545 }
546
547 /// set the value of the maximum property
548 void InputField::setMaximum(double m)
549 {
550 Maximum = m;
551 if (actQuantity.getValue() > Maximum) {
552 actQuantity.setValue(Maximum);
553 updateText(actQuantity);
554 }
555 }
556
557 /// get the value of the minimum property
558 double InputField::minimum() const
559 {
560 return Minimum;
561 }
562
563 /// set the value of the minimum property
564 void InputField::setMinimum(double m)
565 {
566 Minimum = m;
567 if (actQuantity.getValue() < Minimum) {
568 actQuantity.setValue(Minimum);
569 updateText(actQuantity);
570 }
571 }
572
573 void InputField::setUnitText(const QString& str)
574 {
575 try {
576 Base::Quantity quant = Base::Quantity::parse(str.toStdString());
577 setUnit(quant.getUnit());
578 }
579 catch (...) {
580 // ignore exceptions
581 }
582 }
583
584 QString InputField::getUnitText()
585 {
586 double dFactor;
587 std::string unitStr;
588 actQuantity.getUserString(dFactor, unitStr);
589 return QString::fromStdString(unitStr);
590 }
591
592 int InputField::getPrecision() const
593 {
594 return this->actQuantity.getFormat().getPrecision();
595 }
596
597 void InputField::setPrecision(const int precision)
598 {
599 Base::QuantityFormat format = actQuantity.getFormat();
600 format.setPrecision(precision);
601 actQuantity.setFormat(format);
602 updateText(actQuantity);
603 }
604
605 QString InputField::getFormat() const
606 {
607 return {QChar::fromLatin1(actQuantity.getFormat().toFormat())};
608 }
609
610 void InputField::setFormat(const QString& format)
611 {
612 if (format.isEmpty()) {
613 return;
614 }
615 QChar c = format[0];
616 Base::QuantityFormat f = this->actQuantity.getFormat();
617 f.format = Base::QuantityFormat::toFormat(c.toLatin1());
618 actQuantity.setFormat(f);
619 updateText(actQuantity);
620 }
621
622 // get the value of the minimum property
623 int InputField::historySize() const
624 {
625 return HistorySize;
626 }
627
628 // set the value of the minimum property
629 void InputField::setHistorySize(int i)
630 {
631 assert(i >= 0);
632 assert(i < 100);
633
634 HistorySize = i;
635 }
636
637 void InputField::selectNumber()
638 {
639 QString expr = QStringLiteral("^([%1%2]?[0-9\\%3]*)\\%4?([0-9]+(%5[%1%2]?[0-9]+)?)")
640 .arg(locale().negativeSign())
641 .arg(locale().positiveSign())
642 .arg(locale().groupSeparator())
643 .arg(locale().decimalPoint())
644 .arg(locale().exponential());
645 auto rmatch = QRegularExpression(expr).match(text());
646 if (rmatch.hasMatch()) {
647 setSelection(0, rmatch.capturedLength());
648 }
649 }
650
651 void InputField::showEvent(QShowEvent* event)
652 {
653 QLineEdit::showEvent(event);
654
655 bool selected = this->hasSelectedText();
656 updateText(actQuantity);
657 if (selected) {
658 selectNumber();
659 }
660 }
661
662 void InputField::focusInEvent(QFocusEvent* event)
663 {
664 if (event->reason() == Qt::TabFocusReason || event->reason() == Qt::BacktabFocusReason
665 || event->reason() == Qt::ShortcutFocusReason) {
666 if (!this->hasSelectedText()) {
667 selectNumber();
668 }
669 }
670
671 QLineEdit::focusInEvent(event);
672 }
673
674 void InputField::focusOutEvent(QFocusEvent* event)
675 {
676 try {
677 if (Quantity::parse(this->text().toStdString()).isDimensionless()) {
678 // if user didn't enter a unit, we virtually compensate
679 // the multiplication factor induced by user unit system
680 double factor;
681 std::string unitStr;
682 actQuantity.getUserString(factor, unitStr);
683 actQuantity = actQuantity * factor;
684 }
685 }
686 catch (const Base::ParserError&) {
687 // do nothing, let apply the last known good value
688 }
689 this->setText(QString::fromStdString(actQuantity.getUserString()));
690 QLineEdit::focusOutEvent(event);
691 }
692
693 void InputField::keyPressEvent(QKeyEvent* event)
694 {
695 if (isReadOnly()) {
696 QLineEdit::keyPressEvent(event);
697 return;
698 }
699
700 double val = actUnitValue;
701
702 switch (event->key()) {
703 case Qt::Key_Up:
704 val += StepSize;
705 if (val > Maximum) {
706 val = Maximum;
707 }
708 break;
709 case Qt::Key_Down:
710 val -= StepSize;
711 if (val < Minimum) {
712 val = Minimum;
713 }
714 break;
715 default:
716 QLineEdit::keyPressEvent(event);
717 return;
718 }
719
720 double dFactor;
721 std::string unitStr;
722 actQuantity.getUserString(dFactor, unitStr);
723 this->setText(QStringLiteral("%L1 %2").arg(val).arg(QString::fromStdString(unitStr)));
724 event->accept();
725 }
726
727 void InputField::wheelEvent(QWheelEvent* event)
728 {
729 if (!hasFocus()) {
730 return;
731 }
732
733 if (isReadOnly()) {
734 QLineEdit::wheelEvent(event);
735 return;
736 }
737
738 double factor = event->modifiers() & Qt::ControlModifier ? 10 : 1;
739 double step = event->angleDelta().y() > 0 ? StepSize : -StepSize;
740 double val = actUnitValue + factor * step;
741 if (val > Maximum) {
742 val = Maximum;
743 }
744 else if (val < Minimum) {
745 val = Minimum;
746 }
747
748 double dFactor;
749 std::string unitStr;
750 actQuantity.getUserString(dFactor, unitStr);
751
752 this->setText(QStringLiteral("%L1 %2").arg(val).arg(QString::fromStdString(unitStr)));
753 selectNumber();
754 event->accept();
755 }
756
757 void InputField::fixup(QString& input) const
758 {
759 input.remove(locale().groupSeparator());
760
761 QString asciiMinus(QStringLiteral("-"));
762 QString localeMinus(locale().negativeSign());
763 if (localeMinus != asciiMinus) {
764 input.replace(localeMinus, asciiMinus);
765 }
766
767 QString asciiPlus(QStringLiteral("+"));
768 QString localePlus(locale().positiveSign());
769 if (localePlus != asciiPlus) {
770 input.replace(localePlus, asciiPlus);
771 }
772
773 // workaround for improper handling of plus sign
774 // in Building US unit system
775 // https://github.com/FreeCAD/FreeCAD/issues/11345
776 QString asciiMinusMinus(QStringLiteral("--"));
777 input.replace(asciiPlus, asciiMinusMinus);
778 }
779
780 QValidator::State InputField::validate(QString& input, int& pos) const
781 {
782 Q_UNUSED(pos);
783 try {
784 Quantity res;
785 QString text = input;
786 fixup(text);
787 res = Quantity::parse(text.toStdString());
788
789 double factor;
790 std::string unitStr;
791 res.getUserString(factor, unitStr);
792 double value = res.getValue() / factor;
793 // disallow one to enter numbers out of range
794 if (value > this->Maximum || value < this->Minimum) {
795 return QValidator::Invalid;
796 }
797 }
798 catch (Base::Exception&) {
799 // Actually invalid input but the newInput slot gives
800 // some feedback
801 return QValidator::Intermediate;
802 }
803
804 return QValidator::Acceptable;
805 }
806
807 // --------------------------------------------------------------------
808
809 InputValidator::InputValidator(InputField* parent)
810 : QValidator(parent)
811 , dptr(parent)
812 {}
813
814 InputValidator::~InputValidator() = default;
815
816 void InputValidator::fixup(QString& input) const
817 {
818 dptr->fixup(input);
819 }
820
821 QValidator::State InputValidator::validate(QString& input, int& pos) const
822 {
823 return dptr->validate(input, pos);
824 }
825
826
827 #include "moc_InputField.cpp"