Use QString literals

This patch covers src/app and src/base folders.
Follow up of ab64ee872b.
This commit is contained in:
Chocobo1 2022-03-04 14:24:14 +08:00
parent ab64ee872b
commit f0dd7b7dae
No known key found for this signature in database
GPG key ID: 210D9C873253A68C
38 changed files with 771 additions and 764 deletions

View file

@ -136,10 +136,10 @@ Application::Application(int &argc, char **argv)
qRegisterMetaType<Log::Msg>("Log::Msg"); qRegisterMetaType<Log::Msg>("Log::Msg");
qRegisterMetaType<Log::Peer>("Log::Peer"); qRegisterMetaType<Log::Peer>("Log::Peer");
setApplicationName("qBittorrent"); setApplicationName(u"qBittorrent"_qs);
setOrganizationDomain("qbittorrent.org"); setOrganizationDomain(u"qbittorrent.org"_qs);
#if !defined(DISABLE_GUI) #if !defined(DISABLE_GUI)
setDesktopFileName("org.qbittorrent.qBittorrent"); setDesktopFileName(u"org.qbittorrent.qBittorrent"_qs);
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
setAttribute(Qt::AA_UseHighDpiPixmaps, true); // opt-in to the high DPI pixmap support setAttribute(Qt::AA_UseHighDpiPixmaps, true); // opt-in to the high DPI pixmap support
#endif #endif
@ -176,12 +176,12 @@ Application::Application(int &argc, char **argv)
if (isFileLoggerEnabled()) if (isFileLoggerEnabled())
m_fileLogger = new FileLogger(fileLoggerPath(), isFileLoggerBackup(), fileLoggerMaxSize(), isFileLoggerDeleteOld(), fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType())); m_fileLogger = new FileLogger(fileLoggerPath(), isFileLoggerBackup(), fileLoggerMaxSize(), isFileLoggerDeleteOld(), fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType()));
Logger::instance()->addMessage(tr("qBittorrent %1 started", "qBittorrent v3.2.0alpha started").arg(QBT_VERSION)); Logger::instance()->addMessage(tr("qBittorrent %1 started", "qBittorrent v3.2.0alpha started").arg(QStringLiteral(QBT_VERSION)));
if (portableModeEnabled) if (portableModeEnabled)
{ {
Logger::instance()->addMessage(tr("Running in portable mode. Auto detected profile folder at: %1").arg(profileDir.toString())); Logger::instance()->addMessage(tr("Running in portable mode. Auto detected profile folder at: %1").arg(profileDir.toString()));
if (m_commandLineArgs.relativeFastresumePaths) if (m_commandLineArgs.relativeFastresumePaths)
Logger::instance()->addMessage(tr("Redundant command line flag detected: \"%1\". Portable mode implies relative fastresume.").arg("--relative-fastresume"), Log::WARNING); // to avoid translating the `--relative-fastresume` string Logger::instance()->addMessage(tr("Redundant command line flag detected: \"%1\". Portable mode implies relative fastresume.").arg(u"--relative-fastresume"_qs), Log::WARNING); // to avoid translating the `--relative-fastresume` string
} }
else else
{ {
@ -457,12 +457,12 @@ void Application::runExternalProgram(const BitTorrent::Torrent *torrent) const
void Application::sendNotificationEmail(const BitTorrent::Torrent *torrent) void Application::sendNotificationEmail(const BitTorrent::Torrent *torrent)
{ {
// Prepare mail content // Prepare mail content
const QString content = tr("Torrent name: %1").arg(torrent->name()) + '\n' const QString content = tr("Torrent name: %1").arg(torrent->name()) + u'\n'
+ tr("Torrent size: %1").arg(Utils::Misc::friendlyUnit(torrent->wantedSize())) + '\n' + tr("Torrent size: %1").arg(Utils::Misc::friendlyUnit(torrent->wantedSize())) + u'\n'
+ tr("Save path: %1").arg(torrent->savePath().toString()) + "\n\n" + tr("Save path: %1").arg(torrent->savePath().toString()) + u"\n\n"
+ tr("The torrent was downloaded in %1.", "The torrent was downloaded in 1 hour and 20 seconds") + tr("The torrent was downloaded in %1.", "The torrent was downloaded in 1 hour and 20 seconds")
.arg(Utils::Misc::userFriendlyDuration(torrent->activeTime())) + "\n\n\n" .arg(Utils::Misc::userFriendlyDuration(torrent->activeTime())) + u"\n\n\n"
+ tr("Thank you for using qBittorrent.") + '\n'; + tr("Thank you for using qBittorrent.") + u'\n';
// Send the notification email // Send the notification email
const Preferences *pref = Preferences::instance(); const Preferences *pref = Preferences::instance();
@ -755,7 +755,7 @@ void Application::initializeTranslation()
installTranslator(&m_translator); installTranslator(&m_translator);
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
if (localeStr.startsWith("ar") || localeStr.startsWith("he")) if (localeStr.startsWith(u"ar") || localeStr.startsWith(u"he"))
{ {
qDebug("Right to Left mode"); qDebug("Right to Left mode");
setLayoutDirection(Qt::RightToLeft); setLayoutDirection(Qt::RightToLeft);

View file

@ -89,10 +89,10 @@ namespace
public: public:
static QString padUsageText(const QString &usage) static QString padUsageText(const QString &usage)
{ {
QString res = QString(USAGE_INDENTATION, ' ') + usage; QString res = QString(USAGE_INDENTATION, u' ') + usage;
if ((USAGE_TEXT_COLUMN - usage.length() - 4) > 0) if ((USAGE_TEXT_COLUMN - usage.length() - 4) > 0)
return res + QString(USAGE_TEXT_COLUMN - usage.length() - 4, ' '); return res + QString((USAGE_TEXT_COLUMN - usage.length() - 4), u' ');
return res; return res;
} }
@ -284,7 +284,7 @@ namespace
std::optional<bool> value(const QProcessEnvironment &env) const std::optional<bool> value(const QProcessEnvironment &env) const
{ {
const QString val = env.value(envVarName(), "-1"); const QString val = env.value(envVarName(), u"-1"_qs);
if (val.isEmpty()) if (val.isEmpty())
{ {
@ -404,8 +404,8 @@ QBtCommandLineParameters parseCommandLine(const QStringList &args)
{ {
const QString &arg = args[i]; const QString &arg = args[i];
if ((arg.startsWith("--") && !arg.endsWith(".torrent")) if ((arg.startsWith(u"--") && !arg.endsWith(u".torrent"))
|| (arg.startsWith('-') && (arg.size() == 2))) || (arg.startsWith(u'-') && (arg.size() == 2)))
{ {
// Parse known parameters // Parse known parameters
if (arg == SHOW_HELP_OPTION) if (arg == SHOW_HELP_OPTION)
@ -500,7 +500,7 @@ QBtCommandLineParameters parseCommandLine(const QStringList &args)
QString wrapText(const QString &text, int initialIndentation = USAGE_TEXT_COLUMN, int wrapAtColumn = WRAP_AT_COLUMN) QString wrapText(const QString &text, int initialIndentation = USAGE_TEXT_COLUMN, int wrapAtColumn = WRAP_AT_COLUMN)
{ {
QStringList words = text.split(' '); QStringList words = text.split(u' ');
QStringList lines = {words.first()}; QStringList lines = {words.first()};
int currentLineMaxLength = wrapAtColumn - initialIndentation; int currentLineMaxLength = wrapAtColumn - initialIndentation;
@ -508,23 +508,23 @@ QString wrapText(const QString &text, int initialIndentation = USAGE_TEXT_COLUMN
{ {
if (lines.last().length() + word.length() + 1 < currentLineMaxLength) if (lines.last().length() + word.length() + 1 < currentLineMaxLength)
{ {
lines.last().append(' ' + word); lines.last().append(u' ' + word);
} }
else else
{ {
lines.append(QString(initialIndentation, ' ') + word); lines.append(QString(initialIndentation, u' ') + word);
currentLineMaxLength = wrapAtColumn; currentLineMaxLength = wrapAtColumn;
} }
} }
return lines.join('\n'); return lines.join(u'\n');
} }
QString makeUsage(const QString &prgName) QString makeUsage(const QString &prgName)
{ {
QString text; QString text;
QTextStream stream(&text, QIODevice::WriteOnly); QTextStream stream(&text, QIODevice::WriteOnly);
QString indentation = QString(USAGE_INDENTATION, ' '); QString indentation = QString(USAGE_INDENTATION, u' ');
stream << QObject::tr("Usage:") << '\n' stream << QObject::tr("Usage:") << '\n'
<< indentation << prgName << QLatin1String(" [options] [(<filename> | <url>)...]") << '\n' << indentation << prgName << QLatin1String(" [options] [(<filename> | <url>)...]") << '\n'

View file

@ -89,7 +89,7 @@ void FileLogger::deleteOld(const int age, const FileLogAgeType ageType)
{ {
const QDateTime date = QDateTime::currentDateTime(); const QDateTime date = QDateTime::currentDateTime();
const QDir dir {m_path.parentPath().data()}; const QDir dir {m_path.parentPath().data()};
const QFileInfoList fileList = dir.entryInfoList(QStringList("qbittorrent.log.bak*") const QFileInfoList fileList = dir.entryInfoList(QStringList(u"qbittorrent.log.bak*"_qs)
, (QDir::Files | QDir::Writable), (QDir::Time | QDir::Reversed)); , (QDir::Files | QDir::Writable), (QDir::Time | QDir::Reversed));
for (const QFileInfo &file : fileList) for (const QFileInfo &file : fileList)

View file

@ -76,6 +76,7 @@ Q_IMPORT_PLUGIN(QICOPlugin)
#endif // Q_OS_UNIX #endif // Q_OS_UNIX
#endif //STACKTRACE #endif //STACKTRACE
#include "base/global.h"
#include "base/preferences.h" #include "base/preferences.h"
#include "base/profile.h" #include "base/profile.h"
#include "base/version.h" #include "base/version.h"
@ -171,7 +172,7 @@ int main(int argc, char *argv[])
{ {
if (isOneArg) if (isOneArg)
{ {
displayUsage(argv[0]); displayUsage(QString::fromLocal8Bit(argv[0]));
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
throw CommandLineParameterError(QObject::tr("%1 must be the single command line parameter.") throw CommandLineParameterError(QObject::tr("%1 must be the single command line parameter.")
@ -377,11 +378,11 @@ void sigAbnormalHandler(int signum)
#if !defined(DISABLE_GUI) #if !defined(DISABLE_GUI)
void showSplashScreen() void showSplashScreen()
{ {
QPixmap splashImg(":/icons/splash.png"); QPixmap splashImg(u":/icons/splash.png"_qs);
QPainter painter(&splashImg); QPainter painter(&splashImg);
const QString version = QBT_VERSION; const auto version = QStringLiteral(QBT_VERSION);
painter.setPen(QPen(Qt::white)); painter.setPen(QPen(Qt::white));
painter.setFont(QFont("Arial", 22, QFont::Black)); painter.setFont(QFont(u"Arial"_qs, 22, QFont::Black));
painter.drawText(224 - painter.fontMetrics().horizontalAdvance(version), 270, version); painter.drawText(224 - painter.fontMetrics().horizontalAdvance(version), 270, version);
QSplashScreen *splash = new QSplashScreen(splashImg); QSplashScreen *splash = new QSplashScreen(splashImg);
splash->show(); splash->show();
@ -405,9 +406,9 @@ void displayBadArgMessage(const QString &message)
msgBox.move(Utils::Gui::screenCenter(&msgBox)); msgBox.move(Utils::Gui::screenCenter(&msgBox));
msgBox.exec(); msgBox.exec();
#else #else
const QString errMsg = QObject::tr("Bad command line: ") + '\n' const QString errMsg = QObject::tr("Bad command line: ") + u'\n'
+ message + '\n' + message + u'\n'
+ help + '\n'; + help + u'\n';
fprintf(stderr, "%s", qUtf8Printable(errMsg)); fprintf(stderr, "%s", qUtf8Printable(errMsg));
#endif #endif
} }

View file

@ -241,80 +241,80 @@ namespace
const KeyMapping mappings[] = const KeyMapping mappings[] =
{ {
{"AddNewTorrentDialog/Enabled", "Preferences/Downloads/NewAdditionDialog"}, {u"AddNewTorrentDialog/Enabled"_qs, u"Preferences/Downloads/NewAdditionDialog"_qs},
{"AddNewTorrentDialog/Expanded", "AddNewTorrentDialog/expanded"}, {u"AddNewTorrentDialog/Expanded"_qs, u"AddNewTorrentDialog/expanded"_qs},
{"AddNewTorrentDialog/Position", "AddNewTorrentDialog/y"}, {u"AddNewTorrentDialog/Position"_qs, u"AddNewTorrentDialog/y"_qs},
{"AddNewTorrentDialog/SavePathHistory", "TorrentAdditionDlg/save_path_history"}, {u"AddNewTorrentDialog/SavePathHistory"_qs, u"TorrentAdditionDlg/save_path_history"_qs},
{"AddNewTorrentDialog/TopLevel", "Preferences/Downloads/NewAdditionDialogFront"}, {u"AddNewTorrentDialog/TopLevel"_qs, u"Preferences/Downloads/NewAdditionDialogFront"_qs},
{"AddNewTorrentDialog/TreeHeaderState", "AddNewTorrentDialog/qt5/treeHeaderState"}, {u"AddNewTorrentDialog/TreeHeaderState"_qs, u"AddNewTorrentDialog/qt5/treeHeaderState"_qs},
{"AddNewTorrentDialog/Width", "AddNewTorrentDialog/width"}, {u"AddNewTorrentDialog/Width"_qs, u"AddNewTorrentDialog/width"_qs},
{"BitTorrent/Session/AddExtensionToIncompleteFiles", "Preferences/Downloads/UseIncompleteExtension"}, {u"BitTorrent/Session/AddExtensionToIncompleteFiles"_qs, u"Preferences/Downloads/UseIncompleteExtension"_qs},
{"BitTorrent/Session/AdditionalTrackers", "Preferences/Bittorrent/TrackersList"}, {u"BitTorrent/Session/AdditionalTrackers"_qs, u"Preferences/Bittorrent/TrackersList"_qs},
{"BitTorrent/Session/AddTorrentPaused", "Preferences/Downloads/StartInPause"}, {u"BitTorrent/Session/AddTorrentPaused"_qs, u"Preferences/Downloads/StartInPause"_qs},
{"BitTorrent/Session/AddTrackersEnabled", "Preferences/Bittorrent/AddTrackers"}, {u"BitTorrent/Session/AddTrackersEnabled"_qs, u"Preferences/Bittorrent/AddTrackers"_qs},
{"BitTorrent/Session/AlternativeGlobalDLSpeedLimit", "Preferences/Connection/GlobalDLLimitAlt"}, {u"BitTorrent/Session/AlternativeGlobalDLSpeedLimit"_qs, u"Preferences/Connection/GlobalDLLimitAlt"_qs},
{"BitTorrent/Session/AlternativeGlobalUPSpeedLimit", "Preferences/Connection/GlobalUPLimitAlt"}, {u"BitTorrent/Session/AlternativeGlobalUPSpeedLimit"_qs, u"Preferences/Connection/GlobalUPLimitAlt"_qs},
{"BitTorrent/Session/AnnounceIP", "Preferences/Connection/InetAddress"}, {u"BitTorrent/Session/AnnounceIP"_qs, u"Preferences/Connection/InetAddress"_qs},
{"BitTorrent/Session/AnnounceToAllTrackers", "Preferences/Advanced/AnnounceToAllTrackers"}, {u"BitTorrent/Session/AnnounceToAllTrackers"_qs, u"Preferences/Advanced/AnnounceToAllTrackers"_qs},
{"BitTorrent/Session/AnonymousModeEnabled", "Preferences/Advanced/AnonymousMode"}, {u"BitTorrent/Session/AnonymousModeEnabled"_qs, u"Preferences/Advanced/AnonymousMode"_qs},
{"BitTorrent/Session/BandwidthSchedulerEnabled", "Preferences/Scheduler/Enabled"}, {u"BitTorrent/Session/BandwidthSchedulerEnabled"_qs, u"Preferences/Scheduler/Enabled"_qs},
{"BitTorrent/Session/DefaultSavePath", "Preferences/Downloads/SavePath"}, {u"BitTorrent/Session/DefaultSavePath"_qs, u"Preferences/Downloads/SavePath"_qs},
{"BitTorrent/Session/DHTEnabled", "Preferences/Bittorrent/DHT"}, {u"BitTorrent/Session/DHTEnabled"_qs, u"Preferences/Bittorrent/DHT"_qs},
{"BitTorrent/Session/DiskCacheSize", "Preferences/Downloads/DiskWriteCacheSize"}, {u"BitTorrent/Session/DiskCacheSize"_qs, u"Preferences/Downloads/DiskWriteCacheSize"_qs},
{"BitTorrent/Session/DiskCacheTTL", "Preferences/Downloads/DiskWriteCacheTTL"}, {u"BitTorrent/Session/DiskCacheTTL"_qs, u"Preferences/Downloads/DiskWriteCacheTTL"_qs},
{"BitTorrent/Session/Encryption", "Preferences/Bittorrent/Encryption"}, {u"BitTorrent/Session/Encryption"_qs, u"Preferences/Bittorrent/Encryption"_qs},
{"BitTorrent/Session/FinishedTorrentExportDirectory", "Preferences/Downloads/FinishedTorrentExportDir"}, {u"BitTorrent/Session/FinishedTorrentExportDirectory"_qs, u"Preferences/Downloads/FinishedTorrentExportDir"_qs},
{"BitTorrent/Session/ForceProxy", "Preferences/Connection/ProxyForce"}, {u"BitTorrent/Session/ForceProxy"_qs, u"Preferences/Connection/ProxyForce"_qs},
{"BitTorrent/Session/GlobalDLSpeedLimit", "Preferences/Connection/GlobalDLLimit"}, {u"BitTorrent/Session/GlobalDLSpeedLimit"_qs, u"Preferences/Connection/GlobalDLLimit"_qs},
{"BitTorrent/Session/GlobalMaxRatio", "Preferences/Bittorrent/MaxRatio"}, {u"BitTorrent/Session/GlobalMaxRatio"_qs, u"Preferences/Bittorrent/MaxRatio"_qs},
{"BitTorrent/Session/GlobalUPSpeedLimit", "Preferences/Connection/GlobalUPLimit"}, {u"BitTorrent/Session/GlobalUPSpeedLimit"_qs, u"Preferences/Connection/GlobalUPLimit"_qs},
{"BitTorrent/Session/IgnoreLimitsOnLAN", "Preferences/Advanced/IgnoreLimitsLAN"}, {u"BitTorrent/Session/IgnoreLimitsOnLAN"_qs, u"Preferences/Advanced/IgnoreLimitsLAN"_qs},
{"BitTorrent/Session/IgnoreSlowTorrentsForQueueing", "Preferences/Queueing/IgnoreSlowTorrents"}, {u"BitTorrent/Session/IgnoreSlowTorrentsForQueueing"_qs, u"Preferences/Queueing/IgnoreSlowTorrents"_qs},
{"BitTorrent/Session/IncludeOverheadInLimits", "Preferences/Advanced/IncludeOverhead"}, {u"BitTorrent/Session/IncludeOverheadInLimits"_qs, u"Preferences/Advanced/IncludeOverhead"_qs},
{"BitTorrent/Session/Interface", "Preferences/Connection/Interface"}, {u"BitTorrent/Session/Interface"_qs, u"Preferences/Connection/Interface"_qs},
{"BitTorrent/Session/InterfaceAddress", "Preferences/Connection/InterfaceAddress"}, {u"BitTorrent/Session/InterfaceAddress"_qs, u"Preferences/Connection/InterfaceAddress"_qs},
{"BitTorrent/Session/InterfaceName", "Preferences/Connection/InterfaceName"}, {u"BitTorrent/Session/InterfaceName"_qs, u"Preferences/Connection/InterfaceName"_qs},
{"BitTorrent/Session/IPFilter", "Preferences/IPFilter/File"}, {u"BitTorrent/Session/IPFilter"_qs, u"Preferences/IPFilter/File"_qs},
{"BitTorrent/Session/IPFilteringEnabled", "Preferences/IPFilter/Enabled"}, {u"BitTorrent/Session/IPFilteringEnabled"_qs, u"Preferences/IPFilter/Enabled"_qs},
{"BitTorrent/Session/LSDEnabled", "Preferences/Bittorrent/LSD"}, {u"BitTorrent/Session/LSDEnabled"_qs, u"Preferences/Bittorrent/LSD"_qs},
{"BitTorrent/Session/MaxActiveDownloads", "Preferences/Queueing/MaxActiveDownloads"}, {u"BitTorrent/Session/MaxActiveDownloads"_qs, u"Preferences/Queueing/MaxActiveDownloads"_qs},
{"BitTorrent/Session/MaxActiveTorrents", "Preferences/Queueing/MaxActiveTorrents"}, {u"BitTorrent/Session/MaxActiveTorrents"_qs, u"Preferences/Queueing/MaxActiveTorrents"_qs},
{"BitTorrent/Session/MaxActiveUploads", "Preferences/Queueing/MaxActiveUploads"}, {u"BitTorrent/Session/MaxActiveUploads"_qs, u"Preferences/Queueing/MaxActiveUploads"_qs},
{"BitTorrent/Session/MaxConnections", "Preferences/Bittorrent/MaxConnecs"}, {u"BitTorrent/Session/MaxConnections"_qs, u"Preferences/Bittorrent/MaxConnecs"_qs},
{"BitTorrent/Session/MaxConnectionsPerTorrent", "Preferences/Bittorrent/MaxConnecsPerTorrent"}, {u"BitTorrent/Session/MaxConnectionsPerTorrent"_qs, u"Preferences/Bittorrent/MaxConnecsPerTorrent"_qs},
{"BitTorrent/Session/MaxHalfOpenConnections", "Preferences/Connection/MaxHalfOpenConnec"}, {u"BitTorrent/Session/MaxHalfOpenConnections"_qs, u"Preferences/Connection/MaxHalfOpenConnec"_qs},
{"BitTorrent/Session/MaxRatioAction", "Preferences/Bittorrent/MaxRatioAction"}, {u"BitTorrent/Session/MaxRatioAction"_qs, u"Preferences/Bittorrent/MaxRatioAction"_qs},
{"BitTorrent/Session/MaxUploads", "Preferences/Bittorrent/MaxUploads"}, {u"BitTorrent/Session/MaxUploads"_qs, u"Preferences/Bittorrent/MaxUploads"_qs},
{"BitTorrent/Session/MaxUploadsPerTorrent", "Preferences/Bittorrent/MaxUploadsPerTorrent"}, {u"BitTorrent/Session/MaxUploadsPerTorrent"_qs, u"Preferences/Bittorrent/MaxUploadsPerTorrent"_qs},
{"BitTorrent/Session/OutgoingPortsMax", "Preferences/Advanced/OutgoingPortsMax"}, {u"BitTorrent/Session/OutgoingPortsMax"_qs, u"Preferences/Advanced/OutgoingPortsMax"_qs},
{"BitTorrent/Session/OutgoingPortsMin", "Preferences/Advanced/OutgoingPortsMin"}, {u"BitTorrent/Session/OutgoingPortsMin"_qs, u"Preferences/Advanced/OutgoingPortsMin"_qs},
{"BitTorrent/Session/PeXEnabled", "Preferences/Bittorrent/PeX"}, {u"BitTorrent/Session/PeXEnabled"_qs, u"Preferences/Bittorrent/PeX"_qs},
{"BitTorrent/Session/Port", "Preferences/Connection/PortRangeMin"}, {u"BitTorrent/Session/Port"_qs, u"Preferences/Connection/PortRangeMin"_qs},
{"BitTorrent/Session/Preallocation", "Preferences/Downloads/PreAllocation"}, {u"BitTorrent/Session/Preallocation"_qs, u"Preferences/Downloads/PreAllocation"_qs},
{"BitTorrent/Session/ProxyPeerConnections", "Preferences/Connection/ProxyPeerConnections"}, {u"BitTorrent/Session/ProxyPeerConnections"_qs, u"Preferences/Connection/ProxyPeerConnections"_qs},
{"BitTorrent/Session/QueueingSystemEnabled", "Preferences/Queueing/QueueingEnabled"}, {u"BitTorrent/Session/QueueingSystemEnabled"_qs, u"Preferences/Queueing/QueueingEnabled"_qs},
{"BitTorrent/Session/RefreshInterval", "Preferences/General/RefreshInterval"}, {u"BitTorrent/Session/RefreshInterval"_qs, u"Preferences/General/RefreshInterval"_qs},
{"BitTorrent/Session/SaveResumeDataInterval", "Preferences/Downloads/SaveResumeDataInterval"}, {u"BitTorrent/Session/SaveResumeDataInterval"_qs, u"Preferences/Downloads/SaveResumeDataInterval"_qs},
{"BitTorrent/Session/SuperSeedingEnabled", "Preferences/Advanced/SuperSeeding"}, {u"BitTorrent/Session/SuperSeedingEnabled"_qs, u"Preferences/Advanced/SuperSeeding"_qs},
{"BitTorrent/Session/TempPath", "Preferences/Downloads/TempPath"}, {u"BitTorrent/Session/TempPath"_qs, u"Preferences/Downloads/TempPath"_qs},
{"BitTorrent/Session/TempPathEnabled", "Preferences/Downloads/TempPathEnabled"}, {u"BitTorrent/Session/TempPathEnabled"_qs, u"Preferences/Downloads/TempPathEnabled"_qs},
{"BitTorrent/Session/TorrentExportDirectory", "Preferences/Downloads/TorrentExportDir"}, {u"BitTorrent/Session/TorrentExportDirectory"_qs, u"Preferences/Downloads/TorrentExportDir"_qs},
{"BitTorrent/Session/TrackerFilteringEnabled", "Preferences/IPFilter/FilterTracker"}, {u"BitTorrent/Session/TrackerFilteringEnabled"_qs, u"Preferences/IPFilter/FilterTracker"_qs},
{"BitTorrent/Session/UseAlternativeGlobalSpeedLimit", "Preferences/Connection/alt_speeds_on"}, {u"BitTorrent/Session/UseAlternativeGlobalSpeedLimit"_qs, u"Preferences/Connection/alt_speeds_on"_qs},
{"BitTorrent/Session/UseOSCache", "Preferences/Advanced/osCache"}, {u"BitTorrent/Session/UseOSCache"_qs, u"Preferences/Advanced/osCache"_qs},
{"BitTorrent/Session/UseRandomPort", "Preferences/General/UseRandomPort"}, {u"BitTorrent/Session/UseRandomPort"_qs, u"Preferences/General/UseRandomPort"_qs},
{"BitTorrent/Session/uTPEnabled", "Preferences/Bittorrent/uTP"}, {u"BitTorrent/Session/uTPEnabled"_qs, u"Preferences/Bittorrent/uTP"_qs},
{"BitTorrent/Session/uTPRateLimited", "Preferences/Bittorrent/uTP_rate_limited"}, {u"BitTorrent/Session/uTPRateLimited"_qs, u"Preferences/Bittorrent/uTP_rate_limited"_qs},
{"BitTorrent/TrackerEnabled", "Preferences/Advanced/trackerEnabled"}, {u"BitTorrent/TrackerEnabled"_qs, u"Preferences/Advanced/trackerEnabled"_qs},
{"Network/PortForwardingEnabled", "Preferences/Connection/UPnP"}, {u"Network/PortForwardingEnabled"_qs, u"Preferences/Connection/UPnP"_qs},
{"Network/Proxy/Authentication", "Preferences/Connection/Proxy/Authentication"}, {u"Network/Proxy/Authentication"_qs, u"Preferences/Connection/Proxy/Authentication"_qs},
{"Network/Proxy/IP", "Preferences/Connection/Proxy/IP"}, {u"Network/Proxy/IP"_qs, u"Preferences/Connection/Proxy/IP"_qs},
{"Network/Proxy/OnlyForTorrents", "Preferences/Connection/ProxyOnlyForTorrents"}, {u"Network/Proxy/OnlyForTorrents"_qs, u"Preferences/Connection/ProxyOnlyForTorrents"_qs},
{"Network/Proxy/Password", "Preferences/Connection/Proxy/Password"}, {u"Network/Proxy/Password"_qs, u"Preferences/Connection/Proxy/Password"_qs},
{"Network/Proxy/Port", "Preferences/Connection/Proxy/Port"}, {u"Network/Proxy/Port"_qs, u"Preferences/Connection/Proxy/Port"_qs},
{"Network/Proxy/Type", "Preferences/Connection/ProxyType"}, {u"Network/Proxy/Type"_qs, u"Preferences/Connection/ProxyType"_qs},
{"Network/Proxy/Username", "Preferences/Connection/Proxy/Username"}, {u"Network/Proxy/Username"_qs, u"Preferences/Connection/Proxy/Username"_qs},
{"State/BannedIPs", "Preferences/IPFilter/BannedIPs"} {u"State/BannedIPs"_qs, u"Preferences/IPFilter/BannedIPs"_qs}
}; };
auto *settingsStorage = SettingsStorage::instance(); auto *settingsStorage = SettingsStorage::instance();

View file

@ -285,9 +285,9 @@ void BitTorrent::BencodeResumeDataStorage::loadQueue(const Path &queueFilename)
if (queueFile.open(QFile::ReadOnly)) if (queueFile.open(QFile::ReadOnly))
{ {
const QRegularExpression hashPattern {QLatin1String("^([A-Fa-f0-9]{40})$")}; const QRegularExpression hashPattern {QLatin1String("^([A-Fa-f0-9]{40})$")};
QByteArray line; QString line;
int start = 0; int start = 0;
while (!(line = queueFile.readLine().trimmed()).isEmpty()) while (!(line = QString::fromLatin1(queueFile.readLine().trimmed())).isEmpty())
{ {
const QRegularExpressionMatch rxMatch = hashPattern.match(line); const QRegularExpressionMatch rxMatch = hashPattern.match(line);
if (rxMatch.hasMatch()) if (rxMatch.hasMatch())

View file

@ -58,14 +58,14 @@
namespace namespace
{ {
const char DB_CONNECTION_NAME[] = "ResumeDataStorage"; const QString DB_CONNECTION_NAME = u"ResumeDataStorage"_qs;
const int DB_VERSION = 2; const int DB_VERSION = 2;
const char DB_TABLE_META[] = "meta"; const QString DB_TABLE_META = u"meta"_qs;
const char DB_TABLE_TORRENTS[] = "torrents"; const QString DB_TABLE_TORRENTS = u"torrents"_qs;
const char META_VERSION[] = "version"; const QString META_VERSION = u"version"_qs;
struct Column struct Column
{ {
@ -370,7 +370,7 @@ int BitTorrent::DBResumeDataStorage::currentDBVersion() const
if (!query.prepare(selectDBVersionStatement)) if (!query.prepare(selectDBVersionStatement))
throw RuntimeError(query.lastError().text()); throw RuntimeError(query.lastError().text());
query.bindValue(DB_COLUMN_NAME.placeholder, QString::fromLatin1(META_VERSION)); query.bindValue(DB_COLUMN_NAME.placeholder, META_VERSION);
if (!query.exec()) if (!query.exec())
throw RuntimeError(query.lastError().text()); throw RuntimeError(query.lastError().text());
@ -410,7 +410,7 @@ void BitTorrent::DBResumeDataStorage::createDB() const
if (!query.prepare(insertMetaVersionQuery)) if (!query.prepare(insertMetaVersionQuery))
throw RuntimeError(query.lastError().text()); throw RuntimeError(query.lastError().text());
query.bindValue(DB_COLUMN_NAME.placeholder, QString::fromLatin1(META_VERSION)); query.bindValue(DB_COLUMN_NAME.placeholder, META_VERSION);
query.bindValue(DB_COLUMN_VALUE.placeholder, DB_VERSION); query.bindValue(DB_COLUMN_VALUE.placeholder, DB_VERSION);
if (!query.exec()) if (!query.exec())
@ -468,7 +468,7 @@ void BitTorrent::DBResumeDataStorage::updateDBFromVersion1() const
if (!query.prepare(updateMetaVersionQuery)) if (!query.prepare(updateMetaVersionQuery))
throw RuntimeError(query.lastError().text()); throw RuntimeError(query.lastError().text());
query.bindValue(DB_COLUMN_NAME.placeholder, QString::fromLatin1(META_VERSION)); query.bindValue(DB_COLUMN_NAME.placeholder, META_VERSION);
query.bindValue(DB_COLUMN_VALUE.placeholder, DB_VERSION); query.bindValue(DB_COLUMN_VALUE.placeholder, DB_VERSION);
if (!query.exec()) if (!query.exec())

View file

@ -113,7 +113,7 @@ const Path CATEGORIES_FILE_NAME {u"categories.json"_qs};
namespace namespace
{ {
const char PEER_ID[] = "qB"; const char PEER_ID[] = "qB";
const char USER_AGENT[] = "qBittorrent/" QBT_VERSION_2; const auto USER_AGENT = QStringLiteral("qBittorrent/" QBT_VERSION_2);
void torrentQueuePositionUp(const lt::torrent_handle &handle) void torrentQueuePositionUp(const lt::torrent_handle &handle)
{ {
@ -691,7 +691,7 @@ Path Session::downloadPath() const
bool Session::isValidCategoryName(const QString &name) bool Session::isValidCategoryName(const QString &name)
{ {
static const QRegularExpression re(R"(^([^\\\/]|[^\\\/]([^\\\/]|\/(?=[^\/]))*[^\\\/])$)"); static const QRegularExpression re(uR"(^([^\\\/]|[^\\\/]([^\\\/]|\/(?=[^\/]))*[^\\\/])$)"_qs);
if (!name.isEmpty() && (name.indexOf(re) != 0)) if (!name.isEmpty() && (name.indexOf(re) != 0))
{ {
qDebug() << "Incorrect category name:" << name; qDebug() << "Incorrect category name:" << name;
@ -708,7 +708,7 @@ QStringList Session::expandCategory(const QString &category)
return result; return result;
int index = 0; int index = 0;
while ((index = category.indexOf('/', index)) >= 0) while ((index = category.indexOf(u'/', index)) >= 0)
{ {
result << category.left(index); result << category.left(index);
++index; ++index;
@ -824,7 +824,7 @@ bool Session::removeCategory(const QString &name)
for (TorrentImpl *const torrent : asConst(m_torrents)) for (TorrentImpl *const torrent : asConst(m_torrents))
{ {
if (torrent->belongsToCategory(name)) if (torrent->belongsToCategory(name))
torrent->setCategory(""); torrent->setCategory(u""_qs);
} }
// remove stored category and its subcategories if exist // remove stored category and its subcategories if exist
@ -832,7 +832,7 @@ bool Session::removeCategory(const QString &name)
if (isSubcategoriesEnabled()) if (isSubcategoriesEnabled())
{ {
// remove subcategories // remove subcategories
const QString test = name + '/'; const QString test = name + u'/';
Algorithm::removeIf(m_categories, [this, &test, &result](const QString &category, const CategoryOptions &) Algorithm::removeIf(m_categories, [this, &test, &result](const QString &category, const CategoryOptions &)
{ {
if (category.startsWith(test)) if (category.startsWith(test))
@ -900,7 +900,7 @@ QSet<QString> Session::tags() const
bool Session::isValidTag(const QString &tag) bool Session::isValidTag(const QString &tag)
{ {
return (!tag.trimmed().isEmpty() && !tag.contains(',')); return (!tag.trimmed().isEmpty() && !tag.contains(u','));
} }
bool Session::hasTag(const QString &tag) const bool Session::hasTag(const QString &tag) const
@ -1138,7 +1138,7 @@ void Session::initializeNativeSession()
pack.set_int(lt::settings_pack::alert_mask, alertMask); pack.set_int(lt::settings_pack::alert_mask, alertMask);
pack.set_str(lt::settings_pack::peer_fingerprint, peerId); pack.set_str(lt::settings_pack::peer_fingerprint, peerId);
pack.set_bool(lt::settings_pack::listen_system_port_fallback, false); pack.set_bool(lt::settings_pack::listen_system_port_fallback, false);
pack.set_str(lt::settings_pack::user_agent, USER_AGENT); pack.set_str(lt::settings_pack::user_agent, USER_AGENT.toStdString());
pack.set_bool(lt::settings_pack::use_dht_as_fallback, false); pack.set_bool(lt::settings_pack::use_dht_as_fallback, false);
// Speed up exit // Speed up exit
pack.set_int(lt::settings_pack::auto_scrape_interval, 1200); // 20 minutes pack.set_int(lt::settings_pack::auto_scrape_interval, 1200); // 20 minutes
@ -1503,7 +1503,7 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack)
QStringList endpoints; QStringList endpoints;
QStringList outgoingInterfaces; QStringList outgoingInterfaces;
const QString portString = ':' + QString::number(port()); const QString portString = u':' + QString::number(port());
for (const QString &ip : asConst(getListeningIPs())) for (const QString &ip : asConst(getListeningIPs()))
{ {
@ -1515,7 +1515,7 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack)
? Utils::Net::canonicalIPv6Addr(addr).toString() ? Utils::Net::canonicalIPv6Addr(addr).toString()
: addr.toString(); : addr.toString();
endpoints << ((isIPv6 ? ('[' + ip + ']') : ip) + portString); endpoints << ((isIPv6 ? (u'[' + ip + u']') : ip) + portString);
if ((ip != QLatin1String("0.0.0.0")) && (ip != QLatin1String("::"))) if ((ip != QLatin1String("0.0.0.0")) && (ip != QLatin1String("::")))
outgoingInterfaces << ip; outgoingInterfaces << ip;
@ -1548,11 +1548,11 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack)
} }
} }
const QString finalEndpoints = endpoints.join(','); const QString finalEndpoints = endpoints.join(u',');
settingsPack.set_str(lt::settings_pack::listen_interfaces, finalEndpoints.toStdString()); settingsPack.set_str(lt::settings_pack::listen_interfaces, finalEndpoints.toStdString());
LogMsg(tr("Trying to listen on the following list of IP addresses: \"%1\"").arg(finalEndpoints)); LogMsg(tr("Trying to listen on the following list of IP addresses: \"%1\"").arg(finalEndpoints));
settingsPack.set_str(lt::settings_pack::outgoing_interfaces, outgoingInterfaces.join(',').toStdString()); settingsPack.set_str(lt::settings_pack::outgoing_interfaces, outgoingInterfaces.join(u',').toStdString());
m_listenInterfaceConfigured = true; m_listenInterfaceConfigured = true;
} }
@ -2144,7 +2144,7 @@ LoadTorrentParams Session::initLoadTorrentParams(const AddTorrentParams &addTorr
const QString category = addTorrentParams.category; const QString category = addTorrentParams.category;
if (!category.isEmpty() && !m_categories.contains(category) && !addCategory(category)) if (!category.isEmpty() && !m_categories.contains(category) && !addCategory(category))
loadTorrentParams.category = ""; loadTorrentParams.category = u""_qs;
else else
loadTorrentParams.category = category; loadTorrentParams.category = category;
@ -5010,7 +5010,7 @@ void Session::handleFileErrorAlert(const lt::file_error_alert *p)
const QString msg = QString::fromStdString(p->message()); const QString msg = QString::fromStdString(p->message());
LogMsg(tr("File error alert. Torrent: \"%1\". File: \"%2\". Reason: \"%3\"") LogMsg(tr("File error alert. Torrent: \"%1\". File: \"%2\". Reason: \"%3\"")
.arg(torrent->name(), p->filename(), msg) .arg(torrent->name(), QString::fromLocal8Bit(p->filename()), msg)
, Log::WARNING); , Log::WARNING);
emit fullDiskError(torrent, msg); emit fullDiskError(torrent, msg);
} }
@ -5041,7 +5041,7 @@ void Session::handlePeerBlockedAlert(const lt::peer_blocked_alert *p)
reason = tr("port filter", "this peer was blocked. Reason: port filter."); reason = tr("port filter", "this peer was blocked. Reason: port filter.");
break; break;
case lt::peer_blocked_alert::i2p_mixed: case lt::peer_blocked_alert::i2p_mixed:
reason = tr("%1 mixed mode restrictions", "this peer was blocked. Reason: I2P mixed mode restrictions.").arg("I2P"); // don't translate I2P reason = tr("%1 mixed mode restrictions", "this peer was blocked. Reason: I2P mixed mode restrictions.").arg(u"I2P"_qs); // don't translate I2P
break; break;
case lt::peer_blocked_alert::privileged_ports: case lt::peer_blocked_alert::privileged_ports:
reason = tr("use of privileged port", "this peer was blocked. Reason: use of privileged port."); reason = tr("use of privileged port", "this peer was blocked. Reason: use of privileged port.");
@ -5050,7 +5050,7 @@ void Session::handlePeerBlockedAlert(const lt::peer_blocked_alert *p)
reason = tr("%1 is disabled", "this peer was blocked. Reason: uTP is disabled.").arg(QString::fromUtf8(C_UTP)); // don't translate μTP reason = tr("%1 is disabled", "this peer was blocked. Reason: uTP is disabled.").arg(QString::fromUtf8(C_UTP)); // don't translate μTP
break; break;
case lt::peer_blocked_alert::tcp_disabled: case lt::peer_blocked_alert::tcp_disabled:
reason = tr("%1 is disabled", "this peer was blocked. Reason: TCP is disabled.").arg("TCP"); // don't translate TCP reason = tr("%1 is disabled", "this peer was blocked. Reason: TCP is disabled.").arg(u"TCP"_qs); // don't translate TCP
break; break;
} }
@ -5075,13 +5075,13 @@ void Session::handleUrlSeedAlert(const lt::url_seed_alert *p)
if (p->error) if (p->error)
{ {
LogMsg(tr("URL seed DNS lookup failed. Torrent: \"%1\". URL: \"%2\". Error: \"%3\"") LogMsg(tr("URL seed DNS lookup failed. Torrent: \"%1\". URL: \"%2\". Error: \"%3\"")
.arg(torrent->name(), p->server_url(), QString::fromStdString(p->message())) .arg(torrent->name(), QString::fromUtf8(p->server_url()), QString::fromStdString(p->message()))
, Log::WARNING); , Log::WARNING);
} }
else else
{ {
LogMsg(tr("Received error message from URL seed. Torrent: \"%1\". URL: \"%2\". Message: \"%3\"") LogMsg(tr("Received error message from URL seed. Torrent: \"%1\". URL: \"%2\". Message: \"%3\"")
.arg(torrent->name(), p->server_url(), p->error_message()) .arg(torrent->name(), QString::fromUtf8(p->server_url()), QString::fromUtf8(p->error_message()))
, Log::WARNING); , Log::WARNING);
} }
} }
@ -5296,7 +5296,7 @@ void Session::handleTrackerAlert(const lt::tracker_alert *a)
if (a->type() == lt::tracker_reply_alert::alert_type) if (a->type() == lt::tracker_reply_alert::alert_type)
{ {
const int numPeers = static_cast<const lt::tracker_reply_alert *>(a)->num_peers; const int numPeers = static_cast<const lt::tracker_reply_alert *>(a)->num_peers;
torrent->updatePeerCount(trackerURL, a->local_endpoint, numPeers); torrent->updatePeerCount(QString::fromUtf8(trackerURL), a->local_endpoint, numPeers);
} }
} }

View file

@ -30,6 +30,7 @@
#include <QDateTime> #include <QDateTime>
#include "base/global.h"
#include "base/bittorrent/session.h" #include "base/bittorrent/session.h"
#include "base/bittorrent/sessionstatus.h" #include "base/bittorrent/sessionstatus.h"
#include "base/profile.h" #include "base/profile.h"
@ -94,9 +95,9 @@ void Statistics::save() const
SettingsPtr s = Profile::instance()->applicationSettings(QLatin1String("qBittorrent-data")); SettingsPtr s = Profile::instance()->applicationSettings(QLatin1String("qBittorrent-data"));
QVariantHash v; QVariantHash v;
v.insert("AlltimeDL", m_alltimeDL + m_sessionDL); v.insert(u"AlltimeDL"_qs, m_alltimeDL + m_sessionDL);
v.insert("AlltimeUL", m_alltimeUL + m_sessionUL); v.insert(u"AlltimeUL"_qs, m_alltimeUL + m_sessionUL);
s->setValue("Stats/AllStats", v); s->setValue(u"Stats/AllStats"_qs, v);
m_dirty = false; m_dirty = false;
m_lastWrite = now; m_lastWrite = now;
} }
@ -104,8 +105,8 @@ void Statistics::save() const
void Statistics::load() void Statistics::load()
{ {
const SettingsPtr s = Profile::instance()->applicationSettings(QLatin1String("qBittorrent-data")); const SettingsPtr s = Profile::instance()->applicationSettings(QLatin1String("qBittorrent-data"));
const QVariantHash v = s->value("Stats/AllStats").toHash(); const QVariantHash v = s->value(u"Stats/AllStats"_qs).toHash();
m_alltimeDL = v["AlltimeDL"].toULongLong(); m_alltimeDL = v[u"AlltimeDL"_qs].toULongLong();
m_alltimeUL = v["AlltimeUL"].toULongLong(); m_alltimeUL = v[u"AlltimeUL"_qs].toULongLong();
} }

View file

@ -52,7 +52,7 @@ namespace
// name starts with a . // name starts with a .
bool fileFilter(const std::string &f) bool fileFilter(const std::string &f)
{ {
return !Path(f).filename().startsWith('.'); return !Path(f).filename().startsWith(u'.');
} }
#ifdef QBT_USES_LIBTORRENT2 #ifdef QBT_USES_LIBTORRENT2

View file

@ -746,7 +746,7 @@ bool TorrentImpl::belongsToCategory(const QString &category) const
if (m_category == category) return true; if (m_category == category) return true;
if (m_session->isSubcategoriesEnabled() && m_category.startsWith(category + '/')) if (m_session->isSubcategoriesEnabled() && m_category.startsWith(category + u'/'))
return true; return true;
return false; return false;
@ -1843,7 +1843,7 @@ void TorrentImpl::handleFileRenamedAlert(const lt::file_renamed_alert *p)
// For example renaming "a/b/c" to "d/b/c", then folders "a/b" and "a" will // For example renaming "a/b/c" to "d/b/c", then folders "a/b" and "a" will
// be removed if they are empty // be removed if they are empty
const Path oldFilePath = m_filePaths.at(fileIndex); const Path oldFilePath = m_filePaths.at(fileIndex);
const Path newFilePath {QString(p->new_name())}; const Path newFilePath {QString::fromUtf8(p->new_name())};
// Check if ".!qB" extension was just added or removed // Check if ".!qB" extension was just added or removed
// We should compare path in a case sensitive manner even on case insensitive // We should compare path in a case sensitive manner even on case insensitive

View file

@ -122,7 +122,7 @@ nonstd::expected<TorrentInfo, QString> TorrentInfo::loadFromFile(const Path &pat
} }
catch (const std::bad_alloc &e) catch (const std::bad_alloc &e)
{ {
return nonstd::make_unexpected(tr("Torrent file read error: %1").arg(e.what())); return nonstd::make_unexpected(tr("Torrent file read error: %1").arg(QString::fromLocal8Bit(e.what())));
} }
if (data.size() != file.size()) if (data.size() != file.size())
@ -294,7 +294,7 @@ QVector<QUrl> TorrentInfo::urlSeeds() const
for (const lt::web_seed_entry &webSeed : nativeWebSeeds) for (const lt::web_seed_entry &webSeed : nativeWebSeeds)
{ {
if (webSeed.type == lt::web_seed_entry::url_seed) if (webSeed.type == lt::web_seed_entry::url_seed)
urlSeeds.append(QUrl(webSeed.url.c_str())); urlSeeds.append(QUrl(QString::fromStdString(webSeed.url)));
} }
return urlSeeds; return urlSeeds;

View file

@ -53,23 +53,23 @@ namespace
// constants // constants
const int PEER_ID_SIZE = 20; const int PEER_ID_SIZE = 20;
const char ANNOUNCE_REQUEST_PATH[] = "/announce"; const QString ANNOUNCE_REQUEST_PATH = u"/announce"_qs;
const char ANNOUNCE_REQUEST_COMPACT[] = "compact"; const QString ANNOUNCE_REQUEST_COMPACT = u"compact"_qs;
const char ANNOUNCE_REQUEST_INFO_HASH[] = "info_hash"; const QString ANNOUNCE_REQUEST_INFO_HASH = u"info_hash"_qs;
const char ANNOUNCE_REQUEST_IP[] = "ip"; const QString ANNOUNCE_REQUEST_IP = u"ip"_qs;
const char ANNOUNCE_REQUEST_LEFT[] = "left"; const QString ANNOUNCE_REQUEST_LEFT = u"left"_qs;
const char ANNOUNCE_REQUEST_NO_PEER_ID[] = "no_peer_id"; const QString ANNOUNCE_REQUEST_NO_PEER_ID = u"no_peer_id"_qs;
const char ANNOUNCE_REQUEST_NUM_WANT[] = "numwant"; const QString ANNOUNCE_REQUEST_NUM_WANT = u"numwant"_qs;
const char ANNOUNCE_REQUEST_PEER_ID[] = "peer_id"; const QString ANNOUNCE_REQUEST_PEER_ID = u"peer_id"_qs;
const char ANNOUNCE_REQUEST_PORT[] = "port"; const QString ANNOUNCE_REQUEST_PORT = u"port"_qs;
const char ANNOUNCE_REQUEST_EVENT[] = "event"; const QString ANNOUNCE_REQUEST_EVENT = u"event"_qs;
const char ANNOUNCE_REQUEST_EVENT_COMPLETED[] = "completed"; const QString ANNOUNCE_REQUEST_EVENT_COMPLETED = u"completed"_qs;
const char ANNOUNCE_REQUEST_EVENT_EMPTY[] = "empty"; const QString ANNOUNCE_REQUEST_EVENT_EMPTY = u"empty"_qs;
const char ANNOUNCE_REQUEST_EVENT_STARTED[] = "started"; const QString ANNOUNCE_REQUEST_EVENT_STARTED = u"started"_qs;
const char ANNOUNCE_REQUEST_EVENT_STOPPED[] = "stopped"; const QString ANNOUNCE_REQUEST_EVENT_STOPPED = u"stopped"_qs;
const char ANNOUNCE_REQUEST_EVENT_PAUSED[] = "paused"; const QString ANNOUNCE_REQUEST_EVENT_PAUSED = u"paused"_qs;
const char ANNOUNCE_RESPONSE_COMPLETE[] = "complete"; const char ANNOUNCE_RESPONSE_COMPLETE[] = "complete";
const char ANNOUNCE_RESPONSE_EXTERNAL_IP[] = "external ip"; const char ANNOUNCE_RESPONSE_EXTERNAL_IP[] = "external ip";
@ -293,32 +293,32 @@ void Tracker::processAnnounceRequest()
// 1. info_hash // 1. info_hash
const auto infoHashIter = queryParams.find(ANNOUNCE_REQUEST_INFO_HASH); const auto infoHashIter = queryParams.find(ANNOUNCE_REQUEST_INFO_HASH);
if (infoHashIter == queryParams.end()) if (infoHashIter == queryParams.end())
throw TrackerError("Missing \"info_hash\" parameter"); throw TrackerError(u"Missing \"info_hash\" parameter"_qs);
const auto torrentID = TorrentID::fromString(infoHashIter->toHex()); const auto torrentID = TorrentID::fromString(QString::fromLatin1(infoHashIter->toHex()));
if (!torrentID.isValid()) if (!torrentID.isValid())
throw TrackerError("Invalid \"info_hash\" parameter"); throw TrackerError(u"Invalid \"info_hash\" parameter"_qs);
announceReq.torrentID = torrentID; announceReq.torrentID = torrentID;
// 2. peer_id // 2. peer_id
const auto peerIdIter = queryParams.find(ANNOUNCE_REQUEST_PEER_ID); const auto peerIdIter = queryParams.find(ANNOUNCE_REQUEST_PEER_ID);
if (peerIdIter == queryParams.end()) if (peerIdIter == queryParams.end())
throw TrackerError("Missing \"peer_id\" parameter"); throw TrackerError(u"Missing \"peer_id\" parameter"_qs);
if (peerIdIter->size() > PEER_ID_SIZE) if (peerIdIter->size() > PEER_ID_SIZE)
throw TrackerError("Invalid \"peer_id\" parameter"); throw TrackerError(u"Invalid \"peer_id\" parameter"_qs);
announceReq.peer.peerId = *peerIdIter; announceReq.peer.peerId = *peerIdIter;
// 3. port // 3. port
const auto portIter = queryParams.find(ANNOUNCE_REQUEST_PORT); const auto portIter = queryParams.find(ANNOUNCE_REQUEST_PORT);
if (portIter == queryParams.end()) if (portIter == queryParams.end())
throw TrackerError("Missing \"port\" parameter"); throw TrackerError(u"Missing \"port\" parameter"_qs);
const ushort portNum = portIter->toUShort(); const ushort portNum = portIter->toUShort();
if (portNum == 0) if (portNum == 0)
throw TrackerError("Invalid \"port\" parameter"); throw TrackerError(u"Invalid \"port\" parameter"_qs);
announceReq.peer.port = portNum; announceReq.peer.port = portNum;
@ -328,7 +328,7 @@ void Tracker::processAnnounceRequest()
{ {
const int num = numWantIter->toInt(); const int num = numWantIter->toInt();
if (num < 0) if (num < 0)
throw TrackerError("Invalid \"numwant\" parameter"); throw TrackerError(u"Invalid \"numwant\" parameter"_qs);
announceReq.numwant = num; announceReq.numwant = num;
} }
@ -355,7 +355,7 @@ void Tracker::processAnnounceRequest()
: announceReq.socketAddress.toString().toLatin1().constData(), : announceReq.socketAddress.toString().toLatin1().constData(),
// 10. event // 10. event
announceReq.event = queryParams.value(ANNOUNCE_REQUEST_EVENT); announceReq.event = QString::fromLatin1(queryParams.value(ANNOUNCE_REQUEST_EVENT));
if (announceReq.event.isEmpty() if (announceReq.event.isEmpty()
|| (announceReq.event == ANNOUNCE_REQUEST_EVENT_EMPTY) || (announceReq.event == ANNOUNCE_REQUEST_EVENT_EMPTY)
@ -373,7 +373,7 @@ void Tracker::processAnnounceRequest()
} }
else else
{ {
throw TrackerError("Invalid \"event\" parameter"); throw TrackerError(u"Invalid \"event\" parameter"_qs);
} }
prepareAnnounceResponse(announceReq); prepareAnnounceResponse(announceReq);

View file

@ -82,8 +82,8 @@ void Connection::read()
Logger::instance()->addMessage(tr("Http request size exceeds limitation, closing socket. Limit: %1, IP: %2") Logger::instance()->addMessage(tr("Http request size exceeds limitation, closing socket. Limit: %1, IP: %2")
.arg(bufferLimit).arg(m_socket->peerAddress().toString()), Log::WARNING); .arg(bufferLimit).arg(m_socket->peerAddress().toString()), Log::WARNING);
Response resp(413, "Payload Too Large"); Response resp(413, u"Payload Too Large"_qs);
resp.headers[HEADER_CONNECTION] = "close"; resp.headers[HEADER_CONNECTION] = u"close"_qs;
sendResponse(resp); sendResponse(resp);
m_socket->close(); m_socket->close();
@ -96,8 +96,8 @@ void Connection::read()
Logger::instance()->addMessage(tr("Bad Http request, closing socket. IP: %1") Logger::instance()->addMessage(tr("Bad Http request, closing socket. IP: %1")
.arg(m_socket->peerAddress().toString()), Log::WARNING); .arg(m_socket->peerAddress().toString()), Log::WARNING);
Response resp(400, "Bad Request"); Response resp(400, u"Bad Request"_qs);
resp.headers[HEADER_CONNECTION] = "close"; resp.headers[HEADER_CONNECTION] = u"close"_qs;
sendResponse(resp); sendResponse(resp);
m_socket->close(); m_socket->close();
@ -110,10 +110,10 @@ void Connection::read()
Response resp = m_requestHandler->processRequest(result.request, env); Response resp = m_requestHandler->processRequest(result.request, env);
if (acceptsGzipEncoding(result.request.headers["accept-encoding"])) if (acceptsGzipEncoding(result.request.headers[u"accept-encoding"_qs]))
resp.headers[HEADER_CONTENT_ENCODING] = "gzip"; resp.headers[HEADER_CONTENT_ENCODING] = u"gzip"_qs;
resp.headers[HEADER_CONNECTION] = "keep-alive"; resp.headers[HEADER_CONNECTION] = u"keep-alive"_qs;
sendResponse(resp); sendResponse(resp);
m_receivedData = m_receivedData.mid(result.frameSize); m_receivedData = m_receivedData.mid(result.frameSize);
@ -172,7 +172,7 @@ bool Connection::acceptsGzipEncoding(QString codings)
return false; return false;
}; };
const QList<QStringView> list = QStringView(codings.remove(' ').remove('\t')).split(u',', Qt::SkipEmptyParts); const QList<QStringView> list = QStringView(codings.remove(u' ').remove(u'\t')).split(u',', Qt::SkipEmptyParts);
if (list.isEmpty()) if (list.isEmpty())
return false; return false;

View file

@ -60,7 +60,7 @@ namespace
bool parseHeaderLine(const QStringView line, HeaderMap &out) bool parseHeaderLine(const QStringView line, HeaderMap &out)
{ {
// [rfc7230] 3.2. Header Fields // [rfc7230] 3.2. Header Fields
const int i = line.indexOf(':'); const int i = line.indexOf(u':');
if (i <= 0) if (i <= 0)
{ {
qWarning() << Q_FUNC_INFO << "invalid http header:" << line; qWarning() << Q_FUNC_INFO << "invalid http header:" << line;
@ -252,7 +252,7 @@ bool RequestParser::parsePostMessage(const QByteArray &data)
// [URL Standard] 5.1 application/x-www-form-urlencoded parsing // [URL Standard] 5.1 application/x-www-form-urlencoded parsing
const QByteArray processedData = QByteArray(data).replace('+', ' '); const QByteArray processedData = QByteArray(data).replace('+', ' ');
QListIterator<QStringPair> i(QUrlQuery(processedData).queryItems(QUrl::FullyDecoded)); QListIterator<QStringPair> i(QUrlQuery(QString::fromUtf8(processedData)).queryItems(QUrl::FullyDecoded));
while (i.hasNext()) while (i.hasNext())
{ {
const QStringPair pair = i.next(); const QStringPair pair = i.next();
@ -330,7 +330,7 @@ bool RequestParser::parseFormData(const QByteArray &data)
for (const auto &directive : directives) for (const auto &directive : directives)
{ {
const int idx = directive.indexOf('='); const int idx = directive.indexOf(u'=');
if (idx < 0) if (idx < 0)
continue; continue;
@ -356,7 +356,7 @@ bool RequestParser::parseFormData(const QByteArray &data)
} }
else if (headersMap.contains(name)) else if (headersMap.contains(name))
{ {
m_request.posts[headersMap[name]] = payload; m_request.posts[headersMap[name]] = QString::fromUtf8(payload);
} }
else else
{ {

View file

@ -58,11 +58,11 @@ IconProvider *IconProvider::instance()
Path IconProvider::getIconPath(const QString &iconId) const Path IconProvider::getIconPath(const QString &iconId) const
{ {
// there are a few icons not available in svg // there are a few icons not available in svg
const Path pathSvg {":/icons/" + iconId + ".svg"}; const Path pathSvg {u":/icons/" + iconId + u".svg"};
if (pathSvg.exists()) if (pathSvg.exists())
return pathSvg; return pathSvg;
const Path pathPng {":/icons/" + iconId + ".png"}; const Path pathPng {u":/icons/" + iconId + u".png"};
return pathPng; return pathPng;
} }

View file

@ -32,6 +32,7 @@
#include <QRegularExpression> #include <QRegularExpression>
#include <QUrlQuery> #include <QUrlQuery>
#include "base/global.h"
#include "base/logger.h" #include "base/logger.h"
#include "base/net/downloadmanager.h" #include "base/net/downloadmanager.h"
#include "base/version.h" #include "base/version.h"
@ -76,7 +77,7 @@ void DNSUpdater::checkPublicIP()
Q_ASSERT(m_state == OK); Q_ASSERT(m_state == OK);
DownloadManager::instance()->download( DownloadManager::instance()->download(
DownloadRequest("http://checkip.dyndns.org").userAgent("qBittorrent/" QBT_VERSION_2) DownloadRequest(u"http://checkip.dyndns.org"_qs).userAgent(QStringLiteral("qBittorrent/" QBT_VERSION_2))
, this, &DNSUpdater::ipRequestFinished); , this, &DNSUpdater::ipRequestFinished);
m_lastIPCheckTime = QDateTime::currentDateTime(); m_lastIPCheckTime = QDateTime::currentDateTime();
@ -91,7 +92,7 @@ void DNSUpdater::ipRequestFinished(const DownloadResult &result)
} }
// Parse response // Parse response
const QRegularExpressionMatch ipRegexMatch = QRegularExpression("Current IP Address:\\s+([^<]+)</body>").match(result.data); const QRegularExpressionMatch ipRegexMatch = QRegularExpression(u"Current IP Address:\\s+([^<]+)</body>"_qs).match(QString::fromUtf8(result.data));
if (ipRegexMatch.hasMatch()) if (ipRegexMatch.hasMatch())
{ {
QString ipStr = ipRegexMatch.captured(1); QString ipStr = ipRegexMatch.captured(1);
@ -124,7 +125,7 @@ void DNSUpdater::updateDNSService()
m_lastIPCheckTime = QDateTime::currentDateTime(); m_lastIPCheckTime = QDateTime::currentDateTime();
DownloadManager::instance()->download( DownloadManager::instance()->download(
DownloadRequest(getUpdateUrl()).userAgent("qBittorrent/" QBT_VERSION_2) DownloadRequest(getUpdateUrl()).userAgent(QStringLiteral("qBittorrent/" QBT_VERSION_2))
, this, &DNSUpdater::ipUpdateFinished); , this, &DNSUpdater::ipUpdateFinished);
} }
@ -132,9 +133,9 @@ QString DNSUpdater::getUpdateUrl() const
{ {
QUrl url; QUrl url;
#ifdef QT_NO_OPENSSL #ifdef QT_NO_OPENSSL
url.setScheme("http"); url.setScheme(u"http"_qs);
#else #else
url.setScheme("https"); url.setScheme(u"https"_qs);
#endif #endif
url.setUserName(m_username); url.setUserName(m_username);
url.setPassword(m_password); url.setPassword(m_password);
@ -144,21 +145,21 @@ QString DNSUpdater::getUpdateUrl() const
switch (m_service) switch (m_service)
{ {
case DNS::Service::DynDNS: case DNS::Service::DynDNS:
url.setHost("members.dyndns.org"); url.setHost(u"members.dyndns.org"_qs);
break; break;
case DNS::Service::NoIP: case DNS::Service::NoIP:
url.setHost("dynupdate.no-ip.com"); url.setHost(u"dynupdate.no-ip.com"_qs);
break; break;
default: default:
qWarning() << "Unrecognized Dynamic DNS service!"; qWarning() << "Unrecognized Dynamic DNS service!";
Q_ASSERT(false); Q_ASSERT(false);
break; break;
} }
url.setPath("/nic/update"); url.setPath(u"/nic/update"_qs);
QUrlQuery urlQuery(url); QUrlQuery urlQuery(url);
urlQuery.addQueryItem("hostname", m_domain); urlQuery.addQueryItem(u"hostname"_qs, m_domain);
urlQuery.addQueryItem("myip", m_lastIP.toString()); urlQuery.addQueryItem(u"myip"_qs, m_lastIP.toString());
url.setQuery(urlQuery); url.setQuery(urlQuery);
Q_ASSERT(url.isValid()); Q_ASSERT(url.isValid());
@ -169,7 +170,7 @@ QString DNSUpdater::getUpdateUrl() const
void DNSUpdater::ipUpdateFinished(const DownloadResult &result) void DNSUpdater::ipUpdateFinished(const DownloadResult &result)
{ {
if (result.status == DownloadStatus::Success) if (result.status == DownloadStatus::Success)
processIPUpdateReply(result.data); processIPUpdateReply(QString::fromUtf8(result.data));
else else
qWarning() << "IP update failed:" << result.errorString; qWarning() << "IP update failed:" << result.errorString;
} }
@ -178,16 +179,16 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
{ {
Logger *const logger = Logger::instance(); Logger *const logger = Logger::instance();
qDebug() << Q_FUNC_INFO << reply; qDebug() << Q_FUNC_INFO << reply;
const QString code = reply.split(' ').first(); const QString code = reply.split(u' ').first();
qDebug() << Q_FUNC_INFO << "Code:" << code; qDebug() << Q_FUNC_INFO << "Code:" << code;
if ((code == "good") || (code == "nochg")) if ((code == u"good") || (code == u"nochg"))
{ {
logger->addMessage(tr("Your dynamic DNS was successfully updated."), Log::INFO); logger->addMessage(tr("Your dynamic DNS was successfully updated."), Log::INFO);
return; return;
} }
if ((code == "911") || (code == "dnserr")) if ((code == u"911") || (code == u"dnserr"))
{ {
logger->addMessage(tr("Dynamic DNS error: The service is temporarily unavailable, it will be retried in 30 minutes."), Log::CRITICAL); logger->addMessage(tr("Dynamic DNS error: The service is temporarily unavailable, it will be retried in 30 minutes."), Log::CRITICAL);
m_lastIP.clear(); m_lastIP.clear();
@ -198,21 +199,21 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
// Everything below is an error, stop updating until the user updates something // Everything below is an error, stop updating until the user updates something
m_ipCheckTimer.stop(); m_ipCheckTimer.stop();
m_lastIP.clear(); m_lastIP.clear();
if (code == "nohost") if (code == u"nohost")
{ {
logger->addMessage(tr("Dynamic DNS error: hostname supplied does not exist under specified account."), Log::CRITICAL); logger->addMessage(tr("Dynamic DNS error: hostname supplied does not exist under specified account."), Log::CRITICAL);
m_state = INVALID_CREDS; m_state = INVALID_CREDS;
return; return;
} }
if (code == "badauth") if (code == u"badauth")
{ {
logger->addMessage(tr("Dynamic DNS error: Invalid username/password."), Log::CRITICAL); logger->addMessage(tr("Dynamic DNS error: Invalid username/password."), Log::CRITICAL);
m_state = INVALID_CREDS; m_state = INVALID_CREDS;
return; return;
} }
if (code == "badagent") if (code == u"badagent")
{ {
logger->addMessage(tr("Dynamic DNS error: qBittorrent was blacklisted by the service, please submit a bug report at http://bugs.qbittorrent.org."), logger->addMessage(tr("Dynamic DNS error: qBittorrent was blacklisted by the service, please submit a bug report at http://bugs.qbittorrent.org."),
Log::CRITICAL); Log::CRITICAL);
@ -220,15 +221,15 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
return; return;
} }
if (code == "!donator") if (code == u"!donator")
{ {
logger->addMessage(tr("Dynamic DNS error: %1 was returned by the service, please submit a bug report at http://bugs.qbittorrent.org.").arg("!donator"), logger->addMessage(tr("Dynamic DNS error: %1 was returned by the service, please submit a bug report at http://bugs.qbittorrent.org.").arg(u"!donator"_qs),
Log::CRITICAL); Log::CRITICAL);
m_state = FATAL; m_state = FATAL;
return; return;
} }
if (code == "abuse") if (code == u"abuse")
{ {
logger->addMessage(tr("Dynamic DNS error: Your username was blocked due to abuse."), Log::CRITICAL); logger->addMessage(tr("Dynamic DNS error: Your username was blocked due to abuse."), Log::CRITICAL);
m_state = FATAL; m_state = FATAL;
@ -250,7 +251,7 @@ void DNSUpdater::updateCredentials()
if (m_domain != pref->getDynDomainName()) if (m_domain != pref->getDynDomainName())
{ {
m_domain = pref->getDynDomainName(); m_domain = pref->getDynDomainName();
const QRegularExpressionMatch domainRegexMatch = QRegularExpression("^(?:(?!\\d|-)[a-zA-Z0-9\\-]{1,63}\\.)+[a-zA-Z]{2,}$").match(m_domain); const QRegularExpressionMatch domainRegexMatch = QRegularExpression(u"^(?:(?!\\d|-)[a-zA-Z0-9\\-]{1,63}\\.)+[a-zA-Z]{2,}$"_qs).match(m_domain);
if (!domainRegexMatch.hasMatch()) if (!domainRegexMatch.hasMatch())
{ {
logger->addMessage(tr("Dynamic DNS error: supplied domain name is invalid."), Log::CRITICAL); logger->addMessage(tr("Dynamic DNS error: supplied domain name is invalid."), Log::CRITICAL);
@ -301,9 +302,9 @@ QUrl DNSUpdater::getRegistrationUrl(const DNS::Service service)
switch (service) switch (service)
{ {
case DNS::Service::DynDNS: case DNS::Service::DynDNS:
return {"https://account.dyn.com/entrance/"}; return {u"https://account.dyn.com/entrance/"_qs};
case DNS::Service::NoIP: case DNS::Service::NoIP:
return {"https://www.noip.com/remote-access"}; return {u"https://www.noip.com/remote-access"_qs};
default: default:
Q_ASSERT(false); Q_ASSERT(false);
break; break;

View file

@ -183,7 +183,7 @@ void DownloadHandlerImpl::handleRedirection(const QUrl &newUrl)
qDebug("Redirecting from %s to %s...", qUtf8Printable(m_reply->url().toString()), qUtf8Printable(newUrlString)); qDebug("Redirecting from %s to %s...", qUtf8Printable(m_reply->url().toString()), qUtf8Printable(newUrlString));
// Redirect to magnet workaround // Redirect to magnet workaround
if (newUrlString.startsWith("magnet:", Qt::CaseInsensitive)) if (newUrlString.startsWith(u"magnet:", Qt::CaseInsensitive))
{ {
qDebug("Magnet redirect detected."); qDebug("Magnet redirect detected.");
m_result.status = Net::DownloadStatus::RedirectedToMagnet; m_result.status = Net::DownloadStatus::RedirectedToMagnet;

View file

@ -293,7 +293,7 @@ void Net::DownloadManager::ignoreSslErrors(QNetworkReply *reply, const QList<QSs
QStringList errorList; QStringList errorList;
for (const QSslError &error : errors) for (const QSslError &error : errors)
errorList += error.errorString(); errorList += error.errorString();
LogMsg(tr("Ignoring SSL error, URL: \"%1\", errors: \"%2\"").arg(reply->url().toString(), errorList.join(". ")), Log::WARNING); LogMsg(tr("Ignoring SSL error, URL: \"%1\", errors: \"%2\"").arg(reply->url().toString(), errorList.join(u". ")), Log::WARNING);
// Ignore all SSL errors // Ignore all SSL errors
reply->ignoreSslErrors(); reply->ignoreSslErrors();

View file

@ -34,6 +34,7 @@
#include <QHostAddress> #include <QHostAddress>
#include <QVariant> #include <QVariant>
#include "base/global.h"
#include "base/path.h" #include "base/path.h"
namespace namespace
@ -197,7 +198,7 @@ QString GeoIPDatabase::lookup(const QHostAddress &hostAddr) const
const QVariant val = readDataField(tmp); const QVariant val = readDataField(tmp);
if (val.userType() == QMetaType::QVariantHash) if (val.userType() == QMetaType::QVariantHash)
{ {
country = val.toHash()["country"].toHash()["iso_code"].toString(); country = val.toHash()[u"country"_qs].toHash()[u"iso_code"_qs].toString();
m_countries[id] = country; m_countries[id] = country;
} }
} }
@ -212,23 +213,23 @@ QString GeoIPDatabase::lookup(const QHostAddress &hostAddr) const
} }
#define CHECK_METADATA_REQ(key, type) \ #define CHECK_METADATA_REQ(key, type) \
if (!metadata.contains(#key)) \ if (!metadata.contains(key)) \
{ \ { \
error = errMsgNotFound.arg(#key); \ error = errMsgNotFound.arg(key); \
return false; \ return false; \
} \ } \
if (metadata.value(#key).userType() != QMetaType::type) \ if (metadata.value(key).userType() != QMetaType::type) \
{ \ { \
error = errMsgInvalid.arg(#key); \ error = errMsgInvalid.arg(key); \
return false; \ return false; \
} }
#define CHECK_METADATA_OPT(key, type) \ #define CHECK_METADATA_OPT(key, type) \
if (metadata.contains(#key)) \ if (metadata.contains(key)) \
{ \ { \
if (metadata.value(#key).userType() != QMetaType::type) \ if (metadata.value(key).userType() != QMetaType::type) \
{ \ { \
error = errMsgInvalid.arg(#key); \ error = errMsgInvalid.arg(key); \
return false; \ return false; \
} \ } \
} }
@ -240,26 +241,26 @@ bool GeoIPDatabase::parseMetadata(const QVariantHash &metadata, QString &error)
qDebug() << "Parsing MaxMindDB metadata..."; qDebug() << "Parsing MaxMindDB metadata...";
CHECK_METADATA_REQ(binary_format_major_version, UShort); CHECK_METADATA_REQ(u"binary_format_major_version"_qs, UShort);
CHECK_METADATA_REQ(binary_format_minor_version, UShort); CHECK_METADATA_REQ(u"binary_format_minor_version"_qs, UShort);
const uint versionMajor = metadata.value("binary_format_major_version").toUInt(); const uint versionMajor = metadata.value(u"binary_format_major_version"_qs).toUInt();
const uint versionMinor = metadata.value("binary_format_minor_version").toUInt(); const uint versionMinor = metadata.value(u"binary_format_minor_version"_qs).toUInt();
if (versionMajor != 2) if (versionMajor != 2)
{ {
error = tr("Unsupported database version: %1.%2").arg(versionMajor).arg(versionMinor); error = tr("Unsupported database version: %1.%2").arg(versionMajor).arg(versionMinor);
return false; return false;
} }
CHECK_METADATA_REQ(ip_version, UShort); CHECK_METADATA_REQ(u"ip_version"_qs, UShort);
m_ipVersion = metadata.value("ip_version").value<quint16>(); m_ipVersion = metadata.value(u"ip_version"_qs).value<quint16>();
if (m_ipVersion != 6) if (m_ipVersion != 6)
{ {
error = tr("Unsupported IP version: %1").arg(m_ipVersion); error = tr("Unsupported IP version: %1").arg(m_ipVersion);
return false; return false;
} }
CHECK_METADATA_REQ(record_size, UShort); CHECK_METADATA_REQ(u"record_size"_qs, UShort);
m_recordSize = metadata.value("record_size").value<quint16>(); m_recordSize = metadata.value(u"record_size"_qs).value<quint16>();
if (m_recordSize != 24) if (m_recordSize != 24)
{ {
error = tr("Unsupported record size: %1").arg(m_recordSize); error = tr("Unsupported record size: %1").arg(m_recordSize);
@ -268,18 +269,18 @@ bool GeoIPDatabase::parseMetadata(const QVariantHash &metadata, QString &error)
m_nodeSize = m_recordSize / 4; m_nodeSize = m_recordSize / 4;
m_recordBytes = m_nodeSize / 2; m_recordBytes = m_nodeSize / 2;
CHECK_METADATA_REQ(node_count, UInt); CHECK_METADATA_REQ(u"node_count"_qs, UInt);
m_nodeCount = metadata.value("node_count").value<quint32>(); m_nodeCount = metadata.value(u"node_count"_qs).value<quint32>();
m_indexSize = m_nodeCount * m_nodeSize; m_indexSize = m_nodeCount * m_nodeSize;
CHECK_METADATA_REQ(database_type, QString); CHECK_METADATA_REQ(u"database_type"_qs, QString);
m_dbType = metadata.value("database_type").toString(); m_dbType = metadata.value(u"database_type"_qs).toString();
CHECK_METADATA_REQ(build_epoch, ULongLong); CHECK_METADATA_REQ(u"build_epoch"_qs, ULongLong);
m_buildEpoch = QDateTime::fromSecsSinceEpoch(metadata.value("build_epoch").toULongLong()); m_buildEpoch = QDateTime::fromSecsSinceEpoch(metadata.value(u"build_epoch"_qs).toULongLong());
CHECK_METADATA_OPT(languages, QVariantList); CHECK_METADATA_OPT(u"languages"_qs, QVariantList);
CHECK_METADATA_OPT(description, QVariantHash); CHECK_METADATA_OPT(u"description"_qs, QVariantHash);
return true; return true;
} }

View file

@ -130,7 +130,7 @@ void GeoIPManager::manageDatabaseUpdate()
void GeoIPManager::downloadDatabaseFile() void GeoIPManager::downloadDatabaseFile()
{ {
const QDateTime curDatetime = QDateTime::currentDateTimeUtc(); const QDateTime curDatetime = QDateTime::currentDateTimeUtc();
const QString curUrl = DATABASE_URL.arg(QLocale::c().toString(curDatetime, "yyyy-MM")); const QString curUrl = DATABASE_URL.arg(QLocale::c().toString(curDatetime, u"yyyy-MM"));
DownloadManager::instance()->download({curUrl}, this, &GeoIPManager::downloadFinished); DownloadManager::instance()->download({curUrl}, this, &GeoIPManager::downloadFinished);
} }
@ -150,255 +150,255 @@ QString GeoIPManager::CountryName(const QString &countryISOCode)
// http://www.iso.org/iso/home/standards/country_codes/country_names_and_code_elements_txt-temp.htm // http://www.iso.org/iso/home/standards/country_codes/country_names_and_code_elements_txt-temp.htm
// Officially assigned // Officially assigned
{"AD", tr("Andorra")}, {u"AD"_qs, tr("Andorra")},
{"AE", tr("United Arab Emirates")}, {u"AE"_qs, tr("United Arab Emirates")},
{"AF", tr("Afghanistan")}, {u"AF"_qs, tr("Afghanistan")},
{"AG", tr("Antigua and Barbuda")}, {u"AG"_qs, tr("Antigua and Barbuda")},
{"AI", tr("Anguilla")}, {u"AI"_qs, tr("Anguilla")},
{"AL", tr("Albania")}, {u"AL"_qs, tr("Albania")},
{"AM", tr("Armenia")}, {u"AM"_qs, tr("Armenia")},
{"AO", tr("Angola")}, {u"AO"_qs, tr("Angola")},
{"AQ", tr("Antarctica")}, {u"AQ"_qs, tr("Antarctica")},
{"AR", tr("Argentina")}, {u"AR"_qs, tr("Argentina")},
{"AS", tr("American Samoa")}, {u"AS"_qs, tr("American Samoa")},
{"AT", tr("Austria")}, {u"AT"_qs, tr("Austria")},
{"AU", tr("Australia")}, {u"AU"_qs, tr("Australia")},
{"AW", tr("Aruba")}, {u"AW"_qs, tr("Aruba")},
{"AX", tr("Aland Islands")}, {u"AX"_qs, tr("Aland Islands")},
{"AZ", tr("Azerbaijan")}, {u"AZ"_qs, tr("Azerbaijan")},
{"BA", tr("Bosnia and Herzegovina")}, {u"BA"_qs, tr("Bosnia and Herzegovina")},
{"BB", tr("Barbados")}, {u"BB"_qs, tr("Barbados")},
{"BD", tr("Bangladesh")}, {u"BD"_qs, tr("Bangladesh")},
{"BE", tr("Belgium")}, {u"BE"_qs, tr("Belgium")},
{"BF", tr("Burkina Faso")}, {u"BF"_qs, tr("Burkina Faso")},
{"BG", tr("Bulgaria")}, {u"BG"_qs, tr("Bulgaria")},
{"BH", tr("Bahrain")}, {u"BH"_qs, tr("Bahrain")},
{"BI", tr("Burundi")}, {u"BI"_qs, tr("Burundi")},
{"BJ", tr("Benin")}, {u"BJ"_qs, tr("Benin")},
{"BL", tr("Saint Barthelemy")}, {u"BL"_qs, tr("Saint Barthelemy")},
{"BM", tr("Bermuda")}, {u"BM"_qs, tr("Bermuda")},
{"BN", tr("Brunei Darussalam")}, {u"BN"_qs, tr("Brunei Darussalam")},
{"BO", tr("Bolivia, Plurinational State of")}, {u"BO"_qs, tr("Bolivia, Plurinational State of")},
{"BQ", tr("Bonaire, Sint Eustatius and Saba")}, {u"BQ"_qs, tr("Bonaire, Sint Eustatius and Saba")},
{"BR", tr("Brazil")}, {u"BR"_qs, tr("Brazil")},
{"BS", tr("Bahamas")}, {u"BS"_qs, tr("Bahamas")},
{"BT", tr("Bhutan")}, {u"BT"_qs, tr("Bhutan")},
{"BV", tr("Bouvet Island")}, {u"BV"_qs, tr("Bouvet Island")},
{"BW", tr("Botswana")}, {u"BW"_qs, tr("Botswana")},
{"BY", tr("Belarus")}, {u"BY"_qs, tr("Belarus")},
{"BZ", tr("Belize")}, {u"BZ"_qs, tr("Belize")},
{"CA", tr("Canada")}, {u"CA"_qs, tr("Canada")},
{"CC", tr("Cocos (Keeling) Islands")}, {u"CC"_qs, tr("Cocos (Keeling) Islands")},
{"CD", tr("Congo, The Democratic Republic of the")}, {u"CD"_qs, tr("Congo, The Democratic Republic of the")},
{"CF", tr("Central African Republic")}, {u"CF"_qs, tr("Central African Republic")},
{"CG", tr("Congo")}, {u"CG"_qs, tr("Congo")},
{"CH", tr("Switzerland")}, {u"CH"_qs, tr("Switzerland")},
{"CI", tr("Cote d'Ivoire")}, {u"CI"_qs, tr("Cote d'Ivoire")},
{"CK", tr("Cook Islands")}, {u"CK"_qs, tr("Cook Islands")},
{"CL", tr("Chile")}, {u"CL"_qs, tr("Chile")},
{"CM", tr("Cameroon")}, {u"CM"_qs, tr("Cameroon")},
{"CN", tr("China")}, {u"CN"_qs, tr("China")},
{"CO", tr("Colombia")}, {u"CO"_qs, tr("Colombia")},
{"CR", tr("Costa Rica")}, {u"CR"_qs, tr("Costa Rica")},
{"CU", tr("Cuba")}, {u"CU"_qs, tr("Cuba")},
{"CV", tr("Cape Verde")}, {u"CV"_qs, tr("Cape Verde")},
{"CW", tr("Curacao")}, {u"CW"_qs, tr("Curacao")},
{"CX", tr("Christmas Island")}, {u"CX"_qs, tr("Christmas Island")},
{"CY", tr("Cyprus")}, {u"CY"_qs, tr("Cyprus")},
{"CZ", tr("Czech Republic")}, {u"CZ"_qs, tr("Czech Republic")},
{"DE", tr("Germany")}, {u"DE"_qs, tr("Germany")},
{"DJ", tr("Djibouti")}, {u"DJ"_qs, tr("Djibouti")},
{"DK", tr("Denmark")}, {u"DK"_qs, tr("Denmark")},
{"DM", tr("Dominica")}, {u"DM"_qs, tr("Dominica")},
{"DO", tr("Dominican Republic")}, {u"DO"_qs, tr("Dominican Republic")},
{"DZ", tr("Algeria")}, {u"DZ"_qs, tr("Algeria")},
{"EC", tr("Ecuador")}, {u"EC"_qs, tr("Ecuador")},
{"EE", tr("Estonia")}, {u"EE"_qs, tr("Estonia")},
{"EG", tr("Egypt")}, {u"EG"_qs, tr("Egypt")},
{"EH", tr("Western Sahara")}, {u"EH"_qs, tr("Western Sahara")},
{"ER", tr("Eritrea")}, {u"ER"_qs, tr("Eritrea")},
{"ES", tr("Spain")}, {u"ES"_qs, tr("Spain")},
{"ET", tr("Ethiopia")}, {u"ET"_qs, tr("Ethiopia")},
{"FI", tr("Finland")}, {u"FI"_qs, tr("Finland")},
{"FJ", tr("Fiji")}, {u"FJ"_qs, tr("Fiji")},
{"FK", tr("Falkland Islands (Malvinas)")}, {u"FK"_qs, tr("Falkland Islands (Malvinas)")},
{"FM", tr("Micronesia, Federated States of")}, {u"FM"_qs, tr("Micronesia, Federated States of")},
{"FO", tr("Faroe Islands")}, {u"FO"_qs, tr("Faroe Islands")},
{"FR", tr("France")}, {u"FR"_qs, tr("France")},
{"GA", tr("Gabon")}, {u"GA"_qs, tr("Gabon")},
{"GB", tr("United Kingdom")}, {u"GB"_qs, tr("United Kingdom")},
{"GD", tr("Grenada")}, {u"GD"_qs, tr("Grenada")},
{"GE", tr("Georgia")}, {u"GE"_qs, tr("Georgia")},
{"GF", tr("French Guiana")}, {u"GF"_qs, tr("French Guiana")},
{"GG", tr("Guernsey")}, {u"GG"_qs, tr("Guernsey")},
{"GH", tr("Ghana")}, {u"GH"_qs, tr("Ghana")},
{"GI", tr("Gibraltar")}, {u"GI"_qs, tr("Gibraltar")},
{"GL", tr("Greenland")}, {u"GL"_qs, tr("Greenland")},
{"GM", tr("Gambia")}, {u"GM"_qs, tr("Gambia")},
{"GN", tr("Guinea")}, {u"GN"_qs, tr("Guinea")},
{"GP", tr("Guadeloupe")}, {u"GP"_qs, tr("Guadeloupe")},
{"GQ", tr("Equatorial Guinea")}, {u"GQ"_qs, tr("Equatorial Guinea")},
{"GR", tr("Greece")}, {u"GR"_qs, tr("Greece")},
{"GS", tr("South Georgia and the South Sandwich Islands")}, {u"GS"_qs, tr("South Georgia and the South Sandwich Islands")},
{"GT", tr("Guatemala")}, {u"GT"_qs, tr("Guatemala")},
{"GU", tr("Guam")}, {u"GU"_qs, tr("Guam")},
{"GW", tr("Guinea-Bissau")}, {u"GW"_qs, tr("Guinea-Bissau")},
{"GY", tr("Guyana")}, {u"GY"_qs, tr("Guyana")},
{"HK", tr("Hong Kong")}, {u"HK"_qs, tr("Hong Kong")},
{"HM", tr("Heard Island and McDonald Islands")}, {u"HM"_qs, tr("Heard Island and McDonald Islands")},
{"HN", tr("Honduras")}, {u"HN"_qs, tr("Honduras")},
{"HR", tr("Croatia")}, {u"HR"_qs, tr("Croatia")},
{"HT", tr("Haiti")}, {u"HT"_qs, tr("Haiti")},
{"HU", tr("Hungary")}, {u"HU"_qs, tr("Hungary")},
{"ID", tr("Indonesia")}, {u"ID"_qs, tr("Indonesia")},
{"IE", tr("Ireland")}, {u"IE"_qs, tr("Ireland")},
{"IL", tr("Israel")}, {u"IL"_qs, tr("Israel")},
{"IM", tr("Isle of Man")}, {u"IM"_qs, tr("Isle of Man")},
{"IN", tr("India")}, {u"IN"_qs, tr("India")},
{"IO", tr("British Indian Ocean Territory")}, {u"IO"_qs, tr("British Indian Ocean Territory")},
{"IQ", tr("Iraq")}, {u"IQ"_qs, tr("Iraq")},
{"IR", tr("Iran, Islamic Republic of")}, {u"IR"_qs, tr("Iran, Islamic Republic of")},
{"IS", tr("Iceland")}, {u"IS"_qs, tr("Iceland")},
{"IT", tr("Italy")}, {u"IT"_qs, tr("Italy")},
{"JE", tr("Jersey")}, {u"JE"_qs, tr("Jersey")},
{"JM", tr("Jamaica")}, {u"JM"_qs, tr("Jamaica")},
{"JO", tr("Jordan")}, {u"JO"_qs, tr("Jordan")},
{"JP", tr("Japan")}, {u"JP"_qs, tr("Japan")},
{"KE", tr("Kenya")}, {u"KE"_qs, tr("Kenya")},
{"KG", tr("Kyrgyzstan")}, {u"KG"_qs, tr("Kyrgyzstan")},
{"KH", tr("Cambodia")}, {u"KH"_qs, tr("Cambodia")},
{"KI", tr("Kiribati")}, {u"KI"_qs, tr("Kiribati")},
{"KM", tr("Comoros")}, {u"KM"_qs, tr("Comoros")},
{"KN", tr("Saint Kitts and Nevis")}, {u"KN"_qs, tr("Saint Kitts and Nevis")},
{"KP", tr("Korea, Democratic People's Republic of")}, {u"KP"_qs, tr("Korea, Democratic People's Republic of")},
{"KR", tr("Korea, Republic of")}, {u"KR"_qs, tr("Korea, Republic of")},
{"KW", tr("Kuwait")}, {u"KW"_qs, tr("Kuwait")},
{"KY", tr("Cayman Islands")}, {u"KY"_qs, tr("Cayman Islands")},
{"KZ", tr("Kazakhstan")}, {u"KZ"_qs, tr("Kazakhstan")},
{"LA", tr("Lao People's Democratic Republic")}, {u"LA"_qs, tr("Lao People's Democratic Republic")},
{"LB", tr("Lebanon")}, {u"LB"_qs, tr("Lebanon")},
{"LC", tr("Saint Lucia")}, {u"LC"_qs, tr("Saint Lucia")},
{"LI", tr("Liechtenstein")}, {u"LI"_qs, tr("Liechtenstein")},
{"LK", tr("Sri Lanka")}, {u"LK"_qs, tr("Sri Lanka")},
{"LR", tr("Liberia")}, {u"LR"_qs, tr("Liberia")},
{"LS", tr("Lesotho")}, {u"LS"_qs, tr("Lesotho")},
{"LT", tr("Lithuania")}, {u"LT"_qs, tr("Lithuania")},
{"LU", tr("Luxembourg")}, {u"LU"_qs, tr("Luxembourg")},
{"LV", tr("Latvia")}, {u"LV"_qs, tr("Latvia")},
{"LY", tr("Libya")}, {u"LY"_qs, tr("Libya")},
{"MA", tr("Morocco")}, {u"MA"_qs, tr("Morocco")},
{"MC", tr("Monaco")}, {u"MC"_qs, tr("Monaco")},
{"MD", tr("Moldova, Republic of")}, {u"MD"_qs, tr("Moldova, Republic of")},
{"ME", tr("Montenegro")}, {u"ME"_qs, tr("Montenegro")},
{"MF", tr("Saint Martin (French part)")}, {u"MF"_qs, tr("Saint Martin (French part)")},
{"MG", tr("Madagascar")}, {u"MG"_qs, tr("Madagascar")},
{"MH", tr("Marshall Islands")}, {u"MH"_qs, tr("Marshall Islands")},
{"MK", tr("Macedonia, The Former Yugoslav Republic of")}, {u"MK"_qs, tr("Macedonia, The Former Yugoslav Republic of")},
{"ML", tr("Mali")}, {u"ML"_qs, tr("Mali")},
{"MM", tr("Myanmar")}, {u"MM"_qs, tr("Myanmar")},
{"MN", tr("Mongolia")}, {u"MN"_qs, tr("Mongolia")},
{"MO", tr("Macao")}, {u"MO"_qs, tr("Macao")},
{"MP", tr("Northern Mariana Islands")}, {u"MP"_qs, tr("Northern Mariana Islands")},
{"MQ", tr("Martinique")}, {u"MQ"_qs, tr("Martinique")},
{"MR", tr("Mauritania")}, {u"MR"_qs, tr("Mauritania")},
{"MS", tr("Montserrat")}, {u"MS"_qs, tr("Montserrat")},
{"MT", tr("Malta")}, {u"MT"_qs, tr("Malta")},
{"MU", tr("Mauritius")}, {u"MU"_qs, tr("Mauritius")},
{"MV", tr("Maldives")}, {u"MV"_qs, tr("Maldives")},
{"MW", tr("Malawi")}, {u"MW"_qs, tr("Malawi")},
{"MX", tr("Mexico")}, {u"MX"_qs, tr("Mexico")},
{"MY", tr("Malaysia")}, {u"MY"_qs, tr("Malaysia")},
{"MZ", tr("Mozambique")}, {u"MZ"_qs, tr("Mozambique")},
{"NA", tr("Namibia")}, {u"NA"_qs, tr("Namibia")},
{"NC", tr("New Caledonia")}, {u"NC"_qs, tr("New Caledonia")},
{"NE", tr("Niger")}, {u"NE"_qs, tr("Niger")},
{"NF", tr("Norfolk Island")}, {u"NF"_qs, tr("Norfolk Island")},
{"NG", tr("Nigeria")}, {u"NG"_qs, tr("Nigeria")},
{"NI", tr("Nicaragua")}, {u"NI"_qs, tr("Nicaragua")},
{"NL", tr("Netherlands")}, {u"NL"_qs, tr("Netherlands")},
{"NO", tr("Norway")}, {u"NO"_qs, tr("Norway")},
{"NP", tr("Nepal")}, {u"NP"_qs, tr("Nepal")},
{"NR", tr("Nauru")}, {u"NR"_qs, tr("Nauru")},
{"NU", tr("Niue")}, {u"NU"_qs, tr("Niue")},
{"NZ", tr("New Zealand")}, {u"NZ"_qs, tr("New Zealand")},
{"OM", tr("Oman")}, {u"OM"_qs, tr("Oman")},
{"PA", tr("Panama")}, {u"PA"_qs, tr("Panama")},
{"PE", tr("Peru")}, {u"PE"_qs, tr("Peru")},
{"PF", tr("French Polynesia")}, {u"PF"_qs, tr("French Polynesia")},
{"PG", tr("Papua New Guinea")}, {u"PG"_qs, tr("Papua New Guinea")},
{"PH", tr("Philippines")}, {u"PH"_qs, tr("Philippines")},
{"PK", tr("Pakistan")}, {u"PK"_qs, tr("Pakistan")},
{"PL", tr("Poland")}, {u"PL"_qs, tr("Poland")},
{"PM", tr("Saint Pierre and Miquelon")}, {u"PM"_qs, tr("Saint Pierre and Miquelon")},
{"PN", tr("Pitcairn")}, {u"PN"_qs, tr("Pitcairn")},
{"PR", tr("Puerto Rico")}, {u"PR"_qs, tr("Puerto Rico")},
{"PS", tr("Palestine, State of")}, {u"PS"_qs, tr("Palestine, State of")},
{"PT", tr("Portugal")}, {u"PT"_qs, tr("Portugal")},
{"PW", tr("Palau")}, {u"PW"_qs, tr("Palau")},
{"PY", tr("Paraguay")}, {u"PY"_qs, tr("Paraguay")},
{"QA", tr("Qatar")}, {u"QA"_qs, tr("Qatar")},
{"RE", tr("Reunion")}, {u"RE"_qs, tr("Reunion")},
{"RO", tr("Romania")}, {u"RO"_qs, tr("Romania")},
{"RS", tr("Serbia")}, {u"RS"_qs, tr("Serbia")},
{"RU", tr("Russian Federation")}, {u"RU"_qs, tr("Russian Federation")},
{"RW", tr("Rwanda")}, {u"RW"_qs, tr("Rwanda")},
{"SA", tr("Saudi Arabia")}, {u"SA"_qs, tr("Saudi Arabia")},
{"SB", tr("Solomon Islands")}, {u"SB"_qs, tr("Solomon Islands")},
{"SC", tr("Seychelles")}, {u"SC"_qs, tr("Seychelles")},
{"SD", tr("Sudan")}, {u"SD"_qs, tr("Sudan")},
{"SE", tr("Sweden")}, {u"SE"_qs, tr("Sweden")},
{"SG", tr("Singapore")}, {u"SG"_qs, tr("Singapore")},
{"SH", tr("Saint Helena, Ascension and Tristan da Cunha")}, {u"SH"_qs, tr("Saint Helena, Ascension and Tristan da Cunha")},
{"SI", tr("Slovenia")}, {u"SI"_qs, tr("Slovenia")},
{"SJ", tr("Svalbard and Jan Mayen")}, {u"SJ"_qs, tr("Svalbard and Jan Mayen")},
{"SK", tr("Slovakia")}, {u"SK"_qs, tr("Slovakia")},
{"SL", tr("Sierra Leone")}, {u"SL"_qs, tr("Sierra Leone")},
{"SM", tr("San Marino")}, {u"SM"_qs, tr("San Marino")},
{"SN", tr("Senegal")}, {u"SN"_qs, tr("Senegal")},
{"SO", tr("Somalia")}, {u"SO"_qs, tr("Somalia")},
{"SR", tr("Suriname")}, {u"SR"_qs, tr("Suriname")},
{"SS", tr("South Sudan")}, {u"SS"_qs, tr("South Sudan")},
{"ST", tr("Sao Tome and Principe")}, {u"ST"_qs, tr("Sao Tome and Principe")},
{"SV", tr("El Salvador")}, {u"SV"_qs, tr("El Salvador")},
{"SX", tr("Sint Maarten (Dutch part)")}, {u"SX"_qs, tr("Sint Maarten (Dutch part)")},
{"SY", tr("Syrian Arab Republic")}, {u"SY"_qs, tr("Syrian Arab Republic")},
{"SZ", tr("Swaziland")}, {u"SZ"_qs, tr("Swaziland")},
{"TC", tr("Turks and Caicos Islands")}, {u"TC"_qs, tr("Turks and Caicos Islands")},
{"TD", tr("Chad")}, {u"TD"_qs, tr("Chad")},
{"TF", tr("French Southern Territories")}, {u"TF"_qs, tr("French Southern Territories")},
{"TG", tr("Togo")}, {u"TG"_qs, tr("Togo")},
{"TH", tr("Thailand")}, {u"TH"_qs, tr("Thailand")},
{"TJ", tr("Tajikistan")}, {u"TJ"_qs, tr("Tajikistan")},
{"TK", tr("Tokelau")}, {u"TK"_qs, tr("Tokelau")},
{"TL", tr("Timor-Leste")}, {u"TL"_qs, tr("Timor-Leste")},
{"TM", tr("Turkmenistan")}, {u"TM"_qs, tr("Turkmenistan")},
{"TN", tr("Tunisia")}, {u"TN"_qs, tr("Tunisia")},
{"TO", tr("Tonga")}, {u"TO"_qs, tr("Tonga")},
{"TR", tr("Turkey")}, {u"TR"_qs, tr("Turkey")},
{"TT", tr("Trinidad and Tobago")}, {u"TT"_qs, tr("Trinidad and Tobago")},
{"TV", tr("Tuvalu")}, {u"TV"_qs, tr("Tuvalu")},
{"TW", tr("Taiwan")}, {u"TW"_qs, tr("Taiwan")},
{"TZ", tr("Tanzania, United Republic of")}, {u"TZ"_qs, tr("Tanzania, United Republic of")},
{"UA", tr("Ukraine")}, {u"UA"_qs, tr("Ukraine")},
{"UG", tr("Uganda")}, {u"UG"_qs, tr("Uganda")},
{"UM", tr("United States Minor Outlying Islands")}, {u"UM"_qs, tr("United States Minor Outlying Islands")},
{"US", tr("United States")}, {u"US"_qs, tr("United States")},
{"UY", tr("Uruguay")}, {u"UY"_qs, tr("Uruguay")},
{"UZ", tr("Uzbekistan")}, {u"UZ"_qs, tr("Uzbekistan")},
{"VA", tr("Holy See (Vatican City State)")}, {u"VA"_qs, tr("Holy See (Vatican City State)")},
{"VC", tr("Saint Vincent and the Grenadines")}, {u"VC"_qs, tr("Saint Vincent and the Grenadines")},
{"VE", tr("Venezuela, Bolivarian Republic of")}, {u"VE"_qs, tr("Venezuela, Bolivarian Republic of")},
{"VG", tr("Virgin Islands, British")}, {u"VG"_qs, tr("Virgin Islands, British")},
{"VI", tr("Virgin Islands, U.S.")}, {u"VI"_qs, tr("Virgin Islands, U.S.")},
{"VN", tr("Vietnam")}, {u"VN"_qs, tr("Vietnam")},
{"VU", tr("Vanuatu")}, {u"VU"_qs, tr("Vanuatu")},
{"WF", tr("Wallis and Futuna")}, {u"WF"_qs, tr("Wallis and Futuna")},
{"WS", tr("Samoa")}, {u"WS"_qs, tr("Samoa")},
{"YE", tr("Yemen")}, {u"YE"_qs, tr("Yemen")},
{"YT", tr("Mayotte")}, {u"YT"_qs, tr("Mayotte")},
{"ZA", tr("South Africa")}, {u"ZA"_qs, tr("South Africa")},
{"ZM", tr("Zambia")}, {u"ZM"_qs, tr("Zambia")},
{"ZW", tr("Zimbabwe")}, {u"ZW"_qs, tr("Zimbabwe")},
{{}, tr("N/A")} {{}, tr("N/A")}
}; };

View file

@ -30,6 +30,7 @@
#include <QObject> #include <QObject>
#include "base/global.h"
#include "base/settingvalue.h" #include "base/settingvalue.h"
namespace Net namespace Net
@ -50,7 +51,7 @@ namespace Net
struct ProxyConfiguration struct ProxyConfiguration
{ {
ProxyType type = ProxyType::None; ProxyType type = ProxyType::None;
QString ip = "0.0.0.0"; QString ip = u"0.0.0.0"_qs;
ushort port = 8080; ushort port = 8080;
QString username; QString username;
QString password; QString password;

View file

@ -84,7 +84,7 @@ namespace
{ {
QString hostname = QHostInfo::localHostName(); QString hostname = QHostInfo::localHostName();
if (hostname.isEmpty()) if (hostname.isEmpty())
hostname = "localhost"; hostname = u"localhost"_qs;
return hostname.toLocal8Bit(); return hostname.toLocal8Bit();
} }
@ -140,16 +140,16 @@ void Smtp::sendMail(const QString &from, const QString &to, const QString &subje
{ {
const Preferences *const pref = Preferences::instance(); const Preferences *const pref = Preferences::instance();
m_message = "Date: " + getCurrentDateTime().toLatin1() + "\r\n" m_message = "Date: " + getCurrentDateTime().toLatin1() + "\r\n"
+ encodeMimeHeader("From", from) + encodeMimeHeader(u"From"_qs, from)
+ encodeMimeHeader("Subject", subject) + encodeMimeHeader(u"Subject"_qs, subject)
+ encodeMimeHeader("To", to) + encodeMimeHeader(u"To"_qs, to)
+ "MIME-Version: 1.0\r\n" + "MIME-Version: 1.0\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n" + "Content-Type: text/plain; charset=UTF-8\r\n"
+ "Content-Transfer-Encoding: base64\r\n" + "Content-Transfer-Encoding: base64\r\n"
+ "\r\n"; + "\r\n";
// Encode the body in base64 // Encode the body in base64
QString crlfBody = body; QString crlfBody = body;
const QByteArray b = crlfBody.replace("\n", "\r\n").toUtf8().toBase64(); const QByteArray b = crlfBody.replace(u"\n"_qs, u"\r\n"_qs).toUtf8().toBase64();
const int ct = b.length(); const int ct = b.length();
for (int i = 0; i < ct; i += 78) for (int i = 0; i < ct; i += 78)
m_message += b.mid(i, 78); m_message += b.mid(i, 78);
@ -208,14 +208,14 @@ void Smtp::readyRead()
} }
else else
{ {
logError(QLatin1String("Connection failed, unrecognized reply: ") + line); logError(tr("Connection failed, unrecognized reply: %1").arg(QString::fromUtf8(line)));
m_state = Close; m_state = Close;
} }
break; break;
case EhloSent: case EhloSent:
case HeloSent: case HeloSent:
case EhloGreetReceived: case EhloGreetReceived:
parseEhloResponse(code, line[3] != ' ', line.mid(4)); parseEhloResponse(code, (line[3] != ' '), line.mid(4));
break; break;
#ifndef QT_NO_OPENSSL #ifndef QT_NO_OPENSSL
case StartTLSSent: case StartTLSSent:
@ -248,7 +248,7 @@ void Smtp::readyRead()
else else
{ {
// Authentication failed! // Authentication failed!
logError(QLatin1String("Authentication failed, msg: ") + line); logError(tr("Authentication failed, msg: %1").arg(QString::fromUtf8(line)));
m_state = Close; m_state = Close;
} }
break; break;
@ -261,7 +261,7 @@ void Smtp::readyRead()
} }
else else
{ {
logError(QLatin1String("<mail from> was rejected by server, msg: ") + line); logError(tr("<mail from> was rejected by server, msg: %1").arg(QString::fromUtf8(line)));
m_state = Close; m_state = Close;
} }
break; break;
@ -274,7 +274,7 @@ void Smtp::readyRead()
} }
else else
{ {
logError(QLatin1String("<Rcpt to> was rejected by server, msg: ") + line); logError(tr("<Rcpt to> was rejected by server, msg: %1").arg(QString::fromUtf8(line)));
m_state = Close; m_state = Close;
} }
break; break;
@ -287,7 +287,7 @@ void Smtp::readyRead()
} }
else else
{ {
logError(QLatin1String("<data> was rejected by server, msg: ") + line); logError(tr("<data> was rejected by server, msg: %1").arg(QString::fromUtf8(line)));
m_state = Close; m_state = Close;
} }
break; break;
@ -301,7 +301,7 @@ void Smtp::readyRead()
} }
else else
{ {
logError(QLatin1String("Message was rejected by the server, error: ") + line); logError(tr("Message was rejected by the server, error: %1").arg(QString::fromUtf8(line)));
m_state = Close; m_state = Close;
} }
break; break;
@ -318,7 +318,7 @@ QByteArray Smtp::encodeMimeHeader(const QString &key, const QString &value, cons
QByteArray rv = ""; QByteArray rv = "";
QByteArray line = key.toLatin1() + ": "; QByteArray line = key.toLatin1() + ": ";
if (!prefix.isEmpty()) line += prefix; if (!prefix.isEmpty()) line += prefix;
if (!value.contains("=?") && canEncodeAsLatin1(value)) if (!value.contains(u"=?") && canEncodeAsLatin1(value))
{ {
bool firstWord = true; bool firstWord = true;
for (const QByteArray &word : asConst(value.toLatin1().split(' '))) for (const QByteArray &word : asConst(value.toLatin1().split(' ')))
@ -389,7 +389,7 @@ void Smtp::parseEhloResponse(const QByteArray &code, const bool continued, const
{ {
// Both EHLO and HELO failed, chances are this is NOT // Both EHLO and HELO failed, chances are this is NOT
// a SMTP server // a SMTP server
logError("Both EHLO and HELO failed, msg: " + line); logError(tr("Both EHLO and HELO failed, msg: %1").arg(line));
m_state = Close; m_state = Close;
} }
return; return;
@ -413,16 +413,16 @@ void Smtp::parseEhloResponse(const QByteArray &code, const bool continued, const
} }
else else
{ {
qDebug() << Q_FUNC_INFO << "Supported extension: " << line.section(' ', 0, 0).toUpper() qDebug() << Q_FUNC_INFO << "Supported extension: " << line.section(u' ', 0, 0).toUpper()
<< line.section(' ', 1); << line.section(u' ', 1);
m_extensions[line.section(' ', 0, 0).toUpper()] = line.section(' ', 1); m_extensions[line.section(u' ', 0, 0).toUpper()] = line.section(u' ', 1);
if (!continued) if (!continued)
m_state = EhloDone; m_state = EhloDone;
} }
if (m_state != EhloDone) return; if (m_state != EhloDone) return;
if (m_extensions.contains("STARTTLS") && m_useSsl) if (m_extensions.contains(u"STARTTLS"_qs) && m_useSsl)
{ {
qDebug() << "STARTTLS"; qDebug() << "STARTTLS";
startTLS(); startTLS();
@ -436,7 +436,7 @@ void Smtp::parseEhloResponse(const QByteArray &code, const bool continued, const
void Smtp::authenticate() void Smtp::authenticate()
{ {
qDebug() << Q_FUNC_INFO; qDebug() << Q_FUNC_INFO;
if (!m_extensions.contains("AUTH") || if (!m_extensions.contains(u"AUTH"_qs) ||
m_username.isEmpty() || m_password.isEmpty()) m_username.isEmpty() || m_password.isEmpty())
{ {
// Skip authentication // Skip authentication
@ -451,18 +451,18 @@ void Smtp::authenticate()
// AUTH extension is supported, check which // AUTH extension is supported, check which
// authentication modes are supported by // authentication modes are supported by
// the server // the server
const QStringList auth = m_extensions["AUTH"].toUpper().split(' ', Qt::SkipEmptyParts); const QStringList auth = m_extensions[u"AUTH"_qs].toUpper().split(u' ', Qt::SkipEmptyParts);
if (auth.contains("CRAM-MD5")) if (auth.contains(u"CRAM-MD5"))
{ {
qDebug() << "Using CRAM-MD5 authentication..."; qDebug() << "Using CRAM-MD5 authentication...";
authCramMD5(); authCramMD5();
} }
else if (auth.contains("PLAIN")) else if (auth.contains(u"PLAIN"))
{ {
qDebug() << "Using PLAIN authentication..."; qDebug() << "Using PLAIN authentication...";
authPlain(); authPlain();
} }
else if (auth.contains("LOGIN")) else if (auth.contains(u"LOGIN"))
{ {
qDebug() << "Using LOGIN authentication..."; qDebug() << "Using LOGIN authentication...";
authLogin(); authLogin();
@ -470,9 +470,9 @@ void Smtp::authenticate()
else else
{ {
// Skip authentication // Skip authentication
logError("The SMTP server does not seem to support any of the authentications modes " logError(tr("The SMTP server does not seem to support any of the authentications modes "
"we support [CRAM-MD5|PLAIN|LOGIN], skipping authentication, " "we support [CRAM-MD5|PLAIN|LOGIN], skipping authentication, "
"knowing it is likely to fail... Server Auth Modes: " + auth.join('|')); "knowing it is likely to fail... Server Auth Modes: %1").arg(auth.join(u'|')));
m_state = Authenticated; m_state = Authenticated;
// At this point the server will not send any response // At this point the server will not send any response
// So fill the buffer with a fake one to pass the tests // So fill the buffer with a fake one to pass the tests
@ -558,7 +558,7 @@ void Smtp::authLogin()
void Smtp::logError(const QString &msg) void Smtp::logError(const QString &msg)
{ {
qDebug() << "Email Notification Error:" << msg; qDebug() << "Email Notification Error:" << msg;
Logger::instance()->addMessage(tr("Email Notification Error:") + ' ' + msg, Log::CRITICAL); Logger::instance()->addMessage(tr("Email Notification Error: %1").arg(msg), Log::WARNING);
} }
QString Smtp::getCurrentDateTime() const QString Smtp::getCurrentDateTime() const
@ -568,7 +568,7 @@ QString Smtp::getCurrentDateTime() const
const QDate nowDate = nowDateTime.date(); const QDate nowDate = nowDateTime.date();
const QLocale eng(QLocale::English); const QLocale eng(QLocale::English);
const QString timeStr = nowDateTime.time().toString("HH:mm:ss"); const QString timeStr = nowDateTime.time().toString(u"HH:mm:ss");
const QString weekDayStr = eng.dayName(nowDate.dayOfWeek(), QLocale::ShortFormat); const QString weekDayStr = eng.dayName(nowDate.dayOfWeek(), QLocale::ShortFormat);
const QString dayStr = QString::number(nowDate.day()); const QString dayStr = QString::number(nowDate.day());
const QString monthStr = eng.monthName(nowDate.month(), QLocale::ShortFormat); const QString monthStr = eng.monthName(nowDate.month(), QLocale::ShortFormat);
@ -582,9 +582,9 @@ QString Smtp::getCurrentDateTime() const
// buf size = 11 to avoid format truncation warnings from snprintf // buf size = 11 to avoid format truncation warnings from snprintf
char buf[11] = {0}; char buf[11] = {0};
std::snprintf(buf, sizeof(buf), "%+05d", timeOffset); std::snprintf(buf, sizeof(buf), "%+05d", timeOffset);
const QString timeOffsetStr = buf; const auto timeOffsetStr = QString::fromUtf8(buf);
const QString ret = weekDayStr + ", " + dayStr + ' ' + monthStr + ' ' + yearStr + ' ' + timeStr + ' ' + timeOffsetStr; const QString ret = weekDayStr + u", " + dayStr + u' ' + monthStr + u' ' + yearStr + u' ' + timeStr + u' ' + timeOffsetStr;
return ret; return ret;
} }

View file

@ -129,7 +129,7 @@ Path Path::parentPath() const
QString Path::filename() const QString Path::filename() const
{ {
const int slashIndex = m_pathStr.lastIndexOf('/'); const int slashIndex = m_pathStr.lastIndexOf(u'/');
if (slashIndex == -1) if (slashIndex == -1)
return m_pathStr; return m_pathStr;

View file

@ -572,7 +572,7 @@ void Preferences::setWebUiAuthSubnetWhitelist(QStringList subnets)
QString Preferences::getServerDomains() const QString Preferences::getServerDomains() const
{ {
return value<QString>(u"Preferences/WebUI/ServerDomains"_qs, QChar('*')); return value<QString>(u"Preferences/WebUI/ServerDomains"_qs, u"*"_qs);
} }
void Preferences::setServerDomains(const QString &str) void Preferences::setServerDomains(const QString &str)
@ -582,7 +582,7 @@ void Preferences::setServerDomains(const QString &str)
QString Preferences::getWebUiAddress() const QString Preferences::getWebUiAddress() const
{ {
return value<QString>(u"Preferences/WebUI/Address"_qs, QChar('*')).trimmed(); return value<QString>(u"Preferences/WebUI/Address"_qs, u"*"_qs).trimmed();
} }
void Preferences::setWebUiAddress(const QString &addr) void Preferences::setWebUiAddress(const QString &addr)
@ -1614,7 +1614,7 @@ void Preferences::setNetworkCookies(const QList<QNetworkCookie> &cookies)
QStringList rawCookies; QStringList rawCookies;
rawCookies.reserve(cookies.size()); rawCookies.reserve(cookies.size());
for (const QNetworkCookie &cookie : cookies) for (const QNetworkCookie &cookie : cookies)
rawCookies << cookie.toRawForm(); rawCookies << QString::fromLatin1(cookie.toRawForm());
setValue(u"Network/Cookies"_qs, rawCookies); setValue(u"Network/Cookies"_qs, rawCookies);
} }

View file

@ -94,7 +94,7 @@ QPointer<AutoDownloader> AutoDownloader::m_instance = nullptr;
QString computeSmartFilterRegex(const QStringList &filters) QString computeSmartFilterRegex(const QStringList &filters)
{ {
return QString::fromLatin1("(?:_|\\b)(?:%1)(?:_|\\b)").arg(filters.join(QString(")|(?:"))); return u"(?:_|\\b)(?:%1)(?:_|\\b)"_qs.arg(filters.join(u")|(?:"));
} }
AutoDownloader::AutoDownloader() AutoDownloader::AutoDownloader()
@ -162,7 +162,7 @@ bool AutoDownloader::hasRule(const QString &ruleName) const
AutoDownloadRule AutoDownloader::ruleByName(const QString &ruleName) const AutoDownloadRule AutoDownloader::ruleByName(const QString &ruleName) const
{ {
return m_rules.value(ruleName, AutoDownloadRule("Unknown Rule")); return m_rules.value(ruleName, AutoDownloadRule(u"Unknown Rule"_qs));
} }
QList<AutoDownloadRule> AutoDownloader::rules() const QList<AutoDownloadRule> AutoDownloader::rules() const
@ -289,10 +289,10 @@ QStringList AutoDownloader::smartEpisodeFilters() const
{ {
const QStringList defaultFilters = const QStringList defaultFilters =
{ {
"s(\\d+)e(\\d+)", // Format 1: s01e01 u"s(\\d+)e(\\d+)"_qs, // Format 1: s01e01
"(\\d+)x(\\d+)", // Format 2: 01x01 u"(\\d+)x(\\d+)"_qs, // Format 2: 01x01
"(\\d{4}[.\\-]\\d{1,2}[.\\-]\\d{1,2})", // Format 3: 2017.01.01 u"(\\d{4}[.\\-]\\d{1,2}[.\\-]\\d{1,2})"_qs, // Format 3: 2017.01.01
"(\\d{1,2}[.\\-]\\d{1,2}[.\\-]\\d{4})" // Format 4: 01.01.2017 u"(\\d{1,2}[.\\-]\\d{1,2}[.\\-]\\d{4})"_qs // Format 4: 01.01.2017
}; };
return defaultFilters; return defaultFilters;
} }

View file

@ -188,7 +188,7 @@ QString computeEpisodeName(const QString &article)
ret.append(isInt ? QString::number(x) : cap); ret.append(isInt ? QString::number(x) : cap);
} }
return ret.join('x'); return ret.join(u'x');
} }
AutoDownloadRule::AutoDownloadRule(const QString &name) AutoDownloadRule::AutoDownloadRule(const QString &name)
@ -223,7 +223,7 @@ QRegularExpression AutoDownloadRule::cachedRegex(const QString &expression, cons
bool AutoDownloadRule::matchesExpression(const QString &articleTitle, const QString &expression) const bool AutoDownloadRule::matchesExpression(const QString &articleTitle, const QString &expression) const
{ {
const QRegularExpression whitespace {"\\s+"}; const QRegularExpression whitespace {u"\\s+"_qs};
if (expression.isEmpty()) if (expression.isEmpty())
{ {
@ -286,13 +286,13 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl
if (m_dataPtr->episodeFilter.isEmpty()) if (m_dataPtr->episodeFilter.isEmpty())
return true; return true;
const QRegularExpression filterRegex {cachedRegex("(^\\d{1,4})x(.*;$)")}; const QRegularExpression filterRegex {cachedRegex(u"(^\\d{1,4})x(.*;$)"_qs)};
const QRegularExpressionMatch matcher {filterRegex.match(m_dataPtr->episodeFilter)}; const QRegularExpressionMatch matcher {filterRegex.match(m_dataPtr->episodeFilter)};
if (!matcher.hasMatch()) if (!matcher.hasMatch())
return false; return false;
const QString season {matcher.captured(1)}; const QString season {matcher.captured(1)};
const QStringList episodes {matcher.captured(2).split(';')}; const QStringList episodes {matcher.captured(2).split(u';')};
const int seasonOurs {season.toInt()}; const int seasonOurs {season.toInt()};
for (QString episode : episodes) for (QString episode : episodes)
@ -301,13 +301,13 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl
continue; continue;
// We need to trim leading zeroes, but if it's all zeros then we want episode zero. // We need to trim leading zeroes, but if it's all zeros then we want episode zero.
while ((episode.size() > 1) && episode.startsWith('0')) while ((episode.size() > 1) && episode.startsWith(u'0'))
episode = episode.right(episode.size() - 1); episode = episode.right(episode.size() - 1);
if (episode.indexOf('-') != -1) if (episode.indexOf(u'-') != -1)
{ // Range detected { // Range detected
const QString partialPattern1 {"\\bs0?(\\d{1,4})[ -_\\.]?e(0?\\d{1,4})(?:\\D|\\b)"}; const QString partialPattern1 {u"\\bs0?(\\d{1,4})[ -_\\.]?e(0?\\d{1,4})(?:\\D|\\b)"_qs};
const QString partialPattern2 {"\\b(\\d{1,4})x(0?\\d{1,4})(?:\\D|\\b)"}; const QString partialPattern2 {u"\\b(\\d{1,4})x(0?\\d{1,4})(?:\\D|\\b)"_qs};
// Extract partial match from article and compare as digits // Extract partial match from article and compare as digits
QRegularExpressionMatch matcher = cachedRegex(partialPattern1).match(articleTitle); QRegularExpressionMatch matcher = cachedRegex(partialPattern1).match(articleTitle);
@ -324,7 +324,7 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl
const int seasonTheirs {matcher.captured(1).toInt()}; const int seasonTheirs {matcher.captured(1).toInt()};
const int episodeTheirs {matcher.captured(2).toInt()}; const int episodeTheirs {matcher.captured(2).toInt()};
if (episode.endsWith('-')) if (episode.endsWith(u'-'))
{ // Infinite range { // Infinite range
const int episodeOurs {QStringView(episode).left(episode.size() - 1).toInt()}; const int episodeOurs {QStringView(episode).left(episode.size() - 1).toInt()};
if (((seasonTheirs == seasonOurs) && (episodeTheirs >= episodeOurs)) || (seasonTheirs > seasonOurs)) if (((seasonTheirs == seasonOurs) && (episodeTheirs >= episodeOurs)) || (seasonTheirs > seasonOurs))
@ -332,7 +332,7 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl
} }
else else
{ // Normal range { // Normal range
const QStringList range {episode.split('-')}; const QStringList range {episode.split(u'-')};
Q_ASSERT(range.size() == 2); Q_ASSERT(range.size() == 2);
if (range.first().toInt() > range.last().toInt()) if (range.first().toInt() > range.last().toInt())
continue; // Ignore this subrule completely continue; // Ignore this subrule completely
@ -372,15 +372,15 @@ bool AutoDownloadRule::matchesSmartEpisodeFilter(const QString &articleTitle) co
return false; return false;
// Now see if we've downloaded this particular repack/proper combination // Now see if we've downloaded this particular repack/proper combination
const bool isRepack = articleTitle.contains("REPACK", Qt::CaseInsensitive); const bool isRepack = articleTitle.contains(u"REPACK", Qt::CaseInsensitive);
const bool isProper = articleTitle.contains("PROPER", Qt::CaseInsensitive); const bool isProper = articleTitle.contains(u"PROPER", Qt::CaseInsensitive);
if (!isRepack && !isProper) if (!isRepack && !isProper)
return false; return false;
const QString fullEpisodeStr = QString::fromLatin1("%1%2%3").arg(episodeStr, const QString fullEpisodeStr = u"%1%2%3"_qs.arg(episodeStr,
isRepack ? "-REPACK" : "", isRepack ? u"-REPACK" : u"",
isProper ? "-PROPER" : ""); isProper ? u"-PROPER" : u"");
const bool previouslyMatchedFull = m_dataPtr->previouslyMatchedEpisodes.contains(fullEpisodeStr); const bool previouslyMatchedFull = m_dataPtr->previouslyMatchedEpisodes.contains(fullEpisodeStr);
if (previouslyMatchedFull) if (previouslyMatchedFull)
return false; return false;
@ -544,35 +544,35 @@ AutoDownloadRule AutoDownloadRule::fromJsonObject(const QJsonObject &jsonObj, co
QVariantHash AutoDownloadRule::toLegacyDict() const QVariantHash AutoDownloadRule::toLegacyDict() const
{ {
return {{"name", name()}, return {{u"name"_qs, name()},
{"must_contain", mustContain()}, {u"must_contain"_qs, mustContain()},
{"must_not_contain", mustNotContain()}, {u"must_not_contain"_qs, mustNotContain()},
{"save_path", savePath().toString()}, {u"save_path"_qs, savePath().toString()},
{"affected_feeds", feedURLs()}, {u"affected_feeds"_qs, feedURLs()},
{"enabled", isEnabled()}, {u"enabled"_qs, isEnabled()},
{"category_assigned", assignedCategory()}, {u"category_assigned"_qs, assignedCategory()},
{"use_regex", useRegex()}, {u"use_regex"_qs, useRegex()},
{"add_paused", toAddPausedLegacy(addPaused())}, {u"add_paused"_qs, toAddPausedLegacy(addPaused())},
{"episode_filter", episodeFilter()}, {u"episode_filter"_qs, episodeFilter()},
{"last_match", lastMatch()}, {u"last_match"_qs, lastMatch()},
{"ignore_days", ignoreDays()}}; {u"ignore_days"_qs, ignoreDays()}};
} }
AutoDownloadRule AutoDownloadRule::fromLegacyDict(const QVariantHash &dict) AutoDownloadRule AutoDownloadRule::fromLegacyDict(const QVariantHash &dict)
{ {
AutoDownloadRule rule(dict.value("name").toString()); AutoDownloadRule rule(dict.value(u"name"_qs).toString());
rule.setUseRegex(dict.value("use_regex", false).toBool()); rule.setUseRegex(dict.value(u"use_regex"_qs, false).toBool());
rule.setMustContain(dict.value("must_contain").toString()); rule.setMustContain(dict.value(u"must_contain"_qs).toString());
rule.setMustNotContain(dict.value("must_not_contain").toString()); rule.setMustNotContain(dict.value(u"must_not_contain"_qs).toString());
rule.setEpisodeFilter(dict.value("episode_filter").toString()); rule.setEpisodeFilter(dict.value(u"episode_filter"_qs).toString());
rule.setFeedURLs(dict.value("affected_feeds").toStringList()); rule.setFeedURLs(dict.value(u"affected_feeds"_qs).toStringList());
rule.setEnabled(dict.value("enabled", false).toBool()); rule.setEnabled(dict.value(u"enabled"_qs, false).toBool());
rule.setSavePath(Path(dict.value("save_path").toString())); rule.setSavePath(Path(dict.value(u"save_path"_qs).toString()));
rule.setCategory(dict.value("category_assigned").toString()); rule.setCategory(dict.value(u"category_assigned"_qs).toString());
rule.setAddPaused(addPausedLegacyToOptionalBool(dict.value("add_paused").toInt())); rule.setAddPaused(addPausedLegacyToOptionalBool(dict.value(u"add_paused"_qs).toInt()));
rule.setLastMatch(dict.value("last_match").toDateTime()); rule.setLastMatch(dict.value(u"last_match"_qs).toDateTime());
rule.setIgnoreDays(dict.value("ignore_days").toInt()); rule.setIgnoreDays(dict.value(u"ignore_days"_qs).toInt());
return rule; return rule;
} }
@ -584,7 +584,7 @@ void AutoDownloadRule::setMustContain(const QString &tokens)
if (m_dataPtr->useRegex) if (m_dataPtr->useRegex)
m_dataPtr->mustContain = QStringList() << tokens; m_dataPtr->mustContain = QStringList() << tokens;
else else
m_dataPtr->mustContain = tokens.split('|'); m_dataPtr->mustContain = tokens.split(u'|');
// Check for single empty string - if so, no condition // Check for single empty string - if so, no condition
if ((m_dataPtr->mustContain.size() == 1) && m_dataPtr->mustContain[0].isEmpty()) if ((m_dataPtr->mustContain.size() == 1) && m_dataPtr->mustContain[0].isEmpty())
@ -598,7 +598,7 @@ void AutoDownloadRule::setMustNotContain(const QString &tokens)
if (m_dataPtr->useRegex) if (m_dataPtr->useRegex)
m_dataPtr->mustNotContain = QStringList() << tokens; m_dataPtr->mustNotContain = QStringList() << tokens;
else else
m_dataPtr->mustNotContain = tokens.split('|'); m_dataPtr->mustNotContain = tokens.split(u'|');
// Check for single empty string - if so, no condition // Check for single empty string - if so, no condition
if ((m_dataPtr->mustNotContain.size() == 1) && m_dataPtr->mustNotContain[0].isEmpty()) if ((m_dataPtr->mustNotContain.size() == 1) && m_dataPtr->mustNotContain[0].isEmpty())
@ -697,12 +697,12 @@ int AutoDownloadRule::ignoreDays() const
QString AutoDownloadRule::mustContain() const QString AutoDownloadRule::mustContain() const
{ {
return m_dataPtr->mustContain.join('|'); return m_dataPtr->mustContain.join(u'|');
} }
QString AutoDownloadRule::mustNotContain() const QString AutoDownloadRule::mustNotContain() const
{ {
return m_dataPtr->mustNotContain.join('|'); return m_dataPtr->mustNotContain.join(u'|');
} }
bool AutoDownloadRule::useSmartFilter() const bool AutoDownloadRule::useSmartFilter() const

View file

@ -34,6 +34,7 @@
#include <QSharedDataPointer> #include <QSharedDataPointer>
#include <QVariant> #include <QVariant>
#include "base/global.h"
#include "base/bittorrent/torrentcontentlayout.h" #include "base/bittorrent/torrentcontentlayout.h"
#include "base/pathfwd.h" #include "base/pathfwd.h"
@ -48,7 +49,7 @@ namespace RSS
class AutoDownloadRule class AutoDownloadRule
{ {
public: public:
explicit AutoDownloadRule(const QString &name = ""); explicit AutoDownloadRule(const QString &name = u""_qs);
AutoDownloadRule(const AutoDownloadRule &other); AutoDownloadRule(const AutoDownloadRule &other);
~AutoDownloadRule(); ~AutoDownloadRule();
@ -95,7 +96,7 @@ namespace RSS
bool operator!=(const AutoDownloadRule &other) const; bool operator!=(const AutoDownloadRule &other) const;
QJsonObject toJsonObject() const; QJsonObject toJsonObject() const;
static AutoDownloadRule fromJsonObject(const QJsonObject &jsonObj, const QString &name = ""); static AutoDownloadRule fromJsonObject(const QJsonObject &jsonObj, const QString &name = u""_qs);
QVariantHash toLegacyDict() const; QVariantHash toLegacyDict() const;
static AutoDownloadRule fromLegacyDict(const QVariantHash &dict); static AutoDownloadRule fromLegacyDict(const QVariantHash &dict);

View file

@ -324,7 +324,7 @@ void Feed::loadArticles(const QByteArray &data)
void Feed::loadArticlesLegacy() void Feed::loadArticlesLegacy()
{ {
const SettingsPtr qBTRSSFeeds = Profile::instance()->applicationSettings(QStringLiteral("qBittorrent-rss-feeds")); const SettingsPtr qBTRSSFeeds = Profile::instance()->applicationSettings(QStringLiteral("qBittorrent-rss-feeds"));
const QVariantHash allOldItems = qBTRSSFeeds->value("old_items").toHash(); const QVariantHash allOldItems = qBTRSSFeeds->value(u"old_items"_qs).toHash();
for (const QVariant &var : asConst(allOldItems.value(m_url).toList())) for (const QVariant &var : asConst(allOldItems.value(m_url).toList()))
{ {

View file

@ -31,6 +31,8 @@
#pragma once #pragma once
#include <QList> #include <QList>
#include "base/global.h"
#include "rss_item.h" #include "rss_item.h"
namespace RSS namespace RSS
@ -44,7 +46,7 @@ namespace RSS
friend class Session; friend class Session;
explicit Folder(const QString &path = ""); explicit Folder(const QString &path = u""_qs);
~Folder() override; ~Folder() override;
public: public:

View file

@ -71,7 +71,7 @@ Session::Session()
connect(m_workingThread, &QThread::finished, m_confFileStorage, &AsyncFileStorage::deleteLater); connect(m_workingThread, &QThread::finished, m_confFileStorage, &AsyncFileStorage::deleteLater);
connect(m_confFileStorage, &AsyncFileStorage::failed, [](const Path &fileName, const QString &errorString) connect(m_confFileStorage, &AsyncFileStorage::failed, [](const Path &fileName, const QString &errorString)
{ {
LogMsg(tr("Couldn't save RSS Session configuration in %1. Error: %2") LogMsg(tr("Couldn't save RSS session configuration. File: \"%1\". Error: \"%2\"")
.arg(fileName.toString(), errorString), Log::WARNING); .arg(fileName.toString(), errorString), Log::WARNING);
}); });
@ -80,11 +80,11 @@ Session::Session()
connect(m_workingThread, &QThread::finished, m_dataFileStorage, &AsyncFileStorage::deleteLater); connect(m_workingThread, &QThread::finished, m_dataFileStorage, &AsyncFileStorage::deleteLater);
connect(m_dataFileStorage, &AsyncFileStorage::failed, [](const Path &fileName, const QString &errorString) connect(m_dataFileStorage, &AsyncFileStorage::failed, [](const Path &fileName, const QString &errorString)
{ {
LogMsg(tr("Couldn't save RSS Session data in %1. Error: %2") LogMsg(tr("Couldn't save RSS session data. File: \"%1\". Error: \"%2\"")
.arg(fileName.toString(), errorString), Log::WARNING); .arg(fileName.toString(), errorString), Log::WARNING);
}); });
m_itemsByPath.insert("", new Folder); // root folder m_itemsByPath.insert(u""_qs, new Folder); // root folder
m_workingThread->start(); m_workingThread->start();
load(); load();
@ -100,22 +100,22 @@ Session::Session()
// (at least on Windows, QSettings is case-insensitive and it can get // (at least on Windows, QSettings is case-insensitive and it can get
// confused when asked about settings that differ only in their case) // confused when asked about settings that differ only in their case)
auto settingsStorage = SettingsStorage::instance(); auto settingsStorage = SettingsStorage::instance();
settingsStorage->removeValue("Rss/streamList"); settingsStorage->removeValue(u"Rss/streamList"_qs);
settingsStorage->removeValue("Rss/streamAlias"); settingsStorage->removeValue(u"Rss/streamAlias"_qs);
settingsStorage->removeValue("Rss/open_folders"); settingsStorage->removeValue(u"Rss/open_folders"_qs);
settingsStorage->removeValue("Rss/qt5/splitter_h"); settingsStorage->removeValue(u"Rss/qt5/splitter_h"_qs);
settingsStorage->removeValue("Rss/qt5/splitterMain"); settingsStorage->removeValue(u"Rss/qt5/splitterMain"_qs);
settingsStorage->removeValue("Rss/hosts_cookies"); settingsStorage->removeValue(u"Rss/hosts_cookies"_qs);
settingsStorage->removeValue("RSS/streamList"); settingsStorage->removeValue(u"RSS/streamList"_qs);
settingsStorage->removeValue("RSS/streamAlias"); settingsStorage->removeValue(u"RSS/streamAlias"_qs);
settingsStorage->removeValue("RSS/open_folders"); settingsStorage->removeValue(u"RSS/open_folders"_qs);
settingsStorage->removeValue("RSS/qt5/splitter_h"); settingsStorage->removeValue(u"RSS/qt5/splitter_h"_qs);
settingsStorage->removeValue("RSS/qt5/splitterMain"); settingsStorage->removeValue(u"RSS/qt5/splitterMain"_qs);
settingsStorage->removeValue("RSS/hosts_cookies"); settingsStorage->removeValue(u"RSS/hosts_cookies"_qs);
settingsStorage->removeValue("Rss/Session/EnableProcessing"); settingsStorage->removeValue(u"Rss/Session/EnableProcessing"_qs);
settingsStorage->removeValue("Rss/Session/RefreshInterval"); settingsStorage->removeValue(u"Rss/Session/RefreshInterval"_qs);
settingsStorage->removeValue("Rss/Session/MaxArticlesPerFeed"); settingsStorage->removeValue(u"Rss/Session/MaxArticlesPerFeed"_qs);
settingsStorage->removeValue("Rss/AutoDownloader/EnableProcessing"); settingsStorage->removeValue(u"Rss/AutoDownloader/EnableProcessing"_qs);
} }
Session::~Session() Session::~Session()
@ -126,7 +126,7 @@ Session::~Session()
m_workingThread->wait(); m_workingThread->wait();
//store(); //store();
delete m_itemsByPath[""]; // deleting root folder delete m_itemsByPath[u""_qs]; // deleting root folder
qDebug() << "RSS Session deleted."; qDebug() << "RSS Session deleted.";
} }
@ -240,8 +240,7 @@ void Session::load()
if (!itemsFile.open(QFile::ReadOnly)) if (!itemsFile.open(QFile::ReadOnly))
{ {
Logger::instance()->addMessage( LogMsg(tr("Couldn't read RSS session data. File: \"%1\". Error: \"%2\"")
QString("Couldn't read RSS Session data from %1. Error: %2")
.arg(itemsFile.fileName(), itemsFile.errorString()), Log::WARNING); .arg(itemsFile.fileName(), itemsFile.errorString()), Log::WARNING);
return; return;
} }
@ -250,16 +249,14 @@ void Session::load()
const QJsonDocument jsonDoc = QJsonDocument::fromJson(itemsFile.readAll(), &jsonError); const QJsonDocument jsonDoc = QJsonDocument::fromJson(itemsFile.readAll(), &jsonError);
if (jsonError.error != QJsonParseError::NoError) if (jsonError.error != QJsonParseError::NoError)
{ {
Logger::instance()->addMessage( LogMsg(tr("Couldn't parse RSS session data. File: \"%1\". Error: \"%2\"")
QString("Couldn't parse RSS Session data from %1. Error: %2")
.arg(itemsFile.fileName(), jsonError.errorString()), Log::WARNING); .arg(itemsFile.fileName(), jsonError.errorString()), Log::WARNING);
return; return;
} }
if (!jsonDoc.isObject()) if (!jsonDoc.isObject())
{ {
Logger::instance()->addMessage( LogMsg(tr("Couldn't load RSS session data. File: \"%1\". Error: Invalid data format.")
QString("Couldn't load RSS Session data from %1. Invalid data format.")
.arg(itemsFile.fileName()), Log::WARNING); .arg(itemsFile.fileName()), Log::WARNING);
return; return;
} }
@ -285,29 +282,29 @@ void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder)
else if (val.isObject()) else if (val.isObject())
{ {
const QJsonObject valObj {val.toObject()}; const QJsonObject valObj {val.toObject()};
if (valObj.contains("url")) if (valObj.contains(u"url"))
{ {
if (!valObj["url"].isString()) if (!valObj[u"url"].isString())
{ {
LogMsg(tr("Couldn't load RSS Feed '%1'. URL is required.") LogMsg(tr("Couldn't load RSS feed. Feed: \"%1\". Reason: URL is required.")
.arg(QString("%1\\%2").arg(folder->path(), key)), Log::WARNING); .arg(u"%1\\%2"_qs.arg(folder->path(), key)), Log::WARNING);
continue; continue;
} }
QUuid uid; QUuid uid;
if (valObj.contains("uid")) if (valObj.contains(u"uid"))
{ {
uid = QUuid {valObj["uid"].toString()}; uid = QUuid {valObj[u"uid"].toString()};
if (uid.isNull()) if (uid.isNull())
{ {
LogMsg(tr("Couldn't load RSS Feed '%1'. UID is invalid.") LogMsg(tr("Couldn't load RSS feed. Feed: \"%1\". Reason: UID is invalid.")
.arg(QString("%1\\%2").arg(folder->path(), key)), Log::WARNING); .arg(u"%1\\%2"_qs.arg(folder->path(), key)), Log::WARNING);
continue; continue;
} }
if (m_feedsByUID.contains(uid)) if (m_feedsByUID.contains(uid))
{ {
LogMsg(tr("Duplicate RSS Feed UID: %1. Configuration seems to be corrupted.") LogMsg(tr("Duplicate RSS feed found. UID: \"%1\". Error: Configuration seems to be corrupted.")
.arg(uid.toString()), Log::WARNING); .arg(uid.toString()), Log::WARNING);
continue; continue;
} }
@ -319,7 +316,7 @@ void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder)
updated = true; updated = true;
} }
addFeedToFolder(uid, valObj["url"].toString(), key, folder); addFeedToFolder(uid, valObj[u"url"].toString(), key, folder);
} }
else else
{ {
@ -328,7 +325,7 @@ void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder)
} }
else else
{ {
LogMsg(tr("Couldn't load RSS Item '%1'. Invalid data format.") LogMsg(tr("Couldn't load RSS item. Item: \"%1\". Invalid data format.")
.arg(QString::fromLatin1("%1\\%2").arg(folder->path(), key)), Log::WARNING); .arg(QString::fromLatin1("%1\\%2").arg(folder->path(), key)), Log::WARNING);
} }
} }
@ -339,11 +336,11 @@ void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder)
void Session::loadLegacy() void Session::loadLegacy()
{ {
const auto legacyFeedPaths = SettingsStorage::instance()->loadValue<QStringList>("Rss/streamList"); const auto legacyFeedPaths = SettingsStorage::instance()->loadValue<QStringList>(u"Rss/streamList"_qs);
const auto feedAliases = SettingsStorage::instance()->loadValue<QStringList>("Rss/streamAlias"); const auto feedAliases = SettingsStorage::instance()->loadValue<QStringList>(u"Rss/streamAlias"_qs);
if (legacyFeedPaths.size() != feedAliases.size()) if (legacyFeedPaths.size() != feedAliases.size())
{ {
Logger::instance()->addMessage("Corrupted RSS list, not loading it.", Log::WARNING); LogMsg(tr("Corrupted RSS list, not loading it."), Log::WARNING);
return; return;
} }
@ -458,7 +455,7 @@ AsyncFileStorage *Session::dataFileStorage() const
Folder *Session::rootFolder() const Folder *Session::rootFolder() const
{ {
return static_cast<Folder *>(m_itemsByPath.value("")); return static_cast<Folder *>(m_itemsByPath.value(u""_qs));
} }
QList<Feed *> Session::feeds() const QList<Feed *> Session::feeds() const

View file

@ -69,13 +69,13 @@ SearchHandler::SearchHandler(const QString &pattern, const QString &category, co
const QStringList params const QStringList params
{ {
(m_manager->engineLocation() / Path(u"nova2.py"_qs)).toString(), (m_manager->engineLocation() / Path(u"nova2.py"_qs)).toString(),
m_usedPlugins.join(','), m_usedPlugins.join(u','),
m_category m_category
}; };
// Launch search // Launch search
m_searchProcess->setProgram(Utils::ForeignApps::pythonInfo().executableName); m_searchProcess->setProgram(Utils::ForeignApps::pythonInfo().executableName);
m_searchProcess->setArguments(params + m_pattern.split(' ')); m_searchProcess->setArguments(params + m_pattern.split(u' '));
connect(m_searchProcess, &QProcess::errorOccurred, this, &SearchHandler::processFailed); connect(m_searchProcess, &QProcess::errorOccurred, this, &SearchHandler::processFailed);
connect(m_searchProcess, &QProcess::readyReadStandardOutput, this, &SearchHandler::readSearchOutput); connect(m_searchProcess, &QProcess::readyReadStandardOutput, this, &SearchHandler::readSearchOutput);

View file

@ -149,9 +149,9 @@ QStringList SearchPluginManager::supportedCategories() const
QStringList SearchPluginManager::getPluginCategories(const QString &pluginName) const QStringList SearchPluginManager::getPluginCategories(const QString &pluginName) const
{ {
QStringList plugins; QStringList plugins;
if (pluginName == "all") if (pluginName == u"all")
plugins = allPlugins(); plugins = allPlugins();
else if ((pluginName == "enabled") || (pluginName == "multi")) else if ((pluginName == u"enabled") || (pluginName == u"multi"))
plugins = enabledPlugins(); plugins = enabledPlugins();
else else
plugins << pluginName.trimmed(); plugins << pluginName.trimmed();
@ -211,12 +211,12 @@ void SearchPluginManager::installPlugin(const QString &source)
} }
else else
{ {
const Path path {source.startsWith("file:", Qt::CaseInsensitive) ? QUrl(source).toLocalFile() : source}; const Path path {source.startsWith(u"file:", Qt::CaseInsensitive) ? QUrl(source).toLocalFile() : source};
QString pluginName = path.filename(); QString pluginName = path.filename();
if (pluginName.endsWith(".py", Qt::CaseInsensitive)) if (pluginName.endsWith(u".py", Qt::CaseInsensitive))
{ {
pluginName.chop(pluginName.size() - pluginName.lastIndexOf('.')); pluginName.chop(pluginName.size() - pluginName.lastIndexOf(u'.'));
installPlugin_impl(pluginName, path); installPlugin_impl(pluginName, path);
} }
else else
@ -322,7 +322,7 @@ void SearchPluginManager::checkForUpdates()
{ {
// Download version file from update server // Download version file from update server
using namespace Net; using namespace Net;
DownloadManager::instance()->download({m_updateUrl + "versions.txt"} DownloadManager::instance()->download({m_updateUrl + u"versions.txt"}
, this, &SearchPluginManager::versionInfoDownloadFinished); , this, &SearchPluginManager::versionInfoDownloadFinished);
} }
@ -343,15 +343,15 @@ QString SearchPluginManager::categoryFullName(const QString &categoryName)
{ {
const QHash<QString, QString> categoryTable const QHash<QString, QString> categoryTable
{ {
{"all", tr("All categories")}, {u"all"_qs, tr("All categories")},
{"movies", tr("Movies")}, {u"movies"_qs, tr("Movies")},
{"tv", tr("TV shows")}, {u"tv"_qs, tr("TV shows")},
{"music", tr("Music")}, {u"music"_qs, tr("Music")},
{"games", tr("Games")}, {u"games"_qs, tr("Games")},
{"anime", tr("Anime")}, {u"anime"_qs, tr("Anime")},
{"software", tr("Software")}, {u"software"_qs, tr("Software")},
{"pictures", tr("Pictures")}, {u"pictures"_qs, tr("Pictures")},
{"books", tr("Books")} {u"books"_qs, tr("Books")}
}; };
return categoryTable.value(categoryName); return categoryTable.value(categoryName);
} }
@ -400,8 +400,8 @@ void SearchPluginManager::pluginDownloadFinished(const Net::DownloadResult &resu
else else
{ {
const QString url = result.url; const QString url = result.url;
QString pluginName = url.mid(url.lastIndexOf('/') + 1); QString pluginName = url.mid(url.lastIndexOf(u'/') + 1);
pluginName.replace(".py", "", Qt::CaseInsensitive); pluginName.replace(u".py"_qs, u""_qs, Qt::CaseInsensitive);
if (pluginInfo(pluginName)) if (pluginInfo(pluginName))
emit pluginUpdateFailed(pluginName, tr("Failed to download the plugin file. %1").arg(result.errorString)); emit pluginUpdateFailed(pluginName, tr("Failed to download the plugin file. %1").arg(result.errorString));
@ -456,7 +456,7 @@ void SearchPluginManager::update()
nova.start(Utils::ForeignApps::pythonInfo().executableName, params, QIODevice::ReadOnly); nova.start(Utils::ForeignApps::pythonInfo().executableName, params, QIODevice::ReadOnly);
nova.waitForFinished(); nova.waitForFinished();
const QString capabilities = nova.readAll(); const auto capabilities = QString::fromUtf8(nova.readAll());
QDomDocument xmlDoc; QDomDocument xmlDoc;
if (!xmlDoc.setContent(capabilities)) if (!xmlDoc.setContent(capabilities))
{ {
@ -466,7 +466,7 @@ void SearchPluginManager::update()
} }
const QDomElement root = xmlDoc.documentElement(); const QDomElement root = xmlDoc.documentElement();
if (root.tagName() != "capabilities") if (root.tagName() != u"capabilities")
{ {
qWarning() << "Invalid XML file for Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data(); qWarning() << "Invalid XML file for Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data();
return; return;
@ -482,10 +482,10 @@ void SearchPluginManager::update()
auto plugin = std::make_unique<PluginInfo>(); auto plugin = std::make_unique<PluginInfo>();
plugin->name = pluginName; plugin->name = pluginName;
plugin->version = getPluginVersion(pluginPath(pluginName)); plugin->version = getPluginVersion(pluginPath(pluginName));
plugin->fullName = engineElem.elementsByTagName("name").at(0).toElement().text(); plugin->fullName = engineElem.elementsByTagName(u"name"_qs).at(0).toElement().text();
plugin->url = engineElem.elementsByTagName("url").at(0).toElement().text(); plugin->url = engineElem.elementsByTagName(u"url"_qs).at(0).toElement().text();
const QStringList categories = engineElem.elementsByTagName("categories").at(0).toElement().text().split(' '); const QStringList categories = engineElem.elementsByTagName(u"categories"_qs).at(0).toElement().text().split(u' ');
for (QString cat : categories) for (QString cat : categories)
{ {
cat = cat.trimmed(); cat = cat.trimmed();
@ -528,7 +528,7 @@ void SearchPluginManager::parseVersionInfo(const QByteArray &info)
const QVector<QByteArray> list = Utils::ByteArray::splitToViews(line, ":", Qt::SkipEmptyParts); const QVector<QByteArray> list = Utils::ByteArray::splitToViews(line, ":", Qt::SkipEmptyParts);
if (list.size() != 2) continue; if (list.size() != 2) continue;
const QString pluginName = list.first().trimmed(); const auto pluginName = QString::fromUtf8(list.first().trimmed());
const PluginVersion version = PluginVersion::tryParse(list.last().trimmed(), {}); const PluginVersion version = PluginVersion::tryParse(list.last().trimmed(), {});
if (!version.isValid()) continue; if (!version.isValid()) continue;
@ -574,8 +574,8 @@ PluginVersion SearchPluginManager::getPluginVersion(const Path &filePath)
while (!pluginFile.atEnd()) while (!pluginFile.atEnd())
{ {
const QString line = QString(pluginFile.readLine()).remove(' '); const auto line = QString::fromUtf8(pluginFile.readLine()).remove(u' ');
if (!line.startsWith("#VERSION:", Qt::CaseInsensitive)) continue; if (!line.startsWith(u"#VERSION:", Qt::CaseInsensitive)) continue;
const QString versionStr = line.mid(9); const QString versionStr = line.mid(9);
const PluginVersion version = PluginVersion::tryParse(versionStr, {}); const PluginVersion version = PluginVersion::tryParse(versionStr, {});

View file

@ -324,7 +324,7 @@ void TorrentFilesWatcher::load()
void TorrentFilesWatcher::loadLegacy() void TorrentFilesWatcher::loadLegacy()
{ {
const auto dirs = SettingsStorage::instance()->loadValue<QVariantHash>("Preferences/Downloads/ScanDirsV2"); const auto dirs = SettingsStorage::instance()->loadValue<QVariantHash>(u"Preferences/Downloads/ScanDirsV2"_qs);
for (auto it = dirs.cbegin(); it != dirs.cend(); ++it) for (auto it = dirs.cbegin(); it != dirs.cend(); ++it)
{ {
@ -356,7 +356,7 @@ void TorrentFilesWatcher::loadLegacy()
} }
store(); store();
SettingsStorage::instance()->removeValue("Preferences/Downloads/ScanDirsV2"); SettingsStorage::instance()->removeValue(u"Preferences/Downloads/ScanDirsV2"_qs);
} }
void TorrentFilesWatcher::store() const void TorrentFilesWatcher::store() const
@ -497,7 +497,7 @@ void TorrentFilesWatcher::Worker::processWatchedFolder(const Path &path)
void TorrentFilesWatcher::Worker::processFolder(const Path &path, const Path &watchedFolderPath void TorrentFilesWatcher::Worker::processFolder(const Path &path, const Path &watchedFolderPath
, const TorrentFilesWatcher::WatchedFolderOptions &options) , const TorrentFilesWatcher::WatchedFolderOptions &options)
{ {
QDirIterator dirIter {path.data(), {"*.torrent", "*.magnet"}, QDir::Files}; QDirIterator dirIter {path.data(), {u"*.torrent"_qs, u"*.magnet"_qs}, QDir::Files};
while (dirIter.hasNext()) while (dirIter.hasNext())
{ {
const Path filePath {dirIter.next()}; const Path filePath {dirIter.next()};

View file

@ -89,13 +89,13 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const Path &path)
}; };
// travel from the deepest folder and remove anything unwanted on the way out. // travel from the deepest folder and remove anything unwanted on the way out.
QStringList dirList(path.data() + '/'); // get all sub directories paths QStringList dirList(path.data() + u'/'); // get all sub directories paths
QDirIterator iter {path.data(), (QDir::AllDirs | QDir::NoDotAndDotDot), QDirIterator::Subdirectories}; QDirIterator iter {path.data(), (QDir::AllDirs | QDir::NoDotAndDotDot), QDirIterator::Subdirectories};
while (iter.hasNext()) while (iter.hasNext())
dirList << iter.next() + '/'; dirList << iter.next() + u'/';
// sort descending by directory depth // sort descending by directory depth
std::sort(dirList.begin(), dirList.end() std::sort(dirList.begin(), dirList.end()
, [](const QString &l, const QString &r) { return l.count('/') > r.count('/'); }); , [](const QString &l, const QString &r) { return l.count(u'/') > r.count(u'/'); });
for (const QString &p : asConst(dirList)) for (const QString &p : asConst(dirList))
{ {
@ -111,7 +111,7 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const Path &path)
// temp files on linux usually end with '~', e.g. `filename~` // temp files on linux usually end with '~', e.g. `filename~`
const bool hasOtherFiles = std::any_of(tmpFileList.cbegin(), tmpFileList.cend(), [&deleteFilesList](const QString &f) const bool hasOtherFiles = std::any_of(tmpFileList.cbegin(), tmpFileList.cend(), [&deleteFilesList](const QString &f)
{ {
return (!f.endsWith('~') && !deleteFilesList.contains(f, Qt::CaseInsensitive)); return (!f.endsWith(u'~') && !deleteFilesList.contains(f, Qt::CaseInsensitive));
}); });
if (hasOtherFiles) if (hasOtherFiles)
continue; continue;
@ -220,7 +220,7 @@ bool Utils::Fs::isRegularFile(const Path &path)
// analyse erno and log the error // analyse erno and log the error
const auto err = errno; const auto err = errno;
qDebug("Could not get file stats for path '%s'. Error: %s" qDebug("Could not get file stats for path '%s'. Error: %s"
, qUtf8Printable(path.toString()), qUtf8Printable(strerror(err))); , qUtf8Printable(path.toString()), strerror(err));
return false; return false;
} }

View file

@ -190,59 +190,59 @@ void Utils::Misc::shutdownComputer(const ShutdownDialogAction &action)
if (action != ShutdownDialogAction::Shutdown) if (action != ShutdownDialogAction::Shutdown)
{ {
// Some recent systems use systemd's logind // Some recent systems use systemd's logind
QDBusInterface login1Iface("org.freedesktop.login1", "/org/freedesktop/login1", QDBusInterface login1Iface(u"org.freedesktop.login1"_qs, u"/org/freedesktop/login1"_qs,
"org.freedesktop.login1.Manager", QDBusConnection::systemBus()); u"org.freedesktop.login1.Manager"_qs, QDBusConnection::systemBus());
if (login1Iface.isValid()) if (login1Iface.isValid())
{ {
if (action == ShutdownDialogAction::Suspend) if (action == ShutdownDialogAction::Suspend)
login1Iface.call("Suspend", false); login1Iface.call(u"Suspend"_qs, false);
else else
login1Iface.call("Hibernate", false); login1Iface.call(u"Hibernate"_qs, false);
return; return;
} }
// Else, other recent systems use UPower // Else, other recent systems use UPower
QDBusInterface upowerIface("org.freedesktop.UPower", "/org/freedesktop/UPower", QDBusInterface upowerIface(u"org.freedesktop.UPower"_qs, u"/org/freedesktop/UPower"_qs,
"org.freedesktop.UPower", QDBusConnection::systemBus()); u"org.freedesktop.UPower"_qs, QDBusConnection::systemBus());
if (upowerIface.isValid()) if (upowerIface.isValid())
{ {
if (action == ShutdownDialogAction::Suspend) if (action == ShutdownDialogAction::Suspend)
upowerIface.call("Suspend"); upowerIface.call(u"Suspend"_qs);
else else
upowerIface.call("Hibernate"); upowerIface.call(u"Hibernate"_qs);
return; return;
} }
// HAL (older systems) // HAL (older systems)
QDBusInterface halIface("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer", QDBusInterface halIface(u"org.freedesktop.Hal"_qs, u"/org/freedesktop/Hal/devices/computer"_qs,
"org.freedesktop.Hal.Device.SystemPowerManagement", u"org.freedesktop.Hal.Device.SystemPowerManagement"_qs,
QDBusConnection::systemBus()); QDBusConnection::systemBus());
if (action == ShutdownDialogAction::Suspend) if (action == ShutdownDialogAction::Suspend)
halIface.call("Suspend", 5); halIface.call(u"Suspend"_qs, 5);
else else
halIface.call("Hibernate"); halIface.call(u"Hibernate"_qs);
} }
else else
{ {
// Some recent systems use systemd's logind // Some recent systems use systemd's logind
QDBusInterface login1Iface("org.freedesktop.login1", "/org/freedesktop/login1", QDBusInterface login1Iface(u"org.freedesktop.login1"_qs, u"/org/freedesktop/login1"_qs,
"org.freedesktop.login1.Manager", QDBusConnection::systemBus()); u"org.freedesktop.login1.Manager"_qs, QDBusConnection::systemBus());
if (login1Iface.isValid()) if (login1Iface.isValid())
{ {
login1Iface.call("PowerOff", false); login1Iface.call(u"PowerOff"_qs, false);
return; return;
} }
// Else, other recent systems use ConsoleKit // Else, other recent systems use ConsoleKit
QDBusInterface consolekitIface("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Manager", QDBusInterface consolekitIface(u"org.freedesktop.ConsoleKit"_qs, u"/org/freedesktop/ConsoleKit/Manager"_qs,
"org.freedesktop.ConsoleKit.Manager", QDBusConnection::systemBus()); u"org.freedesktop.ConsoleKit.Manager"_qs, QDBusConnection::systemBus());
if (consolekitIface.isValid()) if (consolekitIface.isValid())
{ {
consolekitIface.call("Stop"); consolekitIface.call(u"Stop"_qs);
return; return;
} }
// HAL (older systems) // HAL (older systems)
QDBusInterface halIface("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer", QDBusInterface halIface(u"org.freedesktop.Hal"_qs, u"/org/freedesktop/Hal/devices/computer"_qs,
"org.freedesktop.Hal.Device.SystemPowerManagement", u"org.freedesktop.Hal.Device.SystemPowerManagement"_qs,
QDBusConnection::systemBus()); QDBusConnection::systemBus());
halIface.call("Shutdown"); halIface.call(u"Shutdown"_qs);
} }
#else #else
@ -305,48 +305,48 @@ bool Utils::Misc::isPreviewable(const Path &filePath)
const QSet<QString> multimediaExtensions = const QSet<QString> multimediaExtensions =
{ {
".3GP", u".3GP"_qs,
".AAC", u".AAC"_qs,
".AC3", u".AC3"_qs,
".AIF", u".AIF"_qs,
".AIFC", u".AIFC"_qs,
".AIFF", u".AIFF"_qs,
".ASF", u".ASF"_qs,
".AU", u".AU"_qs,
".AVI", u".AVI"_qs,
".FLAC", u".FLAC"_qs,
".FLV", u".FLV"_qs,
".M3U", u".M3U"_qs,
".M4A", u".M4A"_qs,
".M4P", u".M4P"_qs,
".M4V", u".M4V"_qs,
".MID", u".MID"_qs,
".MKV", u".MKV"_qs,
".MOV", u".MOV"_qs,
".MP2", u".MP2"_qs,
".MP3", u".MP3"_qs,
".MP4", u".MP4"_qs,
".MPC", u".MPC"_qs,
".MPE", u".MPE"_qs,
".MPEG", u".MPEG"_qs,
".MPG", u".MPG"_qs,
".MPP", u".MPP"_qs,
".OGG", u".OGG"_qs,
".OGM", u".OGM"_qs,
".OGV", u".OGV"_qs,
".QT", u".QT"_qs,
".RA", u".RA"_qs,
".RAM", u".RAM"_qs,
".RM", u".RM"_qs,
".RMV", u".RMV"_qs,
".RMVB", u".RMVB"_qs,
".SWA", u".SWA"_qs,
".SWF", u".SWF"_qs,
".TS", u".TS"_qs,
".VOB", u".VOB"_qs,
".WAV", u".WAV"_qs,
".WMA", u".WMA"_qs,
".WMV" u".WMV"_qs
}; };
return multimediaExtensions.contains(filePath.extension().toUpper()); return multimediaExtensions.contains(filePath.extension().toUpper());
} }
@ -359,7 +359,7 @@ QString Utils::Misc::userFriendlyDuration(const qlonglong seconds, const qlonglo
return QString::fromUtf8(C_INFINITY); return QString::fromUtf8(C_INFINITY);
if (seconds == 0) if (seconds == 0)
return "0"; return u"0"_qs;
if (seconds < 60) if (seconds < 60)
return QCoreApplication::translate("misc", "< 1m", "< 1 minute"); return QCoreApplication::translate("misc", "< 1m", "< 1 minute");
@ -389,7 +389,7 @@ QString Utils::Misc::userFriendlyDuration(const qlonglong seconds, const qlonglo
QString Utils::Misc::getUserIDString() QString Utils::Misc::getUserIDString()
{ {
QString uid = "0"; QString uid = u"0"_qs;
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
const int UNLEN = 256; const int UNLEN = 256;
WCHAR buffer[UNLEN + 1] = {0}; WCHAR buffer[UNLEN + 1] = {0};
@ -406,61 +406,61 @@ QString Utils::Misc::parseHtmlLinks(const QString &rawText)
{ {
QString result = rawText; QString result = rawText;
static const QRegularExpression reURL( static const QRegularExpression reURL(
"(\\s|^)" // start with whitespace or beginning of line u"(\\s|^)" // start with whitespace or beginning of line
"(" u"("
"(" // case 1 -- URL with scheme u"(" // case 1 -- URL with scheme
"(http(s?))\\://" // start with scheme u"(http(s?))\\://" // start with scheme
"([a-zA-Z0-9_-]+\\.)+" // domainpart. at least one of these must exist u"([a-zA-Z0-9_-]+\\.)+" // domainpart. at least one of these must exist
"([a-zA-Z0-9\\?%=&/_\\.:#;-]+)" // everything to 1st non-URI char, must be at least one char after the previous dot (cannot use ".*" because it can be too greedy) u"([a-zA-Z0-9\\?%=&/_\\.:#;-]+)" // everything to 1st non-URI char, must be at least one char after the previous dot (cannot use ".*" because it can be too greedy)
")" u")"
"|" u"|"
"(" // case 2a -- no scheme, contains common TLD example.com u"(" // case 2a -- no scheme, contains common TLD example.com
"([a-zA-Z0-9_-]+\\.)+" // domainpart. at least one of these must exist u"([a-zA-Z0-9_-]+\\.)+" // domainpart. at least one of these must exist
"(?=" // must be followed by TLD u"(?=" // must be followed by TLD
"AERO|aero|" // N.B. assertions are non-capturing u"AERO|aero|" // N.B. assertions are non-capturing
"ARPA|arpa|" u"ARPA|arpa|"
"ASIA|asia|" u"ASIA|asia|"
"BIZ|biz|" u"BIZ|biz|"
"CAT|cat|" u"CAT|cat|"
"COM|com|" u"COM|com|"
"COOP|coop|" u"COOP|coop|"
"EDU|edu|" u"EDU|edu|"
"GOV|gov|" u"GOV|gov|"
"INFO|info|" u"INFO|info|"
"INT|int|" u"INT|int|"
"JOBS|jobs|" u"JOBS|jobs|"
"MIL|mil|" u"MIL|mil|"
"MOBI|mobi|" u"MOBI|mobi|"
"MUSEUM|museum|" u"MUSEUM|museum|"
"NAME|name|" u"NAME|name|"
"NET|net|" u"NET|net|"
"ORG|org|" u"ORG|org|"
"PRO|pro|" u"PRO|pro|"
"RO|ro|" u"RO|ro|"
"RU|ru|" u"RU|ru|"
"TEL|tel|" u"TEL|tel|"
"TRAVEL|travel" u"TRAVEL|travel"
")" u")"
"([a-zA-Z0-9\\?%=&/_\\.:#;-]+)" // everything to 1st non-URI char, must be at least one char after the previous dot (cannot use ".*" because it can be too greedy) u"([a-zA-Z0-9\\?%=&/_\\.:#;-]+)" // everything to 1st non-URI char, must be at least one char after the previous dot (cannot use ".*" because it can be too greedy)
")" u")"
"|" u"|"
"(" // case 2b no scheme, no TLD, must have at least 2 alphanum strings plus uncommon TLD string --> del.icio.us u"(" // case 2b no scheme, no TLD, must have at least 2 alphanum strings plus uncommon TLD string --> del.icio.us
"([a-zA-Z0-9_-]+\\.) {2,}" // 2 or more domainpart. --> del.icio. u"([a-zA-Z0-9_-]+\\.) {2,}" // 2 or more domainpart. --> del.icio.
"[a-zA-Z]{2,}" // one ab (2 char or longer) --> us u"[a-zA-Z]{2,}" // one ab (2 char or longer) --> us
"([a-zA-Z0-9\\?%=&/_\\.:#;-]*)" // everything to 1st non-URI char, maybe nothing in case of del.icio.us/path u"([a-zA-Z0-9\\?%=&/_\\.:#;-]*)" // everything to 1st non-URI char, maybe nothing in case of del.icio.us/path
")" u")"
")" u")"_qs
); );
// Capture links // Capture links
result.replace(reURL, "\\1<a href=\"\\2\">\\2</a>"); result.replace(reURL, u"\\1<a href=\"\\2\">\\2</a>"_qs);
// Capture links without scheme // Capture links without scheme
static const QRegularExpression reNoScheme("<a\\s+href=\"(?!https?)([a-zA-Z0-9\\?%=&/_\\.-:#]+)\\s*\">"); static const QRegularExpression reNoScheme(u"<a\\s+href=\"(?!https?)([a-zA-Z0-9\\?%=&/_\\.-:#]+)\\s*\">"_qs);
result.replace(reNoScheme, "<a href=\"http://\\1\">"); result.replace(reNoScheme, u"<a href=\"http://\\1\">"_qs);
// to preserve plain text formatting // to preserve plain text formatting
result = "<p style=\"white-space: pre-wrap;\">" + result + "</p>"; result = u"<p style=\"white-space: pre-wrap;\">" + result + u"</p>";
return result; return result;
} }
@ -468,7 +468,7 @@ QString Utils::Misc::osName()
{ {
// static initialization for usage in signal handler // static initialization for usage in signal handler
static const QString name = static const QString name =
QString("%1 %2 %3") u"%1 %2 %3"_qs
.arg(QSysInfo::prettyProductName() .arg(QSysInfo::prettyProductName()
, QSysInfo::kernelVersion() , QSysInfo::kernelVersion()
, QSysInfo::currentCpuArchitecture()); , QSysInfo::currentCpuArchitecture());
@ -478,7 +478,7 @@ QString Utils::Misc::osName()
QString Utils::Misc::boostVersionString() QString Utils::Misc::boostVersionString()
{ {
// static initialization for usage in signal handler // static initialization for usage in signal handler
static const QString ver = QString("%1.%2.%3") static const QString ver = u"%1.%2.%3"_qs
.arg(QString::number(BOOST_VERSION / 100000) .arg(QString::number(BOOST_VERSION / 100000)
, QString::number((BOOST_VERSION / 100) % 1000) , QString::number((BOOST_VERSION / 100) % 1000)
, QString::number(BOOST_VERSION % 100)); , QString::number(BOOST_VERSION % 100));

View file

@ -71,9 +71,9 @@ QString Utils::String::wildcardToRegexPattern(const QString &pattern)
std::optional<bool> Utils::String::parseBool(const QString &string) std::optional<bool> Utils::String::parseBool(const QString &string)
{ {
if (string.compare("true", Qt::CaseInsensitive) == 0) if (string.compare(u"true", Qt::CaseInsensitive) == 0)
return true; return true;
if (string.compare("false", Qt::CaseInsensitive) == 0) if (string.compare(u"false", Qt::CaseInsensitive) == 0)
return false; return false;
return std::nullopt; return std::nullopt;

View file

@ -37,12 +37,14 @@
#include <Qt> #include <Qt>
#include <QtContainerFwd> #include <QtContainerFwd>
#include "base/global.h"
namespace Utils::String namespace Utils::String
{ {
QString wildcardToRegexPattern(const QString &pattern); QString wildcardToRegexPattern(const QString &pattern);
template <typename T> template <typename T>
T unquote(const T &str, const QString &quotes = QChar('"')) T unquote(const T &str, const QString &quotes = u"\""_qs)
{ {
if (str.length() < 2) return str; if (str.length() < 2) return str;