File indexing completed on 2024-05-12 16:43:57

0001 /*
0002     SPDX-FileCopyrightText: 2019 Thomas Baumgart <tbaumgart@kde.org>
0003     SPDX-License-Identifier: GPL-2.0-or-later
0004 */
0005 
0006 #include "amountvalidator.h"
0007 #include <cmath>
0008 
0009 // ----------------------------------------------------------------------------
0010 // QT Includes
0011 
0012 // ----------------------------------------------------------------------------
0013 // KDE Includes
0014 
0015 // ----------------------------------------------------------------------------
0016 // Project Includes
0017 
0018 #include "platformtools.h"
0019 
0020 AmountValidator::AmountValidator(QObject * parent) :
0021     AmountValidator(-HUGE_VAL, HUGE_VAL, 1000, parent)
0022 {
0023 }
0024 
0025 AmountValidator::AmountValidator(double bottom, double top, int decimals,
0026                                  QObject * parent) :
0027     QDoubleValidator(bottom, top, decimals, parent)
0028 {
0029     setNotation(StandardNotation);
0030 }
0031 
0032 QValidator::State AmountValidator::validate(QString& input, int& pos) const
0033 {
0034     const auto openParen = QStringLiteral("(");
0035     const auto closeParen = QStringLiteral(")");
0036 
0037     if ((platformTools::currencySignPosition(true) == platformTools::ParensAround)
0038         || (platformTools::currencySignPosition(false) == platformTools::ParensAround)) {
0039         const auto openCount = input.count(openParen);
0040         const auto closeCount = input.count(closeParen);
0041 
0042         // if we don't have any, use the normal validator
0043         if ((openCount == 0) && (closeCount == 0)) {
0044             return QDoubleValidator::validate(input, pos);
0045         }
0046         // more than one open and close paren is invalid
0047         if ((openCount > 1) || (closeCount > 1)) {
0048             return Invalid;
0049         }
0050         // close paren w/o open paren is invalid
0051         if (openCount < closeCount) {
0052             return Invalid;
0053         }
0054         // make sure open paren is first char
0055         if (openCount == 1 && !input.startsWith(openParen)) {
0056             return Invalid;
0057         }
0058         // make sure close paren is last char
0059         if (closeCount == 1 && !input.endsWith(closeParen)) {
0060             return Invalid;
0061         }
0062         // open and close paren count differs
0063         if (openCount != closeCount) {
0064             return Intermediate;
0065         }
0066 
0067         // remove the open and close paren and check the remainder
0068         auto modifiedInput(input);
0069         modifiedInput.remove(openParen);
0070         modifiedInput.remove(closeParen);
0071         return QDoubleValidator::validate(modifiedInput, pos);
0072     }
0073     return QDoubleValidator::validate(input, pos);
0074 }