Skip to content

Commit

Permalink
ScriptManager: Replaced QTextCodec with QStringConverter
Browse files Browse the repository at this point in the history
Also adjusted another use of the removed QString::splitRef.
  • Loading branch information
bjorn committed Oct 12, 2020
1 parent 83ee9ab commit 272936f
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/tiled/scriptmanager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@
#include <QFile>
#include <QQmlEngine>
#include <QStandardPaths>
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
#include <QTextCodec>
#endif
#include <QtDebug>
#include <QCoreApplication>

Expand Down Expand Up @@ -151,13 +153,15 @@ QJSValue ScriptManager::evaluate(const QString &program,
return result;
}

#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
static bool fromUtf8(const QByteArray &bytes, QString &unicode)
{
QTextCodec::ConverterState state;
const QTextCodec *codec = QTextCodec::codecForName("UTF-8");
unicode = codec->toUnicode(bytes.constData(), bytes.size(), &state);
return state.invalidChars == 0;
}
#endif

QJSValue ScriptManager::evaluateFile(const QString &fileName)
{
Expand All @@ -170,8 +174,18 @@ QJSValue ScriptManager::evaluateFile(const QString &fileName)

const QByteArray bytes = file.readAll();
QString script;
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
if (!fromUtf8(bytes, script))
script = QTextCodec::codecForUtfText(bytes)->toUnicode(bytes);
#else
auto encoding = QStringConverter::encodingForData(bytes.constData(), bytes.size());
QStringDecoder decoder(encoding.value_or(QStringConverter::Encoding::Utf8));
script = decoder.decode(bytes);
if (decoder.hasError()) {
Tiled::ERROR(tr("Error decoding file: %1").arg(fileName));
return QJSValue();
}
#endif

Tiled::INFO(tr("Evaluating '%1'").arg(fileName));
return evaluate(script, fileName);
Expand Down Expand Up @@ -228,7 +242,11 @@ bool ScriptManager::checkError(QJSValue value, const QString &program)
QString errorString = value.toString();
QString stack = value.property(QStringLiteral("stack")).toString();

#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
const auto stackEntries = QStringView(stack).split(QLatin1Char('\n'));
#else
const auto stackEntries = stack.splitRef(QLatin1Char('\n'));
#endif
if (stackEntries.size() > 0 && !stackEntries.first().startsWith(QLatin1String("%entry@"))) {
// Add stack if there were more than one entries
errorString.append(QLatin1Char('\n'));
Expand Down

0 comments on commit 272936f

Please sign in to comment.