From e8ac7ead0613a2b06827f85e3a0330fd1c297f07 Mon Sep 17 00:00:00 2001 From: Leandro Melo <leandro.melo@nokia.com> Date: Thu, 29 Jul 2010 11:20:06 +0200 Subject: [PATCH] Make QML color validation code reusable. Reviewed-by: ckamm --- src/libs/qmljs/qmljscheck.cpp | 39 +++++++++++++++++++---------------- src/libs/qmljs/qmljscheck.h | 3 +++ 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/src/libs/qmljs/qmljscheck.cpp b/src/libs/qmljs/qmljscheck.cpp index 8d4e00ff8bb..7a1f7e3bf04 100644 --- a/src/libs/qmljs/qmljscheck.cpp +++ b/src/libs/qmljs/qmljscheck.cpp @@ -41,6 +41,26 @@ using namespace QmlJS; using namespace QmlJS::AST; using namespace QmlJS::Interpreter; +QColor QmlJS::toQColor(const QString &qmlColorString) +{ + QColor color; + if (qmlColorString.size() == 9 && qmlColorString.at(0) == QLatin1Char('#')) { + bool ok; + const int alpha = qmlColorString.mid(1, 2).toInt(&ok, 16); + if (ok) { + QString name(qmlColorString.at(0)); + name.append(qmlColorString.right(6)); + if (QColor::isValidColor(name)) { + color.setNamedColor(name); + color.setAlpha(alpha); + } + } + } else { + if (QColor::isValidColor(qmlColorString)) + color.setNamedColor(qmlColorString); + } + return color; +} namespace { @@ -113,24 +133,7 @@ public: virtual void visit(const ColorValue *) { if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) { - const QString colorString = stringLiteral->value->asString(); - - bool ok = true; - if (colorString.size() == 9 && colorString.at(0) == QLatin1Char('#')) { - // #rgba - for (int i = 1; i < 9; ++i) { - const QChar c = colorString.at(i); - if ((c >= QLatin1Char('0') && c <= QLatin1Char('9')) - || (c >= QLatin1Char('a') && c <= QLatin1Char('f')) - || (c >= QLatin1Char('A') && c <= QLatin1Char('F'))) - continue; - ok = false; - break; - } - } else { - ok = QColor::isValidColor(colorString); - } - if (!ok) + if (!toQColor(stringLiteral->value->asString()).isValid()) _message.message = Check::tr("not a valid color"); } else { visit((StringValue *)0); diff --git a/src/libs/qmljs/qmljscheck.h b/src/libs/qmljs/qmljscheck.h index d7c7e930a02..a6fddba361f 100644 --- a/src/libs/qmljs/qmljscheck.h +++ b/src/libs/qmljs/qmljscheck.h @@ -37,6 +37,7 @@ #include <qmljs/parser/qmljsastvisitor_p.h> #include <QtCore/QCoreApplication> +#include <QtGui/QColor> namespace QmlJS { @@ -80,6 +81,8 @@ private: bool _ignoreTypeErrors; }; +QMLJS_EXPORT QColor toQColor(const QString &qmlColorString); + } // namespace QmlJS #endif // QMLJSCHECK_H -- GitLab