Browse Source

Use QString literals

This patch covers src/app and src/base folders.
Follow up of ab64ee872b.
adaptive-webui-19844
Chocobo1 3 years ago
parent
commit
f0dd7b7dae
No known key found for this signature in database
GPG Key ID: 210D9C873253A68C
  1. 22
      src/app/application.cpp
  2. 20
      src/app/cmdoptions.cpp
  3. 2
      src/app/filelogger.cpp
  4. 15
      src/app/main.cpp
  5. 148
      src/app/upgrade.cpp
  6. 4
      src/base/bittorrent/bencoderesumedatastorage.cpp
  7. 14
      src/base/bittorrent/dbresumedatastorage.cpp
  8. 36
      src/base/bittorrent/session.cpp
  9. 13
      src/base/bittorrent/statistics.cpp
  10. 2
      src/base/bittorrent/torrentcreatorthread.cpp
  11. 4
      src/base/bittorrent/torrentimpl.cpp
  12. 4
      src/base/bittorrent/torrentinfo.cpp
  13. 54
      src/base/bittorrent/tracker.cpp
  14. 16
      src/base/http/connection.cpp
  15. 8
      src/base/http/requestparser.cpp
  16. 4
      src/base/iconprovider.cpp
  17. 47
      src/base/net/dnsupdater.cpp
  18. 2
      src/base/net/downloadhandlerimpl.cpp
  19. 2
      src/base/net/downloadmanager.cpp
  20. 49
      src/base/net/geoipdatabase.cpp
  21. 500
      src/base/net/geoipmanager.cpp
  22. 3
      src/base/net/proxyconfigurationmanager.h
  23. 60
      src/base/net/smtp.cpp
  24. 2
      src/base/path.cpp
  25. 6
      src/base/preferences.cpp
  26. 12
      src/base/rss/rss_autodownloader.cpp
  27. 86
      src/base/rss/rss_autodownloadrule.cpp
  28. 5
      src/base/rss/rss_autodownloadrule.h
  29. 2
      src/base/rss/rss_feed.cpp
  30. 4
      src/base/rss/rss_folder.h
  31. 85
      src/base/rss/rss_session.cpp
  32. 4
      src/base/search/searchhandler.cpp
  33. 50
      src/base/search/searchpluginmanager.cpp
  34. 6
      src/base/torrentfileswatcher.cpp
  35. 10
      src/base/utils/fs.cpp
  36. 230
      src/base/utils/misc.cpp
  37. 4
      src/base/utils/string.cpp
  38. 4
      src/base/utils/string.h

22
src/app/application.cpp

@ -136,10 +136,10 @@ Application::Application(int &argc, char **argv) @@ -136,10 +136,10 @@ Application::Application(int &argc, char **argv)
qRegisterMetaType<Log::Msg>("Log::Msg");
qRegisterMetaType<Log::Peer>("Log::Peer");
setApplicationName("qBittorrent");
setOrganizationDomain("qbittorrent.org");
setApplicationName(u"qBittorrent"_qs);
setOrganizationDomain(u"qbittorrent.org"_qs);
#if !defined(DISABLE_GUI)
setDesktopFileName("org.qbittorrent.qBittorrent");
setDesktopFileName(u"org.qbittorrent.qBittorrent"_qs);
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
setAttribute(Qt::AA_UseHighDpiPixmaps, true); // opt-in to the high DPI pixmap support
#endif
@ -176,12 +176,12 @@ Application::Application(int &argc, char **argv) @@ -176,12 +176,12 @@ Application::Application(int &argc, char **argv)
if (isFileLoggerEnabled())
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)
{
Logger::instance()->addMessage(tr("Running in portable mode. Auto detected profile folder at: %1").arg(profileDir.toString()));
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
{
@ -457,12 +457,12 @@ void Application::runExternalProgram(const BitTorrent::Torrent *torrent) const @@ -457,12 +457,12 @@ void Application::runExternalProgram(const BitTorrent::Torrent *torrent) const
void Application::sendNotificationEmail(const BitTorrent::Torrent *torrent)
{
// Prepare mail content
const QString content = tr("Torrent name: %1").arg(torrent->name()) + '\n'
+ tr("Torrent size: %1").arg(Utils::Misc::friendlyUnit(torrent->wantedSize())) + '\n'
+ tr("Save path: %1").arg(torrent->savePath().toString()) + "\n\n"
const QString content = tr("Torrent name: %1").arg(torrent->name()) + u'\n'
+ tr("Torrent size: %1").arg(Utils::Misc::friendlyUnit(torrent->wantedSize())) + u'\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")
.arg(Utils::Misc::userFriendlyDuration(torrent->activeTime())) + "\n\n\n"
+ tr("Thank you for using qBittorrent.") + '\n';
.arg(Utils::Misc::userFriendlyDuration(torrent->activeTime())) + u"\n\n\n"
+ tr("Thank you for using qBittorrent.") + u'\n';
// Send the notification email
const Preferences *pref = Preferences::instance();
@ -755,7 +755,7 @@ void Application::initializeTranslation() @@ -755,7 +755,7 @@ void Application::initializeTranslation()
installTranslator(&m_translator);
#ifndef DISABLE_GUI
if (localeStr.startsWith("ar") || localeStr.startsWith("he"))
if (localeStr.startsWith(u"ar") || localeStr.startsWith(u"he"))
{
qDebug("Right to Left mode");
setLayoutDirection(Qt::RightToLeft);

20
src/app/cmdoptions.cpp

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

2
src/app/filelogger.cpp

@ -89,7 +89,7 @@ void FileLogger::deleteOld(const int age, const FileLogAgeType ageType) @@ -89,7 +89,7 @@ void FileLogger::deleteOld(const int age, const FileLogAgeType ageType)
{
const QDateTime date = QDateTime::currentDateTime();
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));
for (const QFileInfo &file : fileList)

15
src/app/main.cpp

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

148
src/app/upgrade.cpp

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

4
src/base/bittorrent/bencoderesumedatastorage.cpp

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

14
src/base/bittorrent/dbresumedatastorage.cpp

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

36
src/base/bittorrent/session.cpp

@ -113,7 +113,7 @@ const Path CATEGORIES_FILE_NAME {u"categories.json"_qs}; @@ -113,7 +113,7 @@ const Path CATEGORIES_FILE_NAME {u"categories.json"_qs};
namespace
{
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)
{
@ -691,7 +691,7 @@ Path Session::downloadPath() const @@ -691,7 +691,7 @@ Path Session::downloadPath() const
bool Session::isValidCategoryName(const QString &name)
{
static const QRegularExpression re(R"(^([^\\\/]|[^\\\/]([^\\\/]|\/(?=[^\/]))*[^\\\/])$)");
static const QRegularExpression re(uR"(^([^\\\/]|[^\\\/]([^\\\/]|\/(?=[^\/]))*[^\\\/])$)"_qs);
if (!name.isEmpty() && (name.indexOf(re) != 0))
{
qDebug() << "Incorrect category name:" << name;
@ -708,7 +708,7 @@ QStringList Session::expandCategory(const QString &category) @@ -708,7 +708,7 @@ QStringList Session::expandCategory(const QString &category)
return result;
int index = 0;
while ((index = category.indexOf('/', index)) >= 0)
while ((index = category.indexOf(u'/', index)) >= 0)
{
result << category.left(index);
++index;
@ -824,7 +824,7 @@ bool Session::removeCategory(const QString &name) @@ -824,7 +824,7 @@ bool Session::removeCategory(const QString &name)
for (TorrentImpl *const torrent : asConst(m_torrents))
{
if (torrent->belongsToCategory(name))
torrent->setCategory("");
torrent->setCategory(u""_qs);
}
// remove stored category and its subcategories if exist
@ -832,7 +832,7 @@ bool Session::removeCategory(const QString &name) @@ -832,7 +832,7 @@ bool Session::removeCategory(const QString &name)
if (isSubcategoriesEnabled())
{
// remove subcategories
const QString test = name + '/';
const QString test = name + u'/';
Algorithm::removeIf(m_categories, [this, &test, &result](const QString &category, const CategoryOptions &)
{
if (category.startsWith(test))
@ -900,7 +900,7 @@ QSet<QString> Session::tags() const @@ -900,7 +900,7 @@ QSet<QString> Session::tags() const
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
@ -1138,7 +1138,7 @@ void Session::initializeNativeSession() @@ -1138,7 +1138,7 @@ void Session::initializeNativeSession()
pack.set_int(lt::settings_pack::alert_mask, alertMask);
pack.set_str(lt::settings_pack::peer_fingerprint, peerId);
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);
// Speed up exit
pack.set_int(lt::settings_pack::auto_scrape_interval, 1200); // 20 minutes
@ -1503,7 +1503,7 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack) @@ -1503,7 +1503,7 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack)
QStringList endpoints;
QStringList outgoingInterfaces;
const QString portString = ':' + QString::number(port());
const QString portString = u':' + QString::number(port());
for (const QString &ip : asConst(getListeningIPs()))
{
@ -1515,7 +1515,7 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack) @@ -1515,7 +1515,7 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack)
? Utils::Net::canonicalIPv6Addr(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("::")))
outgoingInterfaces << ip;
@ -1548,11 +1548,11 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack) @@ -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());
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;
}
@ -2144,7 +2144,7 @@ LoadTorrentParams Session::initLoadTorrentParams(const AddTorrentParams &addTorr @@ -2144,7 +2144,7 @@ LoadTorrentParams Session::initLoadTorrentParams(const AddTorrentParams &addTorr
const QString category = addTorrentParams.category;
if (!category.isEmpty() && !m_categories.contains(category) && !addCategory(category))
loadTorrentParams.category = "";
loadTorrentParams.category = u""_qs;
else
loadTorrentParams.category = category;
@ -5010,7 +5010,7 @@ void Session::handleFileErrorAlert(const lt::file_error_alert *p) @@ -5010,7 +5010,7 @@ void Session::handleFileErrorAlert(const lt::file_error_alert *p)
const QString msg = QString::fromStdString(p->message());
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);
emit fullDiskError(torrent, msg);
}
@ -5041,7 +5041,7 @@ void Session::handlePeerBlockedAlert(const lt::peer_blocked_alert *p) @@ -5041,7 +5041,7 @@ void Session::handlePeerBlockedAlert(const lt::peer_blocked_alert *p)
reason = tr("port filter", "this peer was blocked. Reason: port filter.");
break;
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;
case lt::peer_blocked_alert::privileged_ports:
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) @@ -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
break;
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;
}
@ -5075,13 +5075,13 @@ void Session::handleUrlSeedAlert(const lt::url_seed_alert *p) @@ -5075,13 +5075,13 @@ void Session::handleUrlSeedAlert(const lt::url_seed_alert *p)
if (p->error)
{
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);
}
else
{
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);
}
}
@ -5296,7 +5296,7 @@ void Session::handleTrackerAlert(const lt::tracker_alert *a) @@ -5296,7 +5296,7 @@ void Session::handleTrackerAlert(const lt::tracker_alert *a)
if (a->type() == lt::tracker_reply_alert::alert_type)
{
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);
}
}

13
src/base/bittorrent/statistics.cpp

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

2
src/base/bittorrent/torrentcreatorthread.cpp

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

4
src/base/bittorrent/torrentimpl.cpp

@ -746,7 +746,7 @@ bool TorrentImpl::belongsToCategory(const QString &category) const @@ -746,7 +746,7 @@ bool TorrentImpl::belongsToCategory(const QString &category) const
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 false;
@ -1843,7 +1843,7 @@ void TorrentImpl::handleFileRenamedAlert(const lt::file_renamed_alert *p) @@ -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
// be removed if they are empty
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
// We should compare path in a case sensitive manner even on case insensitive

4
src/base/bittorrent/torrentinfo.cpp

@ -122,7 +122,7 @@ nonstd::expected<TorrentInfo, QString> TorrentInfo::loadFromFile(const Path &pat @@ -122,7 +122,7 @@ nonstd::expected<TorrentInfo, QString> TorrentInfo::loadFromFile(const Path &pat
}
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())
@ -294,7 +294,7 @@ QVector<QUrl> TorrentInfo::urlSeeds() const @@ -294,7 +294,7 @@ QVector<QUrl> TorrentInfo::urlSeeds() const
for (const lt::web_seed_entry &webSeed : nativeWebSeeds)
{
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;

54
src/base/bittorrent/tracker.cpp

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

16
src/base/http/connection.cpp

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

8
src/base/http/requestparser.cpp

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

4
src/base/iconprovider.cpp

@ -58,11 +58,11 @@ IconProvider *IconProvider::instance() @@ -58,11 +58,11 @@ IconProvider *IconProvider::instance()
Path IconProvider::getIconPath(const QString &iconId) const
{
// 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())
return pathSvg;
const Path pathPng {":/icons/" + iconId + ".png"};
const Path pathPng {u":/icons/" + iconId + u".png"};
return pathPng;
}

47
src/base/net/dnsupdater.cpp

@ -32,6 +32,7 @@ @@ -32,6 +32,7 @@
#include <QRegularExpression>
#include <QUrlQuery>
#include "base/global.h"
#include "base/logger.h"
#include "base/net/downloadmanager.h"
#include "base/version.h"
@ -76,7 +77,7 @@ void DNSUpdater::checkPublicIP() @@ -76,7 +77,7 @@ void DNSUpdater::checkPublicIP()
Q_ASSERT(m_state == OK);
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);
m_lastIPCheckTime = QDateTime::currentDateTime();
@ -91,7 +92,7 @@ void DNSUpdater::ipRequestFinished(const DownloadResult &result) @@ -91,7 +92,7 @@ void DNSUpdater::ipRequestFinished(const DownloadResult &result)
}
// 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())
{
QString ipStr = ipRegexMatch.captured(1);
@ -124,7 +125,7 @@ void DNSUpdater::updateDNSService() @@ -124,7 +125,7 @@ void DNSUpdater::updateDNSService()
m_lastIPCheckTime = QDateTime::currentDateTime();
DownloadManager::instance()->download(
DownloadRequest(getUpdateUrl()).userAgent("qBittorrent/" QBT_VERSION_2)
DownloadRequest(getUpdateUrl()).userAgent(QStringLiteral("qBittorrent/" QBT_VERSION_2))
, this, &DNSUpdater::ipUpdateFinished);
}
@ -132,9 +133,9 @@ QString DNSUpdater::getUpdateUrl() const @@ -132,9 +133,9 @@ QString DNSUpdater::getUpdateUrl() const
{
QUrl url;
#ifdef QT_NO_OPENSSL
url.setScheme("http");
url.setScheme(u"http"_qs);
#else
url.setScheme("https");
url.setScheme(u"https"_qs);
#endif
url.setUserName(m_username);
url.setPassword(m_password);
@ -144,21 +145,21 @@ QString DNSUpdater::getUpdateUrl() const @@ -144,21 +145,21 @@ QString DNSUpdater::getUpdateUrl() const
switch (m_service)
{
case DNS::Service::DynDNS:
url.setHost("members.dyndns.org");
url.setHost(u"members.dyndns.org"_qs);
break;
case DNS::Service::NoIP:
url.setHost("dynupdate.no-ip.com");
url.setHost(u"dynupdate.no-ip.com"_qs);
break;
default:
qWarning() << "Unrecognized Dynamic DNS service!";
Q_ASSERT(false);
break;
}
url.setPath("/nic/update");
url.setPath(u"/nic/update"_qs);
QUrlQuery urlQuery(url);
urlQuery.addQueryItem("hostname", m_domain);
urlQuery.addQueryItem("myip", m_lastIP.toString());
urlQuery.addQueryItem(u"hostname"_qs, m_domain);
urlQuery.addQueryItem(u"myip"_qs, m_lastIP.toString());
url.setQuery(urlQuery);
Q_ASSERT(url.isValid());
@ -169,7 +170,7 @@ QString DNSUpdater::getUpdateUrl() const @@ -169,7 +170,7 @@ QString DNSUpdater::getUpdateUrl() const
void DNSUpdater::ipUpdateFinished(const DownloadResult &result)
{
if (result.status == DownloadStatus::Success)
processIPUpdateReply(result.data);
processIPUpdateReply(QString::fromUtf8(result.data));
else
qWarning() << "IP update failed:" << result.errorString;
}
@ -178,16 +179,16 @@ void DNSUpdater::processIPUpdateReply(const QString &reply) @@ -178,16 +179,16 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
{
Logger *const logger = Logger::instance();
qDebug() << Q_FUNC_INFO << reply;
const QString code = reply.split(' ').first();
const QString code = reply.split(u' ').first();
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);
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);
m_lastIP.clear();
@ -198,21 +199,21 @@ void DNSUpdater::processIPUpdateReply(const QString &reply) @@ -198,21 +199,21 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
// Everything below is an error, stop updating until the user updates something
m_ipCheckTimer.stop();
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);
m_state = INVALID_CREDS;
return;
}
if (code == "badauth")
if (code == u"badauth")
{
logger->addMessage(tr("Dynamic DNS error: Invalid username/password."), Log::CRITICAL);
m_state = INVALID_CREDS;
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."),
Log::CRITICAL);
@ -220,15 +221,15 @@ void DNSUpdater::processIPUpdateReply(const QString &reply) @@ -220,15 +221,15 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
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);
m_state = FATAL;
return;
}
if (code == "abuse")
if (code == u"abuse")
{
logger->addMessage(tr("Dynamic DNS error: Your username was blocked due to abuse."), Log::CRITICAL);
m_state = FATAL;
@ -250,7 +251,7 @@ void DNSUpdater::updateCredentials() @@ -250,7 +251,7 @@ void DNSUpdater::updateCredentials()
if (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())
{
logger->addMessage(tr("Dynamic DNS error: supplied domain name is invalid."), Log::CRITICAL);
@ -301,9 +302,9 @@ QUrl DNSUpdater::getRegistrationUrl(const DNS::Service service) @@ -301,9 +302,9 @@ QUrl DNSUpdater::getRegistrationUrl(const DNS::Service service)
switch (service)
{
case DNS::Service::DynDNS:
return {"https://account.dyn.com/entrance/"};
return {u"https://account.dyn.com/entrance/"_qs};
case DNS::Service::NoIP:
return {"https://www.noip.com/remote-access"};
return {u"https://www.noip.com/remote-access"_qs};
default:
Q_ASSERT(false);
break;

2
src/base/net/downloadhandlerimpl.cpp

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

2
src/base/net/downloadmanager.cpp

@ -293,7 +293,7 @@ void Net::DownloadManager::ignoreSslErrors(QNetworkReply *reply, const QList<QSs @@ -293,7 +293,7 @@ void Net::DownloadManager::ignoreSslErrors(QNetworkReply *reply, const QList<QSs
QStringList errorList;
for (const QSslError &error : errors)
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
reply->ignoreSslErrors();

49
src/base/net/geoipdatabase.cpp

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

500
src/base/net/geoipmanager.cpp

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

3
src/base/net/proxyconfigurationmanager.h

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

60
src/base/net/smtp.cpp

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

2
src/base/path.cpp

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

6
src/base/preferences.cpp

@ -572,7 +572,7 @@ void Preferences::setWebUiAuthSubnetWhitelist(QStringList subnets) @@ -572,7 +572,7 @@ void Preferences::setWebUiAuthSubnetWhitelist(QStringList subnets)
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)
@ -582,7 +582,7 @@ void Preferences::setServerDomains(const QString &str) @@ -582,7 +582,7 @@ void Preferences::setServerDomains(const QString &str)
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)
@ -1614,7 +1614,7 @@ void Preferences::setNetworkCookies(const QList<QNetworkCookie> &cookies) @@ -1614,7 +1614,7 @@ void Preferences::setNetworkCookies(const QList<QNetworkCookie> &cookies)
QStringList rawCookies;
rawCookies.reserve(cookies.size());
for (const QNetworkCookie &cookie : cookies)
rawCookies << cookie.toRawForm();
rawCookies << QString::fromLatin1(cookie.toRawForm());
setValue(u"Network/Cookies"_qs, rawCookies);
}

12
src/base/rss/rss_autodownloader.cpp

@ -94,7 +94,7 @@ QPointer<AutoDownloader> AutoDownloader::m_instance = nullptr; @@ -94,7 +94,7 @@ QPointer<AutoDownloader> AutoDownloader::m_instance = nullptr;
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()
@ -162,7 +162,7 @@ bool AutoDownloader::hasRule(const QString &ruleName) const @@ -162,7 +162,7 @@ bool AutoDownloader::hasRule(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
@ -289,10 +289,10 @@ QStringList AutoDownloader::smartEpisodeFilters() const @@ -289,10 +289,10 @@ QStringList AutoDownloader::smartEpisodeFilters() const
{
const QStringList defaultFilters =
{
"s(\\d+)e(\\d+)", // Format 1: s01e01
"(\\d+)x(\\d+)", // Format 2: 01x01
"(\\d{4}[.\\-]\\d{1,2}[.\\-]\\d{1,2})", // Format 3: 2017.01.01
"(\\d{1,2}[.\\-]\\d{1,2}[.\\-]\\d{4})" // Format 4: 01.01.2017
u"s(\\d+)e(\\d+)"_qs, // Format 1: s01e01
u"(\\d+)x(\\d+)"_qs, // Format 2: 01x01
u"(\\d{4}[.\\-]\\d{1,2}[.\\-]\\d{1,2})"_qs, // Format 3: 2017.01.01
u"(\\d{1,2}[.\\-]\\d{1,2}[.\\-]\\d{4})"_qs // Format 4: 01.01.2017
};
return defaultFilters;
}

86
src/base/rss/rss_autodownloadrule.cpp

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

5
src/base/rss/rss_autodownloadrule.h

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

2
src/base/rss/rss_feed.cpp

@ -324,7 +324,7 @@ void Feed::loadArticles(const QByteArray &data) @@ -324,7 +324,7 @@ void Feed::loadArticles(const QByteArray &data)
void Feed::loadArticlesLegacy()
{
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()))
{

4
src/base/rss/rss_folder.h

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

85
src/base/rss/rss_session.cpp

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

4
src/base/search/searchhandler.cpp

@ -69,13 +69,13 @@ SearchHandler::SearchHandler(const QString &pattern, const QString &category, co @@ -69,13 +69,13 @@ SearchHandler::SearchHandler(const QString &pattern, const QString &category, co
const QStringList params
{
(m_manager->engineLocation() / Path(u"nova2.py"_qs)).toString(),
m_usedPlugins.join(','),
m_usedPlugins.join(u','),
m_category
};
// Launch search
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::readyReadStandardOutput, this, &SearchHandler::readSearchOutput);

50
src/base/search/searchpluginmanager.cpp

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

6
src/base/torrentfileswatcher.cpp

@ -324,7 +324,7 @@ void TorrentFilesWatcher::load() @@ -324,7 +324,7 @@ void TorrentFilesWatcher::load()
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)
{
@ -356,7 +356,7 @@ void TorrentFilesWatcher::loadLegacy() @@ -356,7 +356,7 @@ void TorrentFilesWatcher::loadLegacy()
}
store();
SettingsStorage::instance()->removeValue("Preferences/Downloads/ScanDirsV2");
SettingsStorage::instance()->removeValue(u"Preferences/Downloads/ScanDirsV2"_qs);
}
void TorrentFilesWatcher::store() const
@ -497,7 +497,7 @@ void TorrentFilesWatcher::Worker::processWatchedFolder(const Path &path) @@ -497,7 +497,7 @@ void TorrentFilesWatcher::Worker::processWatchedFolder(const Path &path)
void TorrentFilesWatcher::Worker::processFolder(const Path &path, const Path &watchedFolderPath
, 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())
{
const Path filePath {dirIter.next()};

10
src/base/utils/fs.cpp

@ -89,13 +89,13 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const Path &path) @@ -89,13 +89,13 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const Path &path)
};
// 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};
while (iter.hasNext())
dirList << iter.next() + '/';
dirList << iter.next() + u'/';
// sort descending by directory depth
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))
{
@ -111,7 +111,7 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const Path &path) @@ -111,7 +111,7 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const Path &path)
// temp files on linux usually end with '~', e.g. `filename~`
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)
continue;
@ -220,7 +220,7 @@ bool Utils::Fs::isRegularFile(const Path &path) @@ -220,7 +220,7 @@ bool Utils::Fs::isRegularFile(const Path &path)
// analyse erno and log the error
const auto err = errno;
qDebug("Could not get file stats for path '%s'. Error: %s"
, qUtf8Printable(path.toString()), qUtf8Printable(strerror(err)));
, qUtf8Printable(path.toString()), strerror(err));
return false;
}

230
src/base/utils/misc.cpp

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

4
src/base/utils/string.cpp

@ -71,9 +71,9 @@ QString Utils::String::wildcardToRegexPattern(const QString &pattern) @@ -71,9 +71,9 @@ QString Utils::String::wildcardToRegexPattern(const QString &pattern)
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;
if (string.compare("false", Qt::CaseInsensitive) == 0)
if (string.compare(u"false", Qt::CaseInsensitive) == 0)
return false;
return std::nullopt;

4
src/base/utils/string.h

@ -37,12 +37,14 @@ @@ -37,12 +37,14 @@
#include <Qt>
#include <QtContainerFwd>
#include "base/global.h"
namespace Utils::String
{
QString wildcardToRegexPattern(const QString &pattern);
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;

Loading…
Cancel
Save