Debian Codegraph @

src/Gui/QuantitySpinBox.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2014 Werner Mayer <wmayer[at]users.sourceforge.net> *
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., 51 Franklin Street, *
19 * Fifth Floor, Boston, MA 02110-1301, USA *
20 * *
21 ***************************************************************************/
22
23 #include <limits>
24 #include <QApplication>
25 #include <QDebug>
26 #include <QFocusEvent>
27 #include <QFontMetrics>
28 #include <QLineEdit>
29 #include <QRegularExpression>
30 #include <QRegularExpressionMatch>
31 #include <QStyle>
32 #include <QStyleOptionSpinBox>
33 #include <QToolTip>
34
35 #include <sstream>
36
37 #include <App/Application.h>
38 #include <App/Document.h>
39 #include <App/DocumentObject.h>
40 #include <App/ExpressionParser.h>
41 #include <Base/Exception.h>
42 #include <Base/UnitsApi.h>
43 #include <Base/Tools.h>
44 #include <Base/UnitsSchema.h>
45
46 #include "QuantitySpinBox.h"
47 #include "QuantitySpinBox_p.h"
48 #include "Command.h"
49 #include "Dialogs/DlgExpressionInput.h"
50 #include "Tools.h"
51 #include "Widgets.h"
52
53
54 using namespace Gui;
55 using namespace App;
56 using namespace Base;
57
58 namespace Gui
59 {
60
61 class QuantitySpinBoxPrivate
62 {
63 public:
64 QuantitySpinBoxPrivate(QuantitySpinBox* q)
65 : validInput(true)
66 , pendingEmit(false)
67 , normalize(true)
68 , checkRangeInExpression(false)
69 , unitValue(0)
70 , maximum(std::numeric_limits<double>::max())
71 , minimum(-std::numeric_limits<double>::max())
72 , singleStep(1.0)
73 , q_ptr(q)
74 {}
75 ~QuantitySpinBoxPrivate() = default;
76
77 QString stripped(const QString& t, int* pos) const
78 {
79 QString text = t;
80 const int s = text.size();
81 text = text.trimmed();
82 if (pos) {
83 (*pos) -= (s - text.size());
84 }
85 return text;
86 }
87
88 bool validate(QString& input, Base::Quantity& result, const App::ObjectIdentifier& path) const
89 {
90 Q_Q(const QuantitySpinBox);
91
92 // Do not accept empty strings because the parser will consider
93 // " unit" as "1 unit" which is not the desired behaviour (see #0004104)
94 if (input.isEmpty()) {
95 return false;
96 }
97
98 bool success = false;
99 QString tmp = input;
100
101 auto validateInput = [&](QString& tmp) -> QValidator::State {
102 QValidator::State state;
103 Base::Quantity res = validateAndInterpret(tmp, state, path);
104 res.setFormat(quantity.getFormat());
105 if (state == QValidator::Acceptable) {
106 success = true;
107 result = res;
108 input = tmp;
109 }
110 return state;
111 };
112
113 QValidator::State state = validateInput(tmp);
114 if (state == QValidator::Intermediate && q->hasExpression()) {
115 // Accept the expression as it is but try to add the right unit string
116 success = true;
117
118 Base::Quantity quantity;
119 double value;
120 if (parseString(input, quantity, value, path)) {
121 quantity.setUnit(unit);
122 result = quantity;
123
124 // Now translate the quantity into its string representation using the user-defined
125 // unit system
126 input = QString::fromStdString(Base::UnitsApi::schemaTranslate(result));
127 }
128 }
129
130 return success;
131 }
132 bool parseString(
133 const QString& str,
134 Base::Quantity& result,
135 double& value,
136 const App::ObjectIdentifier& path
137 ) const
138 {
139 App::ObjectIdentifier pathtmp = path;
140 try {
141 QString copy = str;
142 copy.remove(locale.groupSeparator());
143
144 // Expression parser
145 std::shared_ptr<Expression> expr(
146 ExpressionParser::parse(path.getDocumentObject(), copy.toUtf8().constData())
147 );
148 if (expr) {
149
150 std::unique_ptr<Expression> res(expr->eval());
151 NumberExpression* n = freecad_cast<NumberExpression*>(res.get());
152 if (n) {
153 result = n->getQuantity();
154 value = result.getValue();
155 return true;
156 }
157 }
158 }
159 catch (Base::Exception&) {
160 return false;
161 }
162 return false;
163 }
164 Base::Quantity validateAndInterpret(
165 QString& input,
166 QValidator::State& state,
167 const App::ObjectIdentifier& path
168 ) const
169 {
170 Base::Quantity res;
171 const double max = this->maximum;
172 const double min = this->minimum;
173
174 QString copy = input;
175 double value = min;
176 bool ok = false;
177
178 QChar plus = QLatin1Char('+'), minus = QLatin1Char('-');
179
180 if (locale.negativeSign() != minus) {
181 copy.replace(locale.negativeSign(), minus);
182 }
183 if (locale.positiveSign() != plus) {
184 copy.replace(locale.positiveSign(), plus);
185 }
186
187 QString reverseUnitStr = unitStr;
188 std::reverse(reverseUnitStr.begin(), reverseUnitStr.end());
189
190 // Prep for expression parser
191 // This regex matches chunks between +,-,$,^ accounting for matching parenthesis.
192 QRegularExpression chunkRe(
193 QStringLiteral("(?<=^|[\\+\\-])((\\((?>[^()]|(?2))*\\))|[^\\+\\-\n])*(?=$|[\\+\\-])")
194 );
195 QRegularExpressionMatchIterator expressionChunk = chunkRe.globalMatch(copy);
196 unsigned int lengthOffset = 0;
197 while (expressionChunk.hasNext()) {
198 QRegularExpressionMatch matchChunk = expressionChunk.next();
199 QString origionalChunk = matchChunk.captured(0);
200 QString copyChunk = origionalChunk;
201 std::reverse(copyChunk.begin(), copyChunk.end());
202
203 // Reused regex patterns
204 static const std::string regexUnits
205 = "sAV|VC|lim|nim|im|hpm|[mf]?bl|°|ged|dar|nog|″|′|rroT[uµm]?|K[uµm]?|A[mkM]?|F["
206 "pnuµm]?|C|S[uµmkM]?|zH[kMGT]?|H[nuµm]?|mhO[kM]?|J[mk]?|Ve[kM]?|V[mk]?|hWk|sW|"
207 "lack?|N[mkM]?|g[uµmk]?|lm?|(?<=\\b|[^a-zA-Z])m[nuµmcdk]?|uoht|ni|\"|'|dy|dc|bW|"
208 "T|t|zo|ts|twc|Wk?|aP[kMG]?|is[pk]|h|G|M|tfc|tfqs|tf|s";
209 static const std::string regexUnitlessFunctions
210 = "soca|nisa|2nata|nata|hsoc|hnis|hnat|soc|nat|nis|pxe|gol|01gol";
211 static const std::string regexConstants = "e|ip|lomm|lom";
212 static const std::string regexNumber = "\\d+\\s*\\.?\\s*\\d*|\\.\\s*\\d+";
213
214 // If expression does not contain /*() or ^, this regex will not find anything
215 if (copy.contains(QLatin1Char('/')) || copy.contains(QLatin1Char('*'))
216 || copy.contains(QLatin1Char('(')) || copy.contains(QLatin1Char(')'))
217 || copy.contains(QLatin1Char('^'))) {
218 // Find units and replace 1/2mm -> 1/2*(1mm), 1^2mm -> 1^2*(1mm)
219 QRegularExpression fixUnits(
220 QString::fromStdString(
221 "(" + regexUnits + ")(\\s*\\)|(?:\\*|(?:\\)(?:(?:\\s*(?:" + regexConstants
222 + "|\\)(?:[^()]|(?R))*\\((?:" + regexUnitlessFunctions + ")|" + regexNumber
223 + "))|(?R))*\\(|(?:\\s*(?:" + regexConstants
224 + "|\\)(?:[^()]|(?R))*\\((?:" + regexUnitlessFunctions + ")|" + regexNumber
225 + "))))+(?:[\\/\\^]|(.*$))(?!(" + regexUnits + ")))"
226 )
227 );
228 QRegularExpressionMatch fixUnitsMatch = fixUnits.match(copyChunk);
229
230 // 3rd capture group being filled indicates regex bailed out; no match.
231 if (fixUnitsMatch.lastCapturedIndex() == 2
232 || (fixUnitsMatch.lastCapturedIndex() == 3
233 && fixUnitsMatch.captured(3).isEmpty())) {
234 QString matchUnits = fixUnitsMatch.captured(1);
235 QString matchNumbers = fixUnitsMatch.captured(2);
236 copyChunk.replace(
237 matchUnits + matchNumbers,
238 QStringLiteral(")") + matchUnits + QStringLiteral("1(*") + matchNumbers
239 );
240 }
241 }
242
243 // Add default units to string if none are present
244 if (!copyChunk.contains(reverseUnitStr)) { // Fast check
245 QRegularExpression unitsRe(
246 QString::fromStdString(
247 "(?<=\\b|[^a-zA-Z])(" + regexUnits
248 + ")(?=\\b|[^a-zA-Z])|°|″|′|\"|'|\\p{L}\\.\\p{L}|\\[\\p{L}"
249 )
250 );
251
252 QRegularExpressionMatch match = unitsRe.match(copyChunk);
253 if (!match.hasMatch() && !copyChunk.isEmpty()) { // If no units are found, use
254 // default units
255 copyChunk.prepend(
256 QStringLiteral(")") + reverseUnitStr + QStringLiteral("1(*")
257 ); // Add units to the end of chunk *(1unit)
258 }
259 }
260
261 std::reverse(copyChunk.begin(), copyChunk.end());
262
263 copy.replace(
264 matchChunk.capturedStart() + lengthOffset,
265 matchChunk.capturedEnd() - matchChunk.capturedStart(),
266 copyChunk
267 );
268 lengthOffset += copyChunk.length() - origionalChunk.length();
269 }
270
271 ok = parseString(copy, res, value, path);
272
273 // If result does not have unit: add default unit
274 if (res.isDimensionless()) {
275 res.setUnit(unit);
276 }
277
278 if (!ok) {
279 // input may not be finished
280 state = QValidator::Intermediate;
281 }
282 else if (value >= min && value <= max) {
283 state = QValidator::Acceptable;
284 }
285 else if (max == min) { // when max and min is the same the only non-Invalid input is max
286 // (or min)
287 state = QValidator::Invalid;
288 }
289 else {
290 if ((value >= 0 && value > max) || (value < 0 && value < min)) {
291 state = QValidator::Invalid;
292 }
293 else {
294 state = QValidator::Intermediate;
295 }
296 }
297 if (state != QValidator::Acceptable) {
298 res.setValue(max > 0 ? min : max);
299 }
300
301 return res;
302 }
303
304 QLocale locale;
305 bool validInput;
306 bool pendingEmit;
307 bool normalize;
308 bool checkRangeInExpression;
309 QString validStr;
310 Base::Quantity quantity;
311 Base::Quantity cached;
312 Base::Unit unit;
313 double unitValue;
314 QString unitStr;
315 double maximum;
316 double minimum;
317 double singleStep;
318 QuantitySpinBox* q_ptr;
319 std::unique_ptr<Base::UnitsSchema> scheme;
320 Q_DECLARE_PUBLIC(QuantitySpinBox)
321 };
322 } // namespace Gui
323
324 QuantitySpinBox::QuantitySpinBox(QWidget* parent)
325 : QAbstractSpinBox(parent)
326 , ExpressionSpinBox(this)
327 , d_ptr(new QuantitySpinBoxPrivate(this))
328 {
329 d_ptr->locale = locale();
330 this->setContextMenuPolicy(Qt::DefaultContextMenu);
331 connect(lineEdit(), &QLineEdit::textChanged, this, &QuantitySpinBox::userInput);
332 connect(this, &QuantitySpinBox::editingFinished, this, [&] { this->handlePendingEmit(true); });
333 }
334
335 QuantitySpinBox::~QuantitySpinBox() = default;
336
337 void QuantitySpinBox::bind(const App::ObjectIdentifier& _path)
338 {
339 ExpressionSpinBox::bind(_path);
340 }
341
342 void QuantitySpinBox::showIcon()
343 {
344 iconLabel->show();
345 }
346
347 QString QuantitySpinBox::boundToName() const
348 {
349 if (isBound()) {
350 std::string path = getPath().toString();
351 return QString::fromStdString(path);
352 }
353 return {};
354 }
355
356 /**
357 * @brief Create an object identifier by name.
358 *
359 * An identifier is written as document#documentobject.property.subproperty1...subpropertyN
360 * document# may be dropped, in this case the active document is used.
361 */
362 void QuantitySpinBox::setBoundToByName(const QString& name)
363 {
364 try {
365 // get document
366 App::Document* doc = App::GetApplication().getActiveDocument();
367 QStringList list = name.split(QLatin1Char('#'));
368 if (list.size() > 1) {
369 doc = App::GetApplication().getDocument(list.front().toLatin1());
370 list.pop_front();
371 }
372
373 if (!doc) {
374 qDebug() << "No such document";
375 return;
376 }
377
378 // first element is assumed to be the document name
379 list = list.front().split(QLatin1Char('.'));
380
381 // get object
382 App::DocumentObject* obj = doc->getObject(list.front().toLatin1());
383 if (!obj) {
384 qDebug() << "No object " << list.front() << " in document";
385 return;
386 }
387 list.pop_front();
388
389 // the rest of the list defines the property and eventually subproperties
390 App::ObjectIdentifier path(obj);
391 path.setDocumentName(std::string(doc->getName()), true);
392 path.setDocumentObjectName(std::string(obj->getNameInDocument()), true);
393
394 for (const auto& it : list) {
395 path << App::ObjectIdentifier::Component::SimpleComponent(it.toLatin1().constData());
396 }
397
398 if (path.getProperty()) {
399 bind(path);
400 }
401 }
402 catch (const Base::Exception& e) {
403 qDebug() << e.what();
404 }
405 }
406
407 QString Gui::QuantitySpinBox::expressionText() const
408 {
409 try {
410 if (hasExpression()) {
411 return QString::fromStdString(getExpressionString());
412 }
413 }
414 catch (const Base::Exception& e) {
415 qDebug() << e.what();
416 }
417 return {};
418 }
419
420 void QuantitySpinBox::evaluateExpression()
421 {
422 if (isBound() && getExpression()) {
423 showValidExpression(Number::SetIfNumber);
424 }
425 }
426
427 void Gui::QuantitySpinBox::setNumberExpression(App::NumberExpression* expr)
428 {
429 updateEdit(getUserString(expr->getQuantity()));
430 handlePendingEmit();
431 }
432
433 bool QuantitySpinBox::apply(const std::string& propName)
434 {
435 if (!ExpressionBinding::apply(propName)) {
436 double dValue = value().getValue();
437 return assignToProperty(propName, dValue);
438 }
439
440 return false;
441 }
442
443 void QuantitySpinBox::resizeEvent(QResizeEvent* event)
444 {
445 QAbstractSpinBox::resizeEvent(event);
446 resizeWidget();
447 }
448
449 void Gui::QuantitySpinBox::keyPressEvent(QKeyEvent* event)
450 {
451 Q_D(QuantitySpinBox);
452
453 const auto isEnter = event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return;
454
455 if (d->normalize && isEnter && !isNormalized()) {
456 // ensure that input is up to date
457 handlePendingEmit();
458
459 normalize();
460 return;
461 }
462
463 if (!handleKeyEvent(event->text())) {
464 QAbstractSpinBox::keyPressEvent(event);
465 }
466
467 if (isEnter) {
468 returnPressed();
469 }
470 }
471
472 void Gui::QuantitySpinBox::paintEvent(QPaintEvent*)
473 {
474 QStyleOptionSpinBox opt;
475 initStyleOption(&opt);
476 drawControl(opt);
477 }
478
479 void QuantitySpinBox::updateText(const Quantity& quant)
480 {
481 Q_D(QuantitySpinBox);
482
483 double dFactor;
484 QString txt = getUserString(quant, dFactor, d->unitStr);
485 d->unitValue = quant.getValue() / dFactor;
486 updateEdit(txt);
487 handlePendingEmit();
488 }
489
490 void QuantitySpinBox::updateEdit(const QString& text)
491 {
492 Q_D(QuantitySpinBox);
493
494 QLineEdit* edit = lineEdit();
495
496 bool empty = edit->text().isEmpty();
497 int cursor = edit->cursorPosition();
498 int selsize = edit->selectedText().size();
499
500 edit->setText(text);
501
502 cursor = qBound(0, cursor, qMax(0, edit->displayText().size() - d->unitStr.size()));
503 if (selsize > 0) {
504 edit->setSelection(0, cursor);
505 }
506 else {
507 edit->setCursorPosition(empty ? 0 : cursor);
508 }
509 }
510
511 void QuantitySpinBox::validateInput()
512 {
513 Q_D(QuantitySpinBox);
514
515 QValidator::State state;
516 QString text = lineEdit()->text();
517 const App::ObjectIdentifier& path = getPath();
518 d->validateAndInterpret(text, state, path);
519 if (state != QValidator::Acceptable) {
520 updateEdit(d->validStr);
521 }
522
523 handlePendingEmit();
524 }
525
526 Base::Quantity QuantitySpinBox::value() const
527 {
528 Q_D(const QuantitySpinBox);
529 return d->quantity;
530 }
531
532 double QuantitySpinBox::rawValue() const
533 {
534 Q_D(const QuantitySpinBox);
535 return d->quantity.getValue();
536 }
537
538 void QuantitySpinBox::normalize()
539 {
540 // this does not really change the value, only the representation
541 QSignalBlocker blocker(this);
542
543 Q_D(const QuantitySpinBox);
544 return setValue(d->quantity);
545 }
546
547 bool QuantitySpinBox::isNormalized()
548 {
549 static const QRegularExpression operators(
550 QStringLiteral("[+\\-/*]"),
551 QRegularExpression::CaseInsensitiveOption
552 );
553
554 Q_D(const QuantitySpinBox);
555
556 // this check is two level
557 // 1. We consider every string that does not contain operators as normalized
558 // 2. If it does contain operators we check if it differs from normalized input - as some
559 // operators like - can be allowed even in normalized case.
560 return !d->validStr.contains(operators)
561 || d->validStr.toStdString() == d->quantity.getUserString();
562 }
563
564 void QuantitySpinBox::setValue(const Base::Quantity& value)
565 {
566 Q_D(QuantitySpinBox);
567 d->quantity = value;
568 // check limits
569 if (d->quantity.getValue() > d->maximum) {
570 d->quantity.setValue(d->maximum);
571 }
572 if (d->quantity.getValue() < d->minimum) {
573 d->quantity.setValue(d->minimum);
574 }
575
576 d->unit = value.getUnit();
577
578 updateText(value);
579 }
580
581 void QuantitySpinBox::setValue(double value)
582 {
583 Q_D(QuantitySpinBox);
584
585 Base::QuantityFormat currentformat = d->quantity.getFormat();
586 auto quantity = Base::Quantity(value, d->unit);
587 quantity.setFormat(currentformat);
588
589 setValue(quantity);
590 }
591
592 bool QuantitySpinBox::autoNormalize() const
593 {
594 Q_D(const QuantitySpinBox);
595 return d->normalize;
596 }
597
598 void QuantitySpinBox::setAutoNormalize(bool normalize)
599 {
600 Q_D(QuantitySpinBox);
601 d->normalize = normalize;
602 }
603
604 bool QuantitySpinBox::hasValidInput() const
605 {
606 Q_D(const QuantitySpinBox);
607 return d->validInput;
608 }
609
610 // Gets called after call of 'validateAndInterpret'
611 void QuantitySpinBox::userInput(const QString& text)
612 {
613 Q_D(QuantitySpinBox);
614
615 d->pendingEmit = true;
616
617 QString tmp = text;
618 Base::Quantity res;
619 const App::ObjectIdentifier& path = getPath();
620 if (d->validate(tmp, res, path)) {
621 d->validStr = tmp;
622 d->validInput = true;
623 }
624 else {
625 d->validInput = false;
626
627 // only emit signal to reset EditableDatumLabel if the input is truly empty or has
628 // no meaningful number don't emit for partially typed numbers like "71." which are
629 // temporarily invalid
630 const QString trimmedText = text.trimmed();
631 static const QRegularExpression partialNumberRegex(QStringLiteral(R"([+-]?(\d+)?(\.,\d*)?)"));
632 if (trimmedText.isEmpty() || !trimmedText.contains(partialNumberRegex)) {
633 // we have to emit here signal explicitly as validator will not pass
634 // this value further but we want to check it to disable isSet flag if
635 // it has been set previously
636 Q_EMIT valueChanged(d->quantity.getValue());
637 }
638 return;
639 }
640
641 if (keyboardTracking()) {
642 d->cached = res;
643 handlePendingEmit(false);
644 }
645 else {
646 d->cached = res;
647 }
648 }
649
650 void QuantitySpinBox::openFormulaDialog()
651 {
652 Q_ASSERT(isBound());
653
654 Q_D(const QuantitySpinBox);
655 auto box = new Gui::Dialog::DlgExpressionInput(getPath(), getExpression(), d->unit, this);
656 if (d->checkRangeInExpression) {
657 box->setRange(d->minimum, d->maximum);
658 }
659 QObject::connect(box, &Gui::Dialog::DlgExpressionInput::finished, [this, box]() {
660 if (box->result() == QDialog::Accepted) {
661 setExpression(box->getExpression());
662 }
663 else if (box->discardedFormula()) {
664 setExpression(std::shared_ptr<Expression>());
665 }
666
667 updateExpression();
668 box->deleteLater();
669 Q_EMIT showFormulaDialog(false);
670 });
671 box->show();
672
673 QPoint pos = mapToGlobal(QPoint(0, 0));
674 box->move(pos - box->expressionPosition());
675 Gui::adjustDialogPosition(box);
676
677 Q_EMIT showFormulaDialog(true);
678 }
679
680 void QuantitySpinBox::handlePendingEmit(bool updateUnit /* = true */)
681 {
682 updateFromCache(true, updateUnit);
683 }
684
685 void QuantitySpinBox::updateFromCache(bool notify, bool updateUnit /* = true */)
686 {
687 Q_D(QuantitySpinBox);
688 if (d->pendingEmit) {
689 double factor;
690 const Base::Quantity& res = d->cached;
691 auto tmpUnit(d->unitStr);
692 QString text = getUserString(res, factor, updateUnit ? d->unitStr : tmpUnit);
693 d->unitValue = res.getValue() / factor;
694 d->quantity = res;
695
696 // signaling
697 if (notify) {
698 d->pendingEmit = false;
699 Q_EMIT valueChanged(res);
700 Q_EMIT valueChanged(res.getValue());
701 Q_EMIT textChanged(text);
702 }
703 }
704 }
705
706 Base::Unit QuantitySpinBox::unit() const
707 {
708 Q_D(const QuantitySpinBox);
709 return d->unit;
710 }
711
712 void QuantitySpinBox::setUnit(const Base::Unit& unit)
713 {
714 Q_D(QuantitySpinBox);
715
716 d->unit = unit;
717 d->quantity.setUnit(unit);
718 updateText(d->quantity);
719 }
720
721 void QuantitySpinBox::setUnitText(const QString& str)
722 {
723 try {
724 Base::Quantity quant = Base::Quantity::parse(str.toStdString());
725 setUnit(quant.getUnit());
726 }
727 catch (const Base::ParserError&) {
728 }
729 }
730
731 QString QuantitySpinBox::unitText()
732 {
733 Q_D(QuantitySpinBox);
734 return d->unitStr;
735 }
736
737 double QuantitySpinBox::singleStep() const
738 {
739 Q_D(const QuantitySpinBox);
740 return d->singleStep;
741 }
742
743 void QuantitySpinBox::setSingleStep(double value)
744 {
745 Q_D(QuantitySpinBox);
746
747 if (value >= 0) {
748 d->singleStep = value;
749 }
750 }
751
752 double QuantitySpinBox::minimum() const
753 {
754 Q_D(const QuantitySpinBox);
755 return d->minimum;
756 }
757
758 void QuantitySpinBox::setMinimum(double minimum)
759 {
760 Q_D(QuantitySpinBox);
761 d->minimum = minimum;
762 }
763
764 double QuantitySpinBox::maximum() const
765 {
766 Q_D(const QuantitySpinBox);
767 return d->maximum;
768 }
769
770 void QuantitySpinBox::setMaximum(double maximum)
771 {
772 Q_D(QuantitySpinBox);
773 d->maximum = maximum;
774 }
775
776 void QuantitySpinBox::setRange(double minimum, double maximum)
777 {
778 Q_D(QuantitySpinBox);
779 d->minimum = minimum;
780 d->maximum = maximum;
781 }
782
783 void QuantitySpinBox::checkRangeInExpression(bool on)
784 {
785 Q_D(QuantitySpinBox);
786 d->checkRangeInExpression = on;
787 }
788
789 bool QuantitySpinBox::isCheckedRangeInExpresion() const
790 {
791 Q_D(const QuantitySpinBox);
792 return d->checkRangeInExpression;
793 }
794
795
796 int QuantitySpinBox::decimals() const
797 {
798 Q_D(const QuantitySpinBox);
799 return d->quantity.getFormat().getPrecision();
800 }
801
802 void QuantitySpinBox::setDecimals(int v)
803 {
804 Q_D(QuantitySpinBox);
805 Base::QuantityFormat f = d->quantity.getFormat();
806 f.setPrecision(v);
807 d->quantity.setFormat(f);
808 updateText(d->quantity);
809 }
810
811 void QuantitySpinBox::setSchema(const int s)
812 {
813 Q_D(QuantitySpinBox);
814 d->scheme = Base::UnitsApi::createSchema(s);
815 updateText(d->quantity);
816 }
817
818 void QuantitySpinBox::clearSchema()
819 {
820 Q_D(QuantitySpinBox);
821 d->scheme = nullptr;
822 updateText(d->quantity);
823 }
824
825 QString QuantitySpinBox::getUserString(const Base::Quantity& val, double& factor, QString& unitString) const
826 {
827 Q_D(const QuantitySpinBox);
828 std::string unitStr;
829 const std::string str = d->scheme ? val.getUserString(d->scheme.get(), factor, unitStr)
830 : val.getUserString(factor, unitStr);
831 unitString = QString::fromStdString(unitStr);
832 return QString::fromStdString(str);
833 }
834
835 QString QuantitySpinBox::getUserString(const Base::Quantity& val) const
836 {
837 Q_D(const QuantitySpinBox);
838 std::string str;
839 if (d->scheme) {
840 double factor;
841 std::string unitString;
842 str = val.getUserString(d->scheme.get(), factor, unitString);
843 }
844 else {
845 str = val.getUserString();
846 }
847 return QString::fromStdString(str);
848 }
849
850 void QuantitySpinBox::setExpression(std::shared_ptr<Expression> expr)
851 {
852 ExpressionSpinBox::setExpression(expr);
853 }
854
855 QAbstractSpinBox::StepEnabled QuantitySpinBox::stepEnabled() const
856 {
857 Q_D(const QuantitySpinBox);
858 if (isReadOnly() /* || !d->validInput*/) {
859 return StepNone;
860 }
861 if (wrapping()) {
862 return StepEnabled(StepUpEnabled | StepDownEnabled);
863 }
864 StepEnabled ret = StepNone;
865 if (d->quantity.getValue() < d->maximum) {
866 ret |= StepUpEnabled;
867 }
868 if (d->quantity.getValue() > d->minimum) {
869 ret |= StepDownEnabled;
870 }
871 return ret;
872 }
873
874 void QuantitySpinBox::stepBy(int steps)
875 {
876 Q_D(QuantitySpinBox);
877 updateFromCache(false);
878
879 double step = d->singleStep * steps;
880 double val = d->unitValue + step;
881 if (val > d->maximum) {
882 val = d->maximum;
883 }
884 else if (val < d->minimum) {
885 val = d->minimum;
886 }
887
888 Quantity quant(val, d->unitStr.toStdString());
889 updateText(quant);
890 updateFromCache(true);
891 update();
892 selectNumber();
893 }
894
895 QSize QuantitySpinBox::sizeForText(const QString& txt) const
896 {
897 const QFontMetrics fm(fontMetrics());
898 int h = lineEdit()->sizeHint().height();
899 int w = QtTools::horizontalAdvance(fm, txt);
900
901 w += 2; // cursor blinking space
902 w += iconHeight;
903
904 QStyleOptionSpinBox opt;
905 initStyleOption(&opt);
906 QSize hint(w, h);
907 QSize size = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this);
908 return size;
909 }
910
911 QSize QuantitySpinBox::sizeHint() const
912 {
913 return sizeHintCalculator(lineEdit()->sizeHint().height());
914 }
915
916 QSize QuantitySpinBox::minimumSizeHint() const
917 {
918 return sizeHintCalculator(lineEdit()->minimumSizeHint().height());
919 }
920
921 QSize QuantitySpinBox::sizeHintCalculator(int h) const
922 {
923 Q_D(const QuantitySpinBox);
924 ensurePolished();
925
926 const QFontMetrics fm(fontMetrics());
927 int w = 0;
928 constexpr int maxStrLen = 9;
929
930 QString s;
931 QString fixedContent = QLatin1String(" ");
932
933 Base::Quantity q(d->quantity);
934 q.setValue(d->maximum);
935 s = textFromValue(q);
936 s.truncate(maxStrLen);
937 s += fixedContent;
938 w = qMax(w, QtTools::horizontalAdvance(fm, s));
939
940 w += 2; // cursor blinking space
941 w += iconHeight;
942
943 QStyleOptionSpinBox opt;
944 initStyleOption(&opt);
945 QSize hint(w, h);
946
947 QSize size = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this);
948 return size;
949 }
950
951 void QuantitySpinBox::showEvent(QShowEvent* event)
952 {
953 Q_D(QuantitySpinBox);
954
955 QAbstractSpinBox::showEvent(event);
956
957 bool selected = lineEdit()->hasSelectedText();
958 updateText(d->quantity);
959 if (selected) {
960 selectNumber();
961 }
962 }
963
964 void QuantitySpinBox::hideEvent(QHideEvent* event)
965 {
966 handlePendingEmit();
967 QAbstractSpinBox::hideEvent(event);
968 }
969
970 void QuantitySpinBox::closeEvent(QCloseEvent* event)
971 {
972 handlePendingEmit();
973 QAbstractSpinBox::closeEvent(event);
974 }
975
976 bool QuantitySpinBox::event(QEvent* event)
977 {
978 return QAbstractSpinBox::event(event);
979 }
980
981 void QuantitySpinBox::focusInEvent(QFocusEvent* event)
982 {
983 bool hasSel = lineEdit()->hasSelectedText();
984 QAbstractSpinBox::focusInEvent(event);
985
986 if (event->reason() == Qt::TabFocusReason || event->reason() == Qt::BacktabFocusReason
987 || event->reason() == Qt::ShortcutFocusReason) {
988
989 if (isBound() && getExpression() && lineEdit()->isReadOnly()) {
990 auto helpEvent = new QHelpEvent(
991 QEvent::ToolTip,
992 QPoint(0, rect().height()),
993 mapToGlobal(QPoint(0, rect().height()))
994 );
995 QApplication::postEvent(this, helpEvent);
996 lineEdit()->setSelection(0, 0);
997 }
998 else {
999 if (!hasSel) {
1000 selectNumber();
1001 }
1002 }
1003 }
1004 }
1005
1006 void QuantitySpinBox::focusOutEvent(QFocusEvent* event)
1007 {
1008 Q_D(const QuantitySpinBox);
1009
1010 validateInput();
1011
1012 if (d->normalize) {
1013 normalize();
1014 }
1015
1016 QToolTip::hideText();
1017 QAbstractSpinBox::focusOutEvent(event);
1018 }
1019
1020 void QuantitySpinBox::clear()
1021 {
1022 QAbstractSpinBox::clear();
1023 }
1024
1025 void QuantitySpinBox::selectNumber()
1026 {
1027 QString expr = QStringLiteral("^([%1%2]?[0-9\\%3]*)\\%4?([0-9]+(%5[%1%2]?[0-9]+)?)")
1028 .arg(locale().negativeSign())
1029 .arg(locale().positiveSign())
1030 .arg(locale().groupSeparator())
1031 .arg(locale().decimalPoint())
1032 .arg(locale().exponential());
1033 auto rmatch = QRegularExpression(expr).match(lineEdit()->text());
1034 if (rmatch.hasMatch()) {
1035 lineEdit()->setSelection(0, rmatch.capturedLength());
1036 }
1037 }
1038
1039 QString QuantitySpinBox::textFromValue(const Base::Quantity& value) const
1040 {
1041 QString str = getUserString(value);
1042 if (qAbs(value.getValue()) >= 1000.0) {
1043 str.remove(locale().groupSeparator());
1044 }
1045 return str;
1046 }
1047
1048 Base::Quantity QuantitySpinBox::valueFromText(const QString& text) const
1049 {
1050 Q_D(const QuantitySpinBox);
1051
1052 QString copy = text;
1053 QValidator::State state = QValidator::Acceptable;
1054 const App::ObjectIdentifier& path = getPath();
1055 Base::Quantity quant = d->validateAndInterpret(copy, state, path);
1056 if (state != QValidator::Acceptable) {
1057 fixup(copy);
1058 quant = d->validateAndInterpret(copy, state, path);
1059 }
1060
1061 return quant;
1062 }
1063
1064 QValidator::State QuantitySpinBox::validate(QString& text, int& pos) const
1065 {
1066 Q_D(const QuantitySpinBox);
1067 Q_UNUSED(pos)
1068
1069 QValidator::State state;
1070 const App::ObjectIdentifier& path = getPath();
1071 d->validateAndInterpret(text, state, path);
1072 return state;
1073 }
1074
1075 void QuantitySpinBox::fixup(QString& input) const
1076 {
1077 input.remove(locale().groupSeparator());
1078 }
1079
1080
1081 #include "moc_QuantitySpinBox.cpp"
1082 #include "moc_QuantitySpinBox_p.cpp"