Revise string literal usage

PR #16703.
This commit is contained in:
Chocobo1
2022-03-26 11:53:50 +08:00
committed by GitHub
parent e1abcc684a
commit 4ca6de2b54
55 changed files with 485 additions and 472 deletions

View File

@@ -37,7 +37,7 @@
AsyncFileStorage::AsyncFileStorage(const Path &storageFolderPath, QObject *parent)
: QObject(parent)
, m_storageDir(storageFolderPath)
, m_lockFile((m_storageDir / Path(QStringLiteral("storage.lock"))).data())
, m_lockFile((m_storageDir / Path(u"storage.lock"_qs)).data())
{
Q_ASSERT(m_storageDir.isAbsolute());

View File

@@ -103,8 +103,8 @@ BitTorrent::BencodeResumeDataStorage::BencodeResumeDataStorage(const Path &path,
.arg(m_resumeDataPath.toString()));
}
const QRegularExpression filenamePattern {QLatin1String("^([A-Fa-f0-9]{40})\\.fastresume$")};
const QStringList filenames = QDir(m_resumeDataPath.data()).entryList(QStringList(QLatin1String("*.fastresume")), QDir::Files, QDir::Unsorted);
const QRegularExpression filenamePattern {u"^([A-Fa-f0-9]{40})\\.fastresume$"_qs};
const QStringList filenames = QDir(m_resumeDataPath.data()).entryList(QStringList(u"*.fastresume"_qs), QDir::Files, QDir::Unsorted);
m_registeredTorrents.reserve(filenames.size());
for (const QString &filename : filenames)
@@ -137,8 +137,8 @@ QVector<BitTorrent::TorrentID> BitTorrent::BencodeResumeDataStorage::registeredT
std::optional<BitTorrent::LoadTorrentParams> BitTorrent::BencodeResumeDataStorage::load(const TorrentID &id) const
{
const QString idString = id.toString();
const Path fastresumePath = m_resumeDataPath / Path(idString + QLatin1String(".fastresume"));
const Path torrentFilePath = m_resumeDataPath / Path(idString + QLatin1String(".torrent"));
const Path fastresumePath = m_resumeDataPath / Path(idString + u".fastresume");
const Path torrentFilePath = m_resumeDataPath / Path(idString + u".torrent");
QFile resumeDataFile {fastresumePath.data()};
if (!resumeDataFile.open(QIODevice::ReadOnly))
@@ -284,7 +284,7 @@ void BitTorrent::BencodeResumeDataStorage::loadQueue(const Path &queueFilename)
if (queueFile.open(QFile::ReadOnly))
{
const QRegularExpression hashPattern {QLatin1String("^([A-Fa-f0-9]{40})$")};
const QRegularExpression hashPattern {u"^([A-Fa-f0-9]{40})$"_qs};
QString line;
int start = 0;
while (!(line = QString::fromLatin1(queueFile.readLine().trimmed())).isEmpty())
@@ -353,7 +353,7 @@ void BitTorrent::BencodeResumeDataStorage::Worker::store(const TorrentID &id, co
metadataDict.insert(dataDict.extract("created by"));
metadataDict.insert(dataDict.extract("comment"));
const Path torrentFilepath = m_resumeDataDir / Path(QString::fromLatin1("%1.torrent").arg(id.toString()));
const Path torrentFilepath = m_resumeDataDir / Path(u"%1.torrent"_qs.arg(id.toString()));
const nonstd::expected<void, QString> result = Utils::IO::saveToFile(torrentFilepath, metadata);
if (!result)
{
@@ -378,7 +378,7 @@ void BitTorrent::BencodeResumeDataStorage::Worker::store(const TorrentID &id, co
data["qBt-downloadPath"] = Profile::instance()->toPortablePath(resumeData.downloadPath).data().toStdString();
}
const Path resumeFilepath = m_resumeDataDir / Path(QString::fromLatin1("%1.fastresume").arg(id.toString()));
const Path resumeFilepath = m_resumeDataDir / Path(u"%1.fastresume"_qs.arg(id.toString()));
const nonstd::expected<void, QString> result = Utils::IO::saveToFile(resumeFilepath, data);
if (!result)
{
@@ -389,10 +389,10 @@ void BitTorrent::BencodeResumeDataStorage::Worker::store(const TorrentID &id, co
void BitTorrent::BencodeResumeDataStorage::Worker::remove(const TorrentID &id) const
{
const Path resumeFilename {QString::fromLatin1("%1.fastresume").arg(id.toString())};
const Path resumeFilename {u"%1.fastresume"_qs.arg(id.toString())};
Utils::Fs::removeFile(m_resumeDataDir / resumeFilename);
const Path torrentFilename {QString::fromLatin1("%1.torrent").arg(id.toString())};
const Path torrentFilename {u"%1.torrent"_qs.arg(id.toString())};
Utils::Fs::removeFile(m_resumeDataDir / torrentFilename);
}

View File

@@ -31,8 +31,10 @@
#include <QJsonObject>
#include <QJsonValue>
const QString OPTION_SAVEPATH {QStringLiteral("save_path")};
const QString OPTION_DOWNLOADPATH {QStringLiteral("download_path")};
#include "base/global.h"
const QString OPTION_SAVEPATH = u"save_path"_qs;
const QString OPTION_DOWNLOADPATH = u"download_path"_qs;
BitTorrent::CategoryOptions BitTorrent::CategoryOptions::fromJSON(const QJsonObject &jsonObj)
{

View File

@@ -30,4 +30,6 @@
#include <QString>
inline const QString QB_EXT {QStringLiteral(".!qB")};
#include "base/global.h"
inline const QString QB_EXT = u".!qB"_qs;

View File

@@ -75,7 +75,7 @@ namespace
Column makeColumn(const char *columnName)
{
return {QLatin1String(columnName), (QLatin1Char(':') + QLatin1String(columnName))};
return {QString::fromLatin1(columnName), (u':' + QString::fromLatin1(columnName))};
}
const Column DB_COLUMN_ID = makeColumn("id");
@@ -105,14 +105,14 @@ namespace
QString quoted(const QString &name)
{
const QLatin1Char quote {'`'};
const QChar quote = u'`';
return (quote + name + quote);
}
QString makeCreateTableStatement(const QString &tableName, const QStringList &items)
{
return QString::fromLatin1("CREATE TABLE %1 (%2)").arg(quoted(tableName), items.join(QLatin1Char(',')));
return u"CREATE TABLE %1 (%2)"_qs.arg(quoted(tableName), items.join(u','));
}
std::pair<QString, QString> joinColumns(const QVector<Column> &columns)
@@ -131,8 +131,8 @@ namespace
values.reserve(valuesSize);
for (const Column &column : columns)
{
names.append(quoted(column.name) + QLatin1Char(','));
values.append(column.placeholder + QLatin1Char(','));
names.append(quoted(column.name) + u',');
values.append(column.placeholder + u',');
}
names.chop(1);
values.chop(1);
@@ -143,27 +143,27 @@ namespace
QString makeInsertStatement(const QString &tableName, const QVector<Column> &columns)
{
const auto [names, values] = joinColumns(columns);
return QString::fromLatin1("INSERT INTO %1 (%2) VALUES (%3)")
return u"INSERT INTO %1 (%2) VALUES (%3)"_qs
.arg(quoted(tableName), names, values);
}
QString makeUpdateStatement(const QString &tableName, const QVector<Column> &columns)
{
const auto [names, values] = joinColumns(columns);
return QString::fromLatin1("UPDATE %1 SET (%2) = (%3)")
return u"UPDATE %1 SET (%2) = (%3)"_qs
.arg(quoted(tableName), names, values);
}
QString makeOnConflictUpdateStatement(const Column &constraint, const QVector<Column> &columns)
{
const auto [names, values] = joinColumns(columns);
return QString::fromLatin1(" ON CONFLICT (%1) DO UPDATE SET (%2) = (%3)")
return u" ON CONFLICT (%1) DO UPDATE SET (%2) = (%3)"_qs
.arg(quoted(constraint.name), names, values);
}
QString makeColumnDefinition(const Column &column, const char *definition)
{
return QString::fromLatin1("%1 %2").arg(quoted(column.name), QLatin1String(definition));
return u"%1 %2"_qs.arg(quoted(column.name), QString::fromLatin1(definition));
}
}
@@ -195,7 +195,7 @@ BitTorrent::DBResumeDataStorage::DBResumeDataStorage(const Path &dbPath, QObject
{
const bool needCreateDB = !dbPath.exists();
auto db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), DB_CONNECTION_NAME);
auto db = QSqlDatabase::addDatabase(u"QSQLITE"_qs, DB_CONNECTION_NAME);
db.setDatabaseName(dbPath.data());
if (!db.open())
throw RuntimeError(db.lastError().text());
@@ -211,7 +211,7 @@ BitTorrent::DBResumeDataStorage::DBResumeDataStorage(const Path &dbPath, QObject
updateDBFromVersion1();
}
m_asyncWorker = new Worker(dbPath, QLatin1String("ResumeDataStorageWorker"));
m_asyncWorker = new Worker(dbPath, u"ResumeDataStorageWorker"_qs);
m_asyncWorker->moveToThread(m_ioThread);
connect(m_ioThread, &QThread::finished, m_asyncWorker, &QObject::deleteLater);
m_ioThread->start();
@@ -244,7 +244,7 @@ BitTorrent::DBResumeDataStorage::~DBResumeDataStorage()
QVector<BitTorrent::TorrentID> BitTorrent::DBResumeDataStorage::registeredTorrents() const
{
const auto selectTorrentIDStatement = QString::fromLatin1("SELECT %1 FROM %2 ORDER BY %3;")
const auto selectTorrentIDStatement = u"SELECT %1 FROM %2 ORDER BY %3;"_qs
.arg(quoted(DB_COLUMN_TORRENT_ID.name), quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_QUEUE_POSITION.name));
auto db = QSqlDatabase::database(DB_CONNECTION_NAME);
@@ -263,9 +263,8 @@ QVector<BitTorrent::TorrentID> BitTorrent::DBResumeDataStorage::registeredTorren
std::optional<BitTorrent::LoadTorrentParams> BitTorrent::DBResumeDataStorage::load(const TorrentID &id) const
{
const QString selectTorrentStatement =
QString(QLatin1String("SELECT * FROM %1 WHERE %2 = %3;"))
.arg(quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_TORRENT_ID.name), DB_COLUMN_TORRENT_ID.placeholder);
const QString selectTorrentStatement = u"SELECT * FROM %1 WHERE %2 = %3;"_qs
.arg(quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_TORRENT_ID.name), DB_COLUMN_TORRENT_ID.placeholder);
auto db = QSqlDatabase::database(DB_CONNECTION_NAME);
QSqlQuery query {db};
@@ -295,7 +294,7 @@ std::optional<BitTorrent::LoadTorrentParams> BitTorrent::DBResumeDataStorage::lo
const QString tagsData = query.value(DB_COLUMN_TAGS.name).toString();
if (!tagsData.isEmpty())
{
const QStringList tagList = tagsData.split(QLatin1Char(','));
const QStringList tagList = tagsData.split(u',');
resumeData.tags.insert(tagList.cbegin(), tagList.cend());
}
resumeData.hasSeedStatus = query.value(DB_COLUMN_HAS_SEED_STATUS.name).toBool();
@@ -361,7 +360,7 @@ void BitTorrent::DBResumeDataStorage::storeQueue(const QVector<TorrentID> &queue
int BitTorrent::DBResumeDataStorage::currentDBVersion() const
{
const auto selectDBVersionStatement = QString::fromLatin1("SELECT %1 FROM %2 WHERE %3 = %4;")
const auto selectDBVersionStatement = u"SELECT %1 FROM %2 WHERE %3 = %4;"_qs
.arg(quoted(DB_COLUMN_VALUE.name), quoted(DB_TABLE_META), quoted(DB_COLUMN_NAME.name), DB_COLUMN_NAME.placeholder);
auto db = QSqlDatabase::database(DB_CONNECTION_NAME);
@@ -459,7 +458,7 @@ void BitTorrent::DBResumeDataStorage::updateDBFromVersion1() const
try
{
const auto alterTableTorrentsQuery = QString::fromLatin1("ALTER TABLE %1 ADD %2")
const auto alterTableTorrentsQuery = u"ALTER TABLE %1 ADD %2"_qs
.arg(quoted(DB_TABLE_TORRENTS), makeColumnDefinition(DB_COLUMN_DOWNLOAD_PATH, "TEXT"));
if (!query.exec(alterTableTorrentsQuery))
throw RuntimeError(query.lastError().text());
@@ -492,7 +491,7 @@ BitTorrent::DBResumeDataStorage::Worker::Worker(const Path &dbPath, const QStrin
void BitTorrent::DBResumeDataStorage::Worker::openDatabase() const
{
auto db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), m_connectionName);
auto db = QSqlDatabase::addDatabase(u"QSQLITE"_qs, m_connectionName);
db.setDatabaseName(m_path.data());
if (!db.open())
throw RuntimeError(db.lastError().text());
@@ -592,7 +591,7 @@ void BitTorrent::DBResumeDataStorage::Worker::store(const TorrentID &id, const L
query.bindValue(DB_COLUMN_NAME.placeholder, resumeData.name);
query.bindValue(DB_COLUMN_CATEGORY.placeholder, resumeData.category);
query.bindValue(DB_COLUMN_TAGS.placeholder, (resumeData.tags.isEmpty()
? QVariant(QVariant::String) : resumeData.tags.join(QLatin1String(","))));
? QVariant(QVariant::String) : resumeData.tags.join(u","_qs)));
query.bindValue(DB_COLUMN_CONTENT_LAYOUT.placeholder, Utils::String::fromEnum(resumeData.contentLayout));
query.bindValue(DB_COLUMN_RATIO_LIMIT.placeholder, static_cast<int>(resumeData.ratioLimit * 1000));
query.bindValue(DB_COLUMN_SEEDING_TIME_LIMIT.placeholder, resumeData.seedingTimeLimit);
@@ -623,7 +622,7 @@ void BitTorrent::DBResumeDataStorage::Worker::store(const TorrentID &id, const L
void BitTorrent::DBResumeDataStorage::Worker::remove(const TorrentID &id) const
{
const auto deleteTorrentStatement = QString::fromLatin1("DELETE FROM %1 WHERE %2 = %3;")
const auto deleteTorrentStatement = u"DELETE FROM %1 WHERE %2 = %3;"_qs
.arg(quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_TORRENT_ID.name), DB_COLUMN_TORRENT_ID.placeholder);
auto db = QSqlDatabase::database(m_connectionName);
@@ -647,7 +646,7 @@ void BitTorrent::DBResumeDataStorage::Worker::remove(const TorrentID &id) const
void BitTorrent::DBResumeDataStorage::Worker::storeQueue(const QVector<TorrentID> &queue) const
{
const auto updateQueuePosStatement = QString::fromLatin1("UPDATE %1 SET %2 = %3 WHERE %4 = %5;")
const auto updateQueuePosStatement = u"UPDATE %1 SET %2 = %3 WHERE %4 = %5;"_qs
.arg(quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_QUEUE_POSITION.name), DB_COLUMN_QUEUE_POSITION.placeholder
, quoted(DB_COLUMN_TORRENT_ID.name), DB_COLUMN_TORRENT_ID.placeholder);

View File

@@ -35,6 +35,7 @@
#include <QDataStream>
#include <QFile>
#include "base/global.h"
#include "base/logger.h"
namespace
@@ -617,17 +618,17 @@ void FilterParserThread::run()
{
qDebug("Processing filter file");
int ruleCount = 0;
if (m_filePath.hasExtension(QLatin1String(".p2p")))
if (m_filePath.hasExtension(u".p2p"_qs))
{
// PeerGuardian p2p file
ruleCount = parseP2PFilterFile();
}
else if (m_filePath.hasExtension(QLatin1String(".p2b")))
else if (m_filePath.hasExtension(u".p2b"_qs))
{
// PeerGuardian p2b file
ruleCount = parseP2BFilterFile();
}
else if (m_filePath.hasExtension(QLatin1String(".dat")))
else if (m_filePath.hasExtension(u".dat"_qs))
{
// eMule DAT format
ruleCount = parseDATFilterFile();

View File

@@ -35,6 +35,7 @@
#include <QRegularExpression>
#include "base/global.h"
#include "infohash.h"
namespace
@@ -52,9 +53,9 @@ namespace
const int V1_BASE32_SIZE = SHA1Hash::length() * 1.6;
return ((((string.size() == V1_HEX_SIZE))
&& !string.contains(QRegularExpression(QLatin1String("[^0-9A-Fa-f]"))))
&& !string.contains(QRegularExpression(u"[^0-9A-Fa-f]"_qs)))
|| ((string.size() == V1_BASE32_SIZE)
&& !string.contains(QRegularExpression(QLatin1String("[^2-7A-Za-z]")))));
&& !string.contains(QRegularExpression(u"[^2-7A-Za-z]"_qs))));
}
bool isV2Hash(const QString &string)
@@ -65,7 +66,7 @@ namespace
const int V2_HEX_SIZE = SHA256Hash::length() * 2;
return (string.size() == V2_HEX_SIZE)
&& !string.contains(QRegularExpression(QLatin1String("[^0-9A-Fa-f]")));
&& !string.contains(QRegularExpression(u"[^0-9A-Fa-f]"_qs));
}
}
@@ -80,9 +81,9 @@ MagnetUri::MagnetUri(const QString &source)
if (source.isEmpty()) return;
if (isV2Hash(source))
m_url = QString::fromLatin1("magnet:?xt=urn:btmh:1220") + source; // 0x12 0x20 is the "multihash format" tag for the SHA-256 hashing scheme.
m_url = u"magnet:?xt=urn:btmh:1220" + source; // 0x12 0x20 is the "multihash format" tag for the SHA-256 hashing scheme.
else if (isV1Hash(source))
m_url = QString::fromLatin1("magnet:?xt=urn:btih:") + source;
m_url = u"magnet:?xt=urn:btih:" + source;
lt::error_code ec;
lt::parse_magnet_uri(m_url.toStdString(), m_addTorrentParams, ec);

View File

@@ -36,9 +36,9 @@ PeerAddress PeerAddress::parse(const QStringView address)
{
QList<QStringView> ipPort;
if (address.startsWith(u'[') && address.contains(QLatin1String("]:")))
if (address.startsWith(u'[') && address.contains(u"]:"))
{ // IPv6
ipPort = address.split(QString::fromLatin1("]:"));
ipPort = address.split(u"]:");
ipPort[0] = ipPort[0].mid(1); // chop '['
}
else if (address.contains(u':'))

View File

@@ -217,8 +217,8 @@ QString PeerInfo::connectionType() const
return C_UTP;
return (m_nativeInfo.connection_type == lt::peer_info::standard_bittorrent)
? QLatin1String {"BT"}
: QLatin1String {"Web"};
? u"BT"_qs
: u"Web"_qs;
}
qreal PeerInfo::calcRelevance(const Torrent *torrent) const
@@ -242,8 +242,8 @@ void PeerInfo::determineFlags()
{
const auto updateFlags = [this](const QChar specifier, const QString &explanation)
{
m_flags += (specifier + QLatin1Char(' '));
m_flagsDescription += QString::fromLatin1("%1 = %2\n").arg(specifier, explanation);
m_flags += (specifier + u' ');
m_flagsDescription += u"%1 = %2\n"_qs.arg(specifier, explanation);
};
if (isInteresting())
@@ -251,12 +251,12 @@ void PeerInfo::determineFlags()
if (isRemoteChocked())
{
// d = Your client wants to download, but peer doesn't want to send (interested and choked)
updateFlags(QLatin1Char('d'), tr("Interested (local) and choked (peer)"));
updateFlags(u'd', tr("Interested (local) and choked (peer)"));
}
else
{
// D = Currently downloading (interested and not choked)
updateFlags(QLatin1Char('D'), tr("Interested (local) and unchoked (peer)"));
updateFlags(u'D', tr("Interested (local) and unchoked (peer)"));
}
}
@@ -265,58 +265,58 @@ void PeerInfo::determineFlags()
if (isChocked())
{
// u = Peer wants your client to upload, but your client doesn't want to (interested and choked)
updateFlags(QLatin1Char('u'), tr("Interested (peer) and choked (local)"));
updateFlags(u'u', tr("Interested (peer) and choked (local)"));
}
else
{
// U = Currently uploading (interested and not choked)
updateFlags(QLatin1Char('U'), tr("Interested (peer) and unchoked (local)"));
updateFlags(u'U', tr("Interested (peer) and unchoked (local)"));
}
}
// K = Peer is unchoking your client, but your client is not interested
if (!isRemoteChocked() && !isInteresting())
updateFlags(QLatin1Char('K'), tr("Not interested (local) and unchoked (peer)"));
updateFlags(u'K', tr("Not interested (local) and unchoked (peer)"));
// ? = Your client unchoked the peer but the peer is not interested
if (!isChocked() && !isRemoteInterested())
updateFlags(QLatin1Char('?'), tr("Not interested (peer) and unchoked (local)"));
updateFlags(u'?', tr("Not interested (peer) and unchoked (local)"));
// O = Optimistic unchoke
if (optimisticUnchoke())
updateFlags(QLatin1Char('O'), tr("Optimistic unchoke"));
updateFlags(u'O', tr("Optimistic unchoke"));
// S = Peer is snubbed
if (isSnubbed())
updateFlags(QLatin1Char('S'), tr("Peer snubbed"));
updateFlags(u'S', tr("Peer snubbed"));
// I = Peer is an incoming connection
if (!isLocalConnection())
updateFlags(QLatin1Char('I'), tr("Incoming connection"));
updateFlags(u'I', tr("Incoming connection"));
// H = Peer was obtained through DHT
if (fromDHT())
updateFlags(QLatin1Char('H'), tr("Peer from DHT"));
updateFlags(u'H', tr("Peer from DHT"));
// X = Peer was included in peerlists obtained through Peer Exchange (PEX)
if (fromPeX())
updateFlags(QLatin1Char('X'), tr("Peer from PEX"));
updateFlags(u'X', tr("Peer from PEX"));
// L = Peer is local
if (fromLSD())
updateFlags(QLatin1Char('L'), tr("Peer from LSD"));
updateFlags(u'L', tr("Peer from LSD"));
// E = Peer is using Protocol Encryption (all traffic)
if (isRC4Encrypted())
updateFlags(QLatin1Char('E'), tr("Encrypted traffic"));
updateFlags(u'E', tr("Encrypted traffic"));
// e = Peer is using Protocol Encryption (handshake)
if (isPlaintextEncrypted())
updateFlags(QLatin1Char('e'), tr("Encrypted handshake"));
updateFlags(u'e', tr("Encrypted handshake"));
// P = Peer is using uTorrent uTP
if (useUTPSocket())
updateFlags(QLatin1Char('P'), C_UTP);
updateFlags(u'P', C_UTP);
m_flags.chop(1);
m_flagsDescription.chop(1);

View File

@@ -186,33 +186,33 @@ namespace
{
#ifdef QBT_USES_LIBTORRENT2
case lt::socket_type_t::http:
return QLatin1String("HTTP");
return u"HTTP"_qs;
case lt::socket_type_t::http_ssl:
return QLatin1String("HTTP_SSL");
return u"HTTP_SSL"_qs;
#endif
case lt::socket_type_t::i2p:
return QLatin1String("I2P");
return u"I2P"_qs;
case lt::socket_type_t::socks5:
return QLatin1String("SOCKS5");
return u"SOCKS5"_qs;
#ifdef QBT_USES_LIBTORRENT2
case lt::socket_type_t::socks5_ssl:
return QLatin1String("SOCKS5_SSL");
return u"SOCKS5_SSL"_qs;
#endif
case lt::socket_type_t::tcp:
return QLatin1String("TCP");
return u"TCP"_qs;
case lt::socket_type_t::tcp_ssl:
return QLatin1String("TCP_SSL");
return u"TCP_SSL"_qs;
#ifdef QBT_USES_LIBTORRENT2
case lt::socket_type_t::utp:
return QLatin1String("UTP");
return u"UTP"_qs;
#else
case lt::socket_type_t::udp:
return QLatin1String("UDP");
return u"UDP"_qs;
#endif
case lt::socket_type_t::utp_ssl:
return QLatin1String("UTP_SSL");
return u"UTP_SSL"_qs;
}
return QLatin1String("INVALID");
return u"INVALID"_qs;
}
QString toString(const lt::address &address)
@@ -1523,7 +1523,7 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack)
endpoints << ((isIPv6 ? (u'[' + ip + u']') : ip) + portString);
if ((ip != QLatin1String("0.0.0.0")) && (ip != QLatin1String("::")))
if ((ip != u"0.0.0.0") && (ip != u"::"))
outgoingInterfaces << ip;
}
else
@@ -1709,23 +1709,23 @@ void Session::processShareLimits()
if (m_maxRatioAction == Remove)
{
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Removed torrent."), torrentName));
LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Removed torrent."), torrentName));
deleteTorrent(torrent->id());
}
else if (m_maxRatioAction == DeleteFiles)
{
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Removed torrent and deleted its content."), torrentName));
LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Removed torrent and deleted its content."), torrentName));
deleteTorrent(torrent->id(), DeleteTorrentAndFiles);
}
else if ((m_maxRatioAction == Pause) && !torrent->isPaused())
{
torrent->pause();
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Torrent paused."), torrentName));
LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Torrent paused."), torrentName));
}
else if ((m_maxRatioAction == EnableSuperSeeding) && !torrent->isPaused() && !torrent->superSeeding())
{
torrent->setSuperSeeding(true);
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Super seeding enabled."), torrentName));
LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Super seeding enabled."), torrentName));
}
continue;
@@ -1752,23 +1752,23 @@ void Session::processShareLimits()
if (m_maxRatioAction == Remove)
{
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Removed torrent."), torrentName));
LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Removed torrent."), torrentName));
deleteTorrent(torrent->id());
}
else if (m_maxRatioAction == DeleteFiles)
{
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Removed torrent and deleted its content."), torrentName));
LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Removed torrent and deleted its content."), torrentName));
deleteTorrent(torrent->id(), DeleteTorrentAndFiles);
}
else if ((m_maxRatioAction == Pause) && !torrent->isPaused())
{
torrent->pause();
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Torrent paused."), torrentName));
LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Torrent paused."), torrentName));
}
else if ((m_maxRatioAction == EnableSuperSeeding) && !torrent->isPaused() && !torrent->superSeeding())
{
torrent->setSuperSeeding(true);
LogMsg(QString::fromLatin1("%1 %2 %3").arg(description, tr("Super seeding enabled."), torrentName));
LogMsg(u"%1 %2 %3"_qs.arg(description, tr("Super seeding enabled."), torrentName));
}
}
}
@@ -2448,13 +2448,13 @@ void Session::exportTorrentFile(const TorrentInfo &torrentInfo, const Path &fold
return;
const QString validName = Utils::Fs::toValidFileName(baseName);
QString torrentExportFilename = QString::fromLatin1("%1.torrent").arg(validName);
QString torrentExportFilename = u"%1.torrent"_qs.arg(validName);
Path newTorrentPath = folderPath / Path(torrentExportFilename);
int counter = 0;
while (newTorrentPath.exists())
{
// Append number to torrent name to make it unique
torrentExportFilename = QString::fromLatin1("%1 %2.torrent").arg(validName).arg(++counter);
torrentExportFilename = u"%1 %2.torrent"_qs.arg(validName).arg(++counter);
newTorrentPath = folderPath / Path(torrentExportFilename);
}
@@ -2626,8 +2626,8 @@ QStringList Session::getListeningIPs() const
const QString ifaceName = networkInterface();
const QString ifaceAddr = networkInterfaceAddress();
const QHostAddress configuredAddr(ifaceAddr);
const bool allIPv4 = (ifaceAddr == QLatin1String("0.0.0.0")); // Means All IPv4 addresses
const bool allIPv6 = (ifaceAddr == QLatin1String("::")); // Means All IPv6 addresses
const bool allIPv4 = (ifaceAddr == u"0.0.0.0"); // Means All IPv4 addresses
const bool allIPv6 = (ifaceAddr == u"::"); // Means All IPv6 addresses
if (!ifaceAddr.isEmpty() && !allIPv4 && !allIPv6 && configuredAddr.isNull())
{
@@ -2643,13 +2643,13 @@ QStringList Session::getListeningIPs() const
if (ifaceName.isEmpty())
{
if (ifaceAddr.isEmpty())
return {QLatin1String("0.0.0.0"), QLatin1String("::")}; // Indicates all interfaces + all addresses (aka default)
return {u"0.0.0.0"_qs, u"::"_qs}; // Indicates all interfaces + all addresses (aka default)
if (allIPv4)
return {QLatin1String("0.0.0.0")};
return {u"0.0.0.0"_qs};
if (allIPv6)
return {QLatin1String("::")};
return {u"::"_qs};
}
const auto checkAndAddIP = [allIPv4, allIPv6, &IPs](const QHostAddress &addr, const QHostAddress &match)
@@ -4160,7 +4160,7 @@ void Session::handleTorrentFinished(TorrentImpl *const torrent)
// Check if there are torrent files inside
for (const Path &torrentRelpath : asConst(torrent->filePaths()))
{
if (torrentRelpath.hasExtension(QLatin1String(".torrent")))
if (torrentRelpath.hasExtension(u".torrent"_qs))
{
qDebug("Found possible recursive torrent download.");
const Path torrentFullpath = torrent->actualStorageLocation() / torrentRelpath;
@@ -4458,7 +4458,7 @@ void Session::recursiveTorrentDownload(const TorrentID &id)
for (const Path &torrentRelpath : asConst(torrent->filePaths()))
{
if (torrentRelpath.hasExtension(QLatin1String(".torrent")))
if (torrentRelpath.hasExtension(u".torrent"_qs))
{
LogMsg(tr("Recursive download .torrent file within torrent. Source torrent: \"%1\". File: \"%2\"")
.arg(torrent->name(), torrentRelpath.toString()));

View File

@@ -93,7 +93,7 @@ void Statistics::save() const
if (!m_dirty || ((now - m_lastWrite) < SAVE_INTERVAL))
return;
SettingsPtr s = Profile::instance()->applicationSettings(QLatin1String("qBittorrent-data"));
SettingsPtr s = Profile::instance()->applicationSettings(u"qBittorrent-data"_qs);
QVariantHash v;
v.insert(u"AlltimeDL"_qs, m_alltimeDL + m_sessionDL);
v.insert(u"AlltimeUL"_qs, m_alltimeUL + m_sessionUL);
@@ -104,7 +104,7 @@ void Statistics::save() const
void Statistics::load()
{
const SettingsPtr s = Profile::instance()->applicationSettings(QLatin1String("qBittorrent-data"));
const SettingsPtr s = Profile::instance()->applicationSettings(u"qBittorrent-data"_qs);
const QVariantHash v = s->value(u"Stats/AllStats"_qs).toHash();
m_alltimeDL = v[u"AlltimeDL"_qs].toULongLong();

View File

@@ -317,7 +317,7 @@ TorrentImpl::TorrentImpl(Session *session, lt::session *nativeSession
const Path filepath = filePath(i);
// Move "unwanted" files back to their original folder
const Path parentRelPath = filepath.parentPath();
if (parentRelPath.filename() == QLatin1String(".unwanted"))
if (parentRelPath.filename() == u".unwanted")
{
const QString oldName = filepath.filename();
const Path newRelPath = parentRelPath.parentPath();
@@ -1050,10 +1050,8 @@ QString TorrentImpl::error() const
if (m_nativeStatus.flags & lt::torrent_flags::upload_mode)
{
const QString writeErrorStr = tr("Couldn't write to file.");
const QString uploadModeStr = tr("Torrent is now in \"upload only\" mode.");
const QString errorMessage = tr("Reason:") + QLatin1Char(' ') + QString::fromLocal8Bit(m_lastFileError.error.message().c_str());
return QString::fromLatin1("%1 %2 %3").arg(writeErrorStr, errorMessage, uploadModeStr);
return tr("Couldn't write to file. Reason: \"%1\". Torrent is now in \"upload only\" mode.")
.arg(QString::fromLocal8Bit(m_lastFileError.error.message().c_str()));
}
return {};

View File

@@ -176,11 +176,11 @@ bool Connection::acceptsGzipEncoding(QString codings)
if (list.isEmpty())
return false;
const bool canGzip = isCodingAvailable(list, QString::fromLatin1("gzip"));
const bool canGzip = isCodingAvailable(list, u"gzip"_qs);
if (canGzip)
return true;
const bool canAny = isCodingAvailable(list, QString::fromLatin1("*"));
const bool canAny = isCodingAvailable(list, u"*"_qs);
if (canAny)
return true;

View File

@@ -28,6 +28,8 @@
#include "httperror.h"
#include "base/global.h"
HTTPError::HTTPError(const int statusCode, const QString &statusText, const QString &message)
: RuntimeError {message}
, m_statusCode {statusCode}
@@ -46,41 +48,41 @@ QString HTTPError::statusText() const
}
BadRequestHTTPError::BadRequestHTTPError(const QString &message)
: HTTPError(400, QLatin1String("Bad Request"), message)
: HTTPError(400, u"Bad Request"_qs, message)
{
}
UnauthorizedHTTPError::UnauthorizedHTTPError(const QString &message)
: HTTPError(401, QLatin1String("Unauthorized"), message)
: HTTPError(401, u"Unauthorized"_qs, message)
{
}
ForbiddenHTTPError::ForbiddenHTTPError(const QString &message)
: HTTPError(403, QLatin1String("Forbidden"), message)
: HTTPError(403, u"Forbidden"_qs, message)
{
}
NotFoundHTTPError::NotFoundHTTPError(const QString &message)
: HTTPError(404, QLatin1String("Not Found"), message)
: HTTPError(404, u"Not Found"_qs, message)
{
}
MethodNotAllowedHTTPError::MethodNotAllowedHTTPError(const QString &message)
: HTTPError(405, QLatin1String("Method Not Allowed"), message)
: HTTPError(405, u"Method Not Allowed"_qs, message)
{
}
ConflictHTTPError::ConflictHTTPError(const QString &message)
: HTTPError(409, QLatin1String("Conflict"), message)
: HTTPError(409, u"Conflict"_qs, message)
{
}
UnsupportedMediaTypeHTTPError::UnsupportedMediaTypeHTTPError(const QString &message)
: HTTPError(415, QLatin1String("Unsupported Media Type"), message)
: HTTPError(415, u"Unsupported Media Type"_qs, message)
{
}
InternalServerErrorHTTPError::InternalServerErrorHTTPError(const QString &message)
: HTTPError(500, QLatin1String("Internal Server Error"), message)
: HTTPError(500, u"Internal Server Error"_qs, message)
{
}

View File

@@ -193,7 +193,7 @@ bool RequestParser::parseRequestLine(const QString &line)
{
// [rfc7230] 3.1.1. Request Line
const QRegularExpression re(QLatin1String("^([A-Z]+)\\s+(\\S+)\\s+HTTP\\/(\\d\\.\\d)$"));
const QRegularExpression re(u"^([A-Z]+)\\s+(\\S+)\\s+HTTP\\/(\\d\\.\\d)$"_qs);
const QRegularExpressionMatch match = re.match(line);
if (!match.hasMatch())
@@ -268,7 +268,7 @@ bool RequestParser::parsePostMessage(const QByteArray &data)
// [rfc2046] 5.1.1. Common Syntax
// find boundary delimiter
const QLatin1String boundaryFieldName("boundary=");
const QString boundaryFieldName = u"boundary="_qs;
const int idx = contentType.indexOf(boundaryFieldName);
if (idx < 0)
{
@@ -347,8 +347,8 @@ bool RequestParser::parseFormData(const QByteArray &data)
}
// pick data
const QLatin1String filename("filename");
const QLatin1String name("name");
const QString filename = u"filename"_qs;
const QString name = u"name"_qs;
if (headersMap.contains(filename))
{

View File

@@ -28,6 +28,9 @@
#pragma once
#include <QString>
#include "base/global.h"
#include "types.h"
namespace Http
@@ -35,7 +38,7 @@ namespace Http
class ResponseBuilder
{
public:
void status(uint code = 200, const QString &text = QLatin1String("OK"));
void status(uint code = 200, const QString &text = u"OK"_qs);
void setHeader(const Header &header);
void print(const QString &text, const QString &type = CONTENT_TYPE_HTML);
void print(const QByteArray &data, const QString &type = CONTENT_TYPE_HTML);

View File

@@ -74,13 +74,13 @@ QString Http::httpDate()
// [RFC 7231] 7.1.1.1. Date/Time Formats
// example: "Sun, 06 Nov 1994 08:49:37 GMT"
return QLocale::c().toString(QDateTime::currentDateTimeUtc(), QLatin1String("ddd, dd MMM yyyy HH:mm:ss"))
.append(QLatin1String(" GMT"));
return QLocale::c().toString(QDateTime::currentDateTimeUtc(), u"ddd, dd MMM yyyy HH:mm:ss"_qs)
.append(u" GMT");
}
void Http::compressContent(Response &response)
{
if (response.headers.value(HEADER_CONTENT_ENCODING) != QLatin1String("gzip"))
if (response.headers.value(HEADER_CONTENT_ENCODING) != u"gzip")
return;
response.headers.remove(HEADER_CONTENT_ENCODING);
@@ -106,5 +106,5 @@ void Http::compressContent(Response &response)
return;
response.content = compressedData;
response.headers[HEADER_CONTENT_ENCODING] = QLatin1String("gzip");
response.headers[HEADER_CONTENT_ENCODING] = u"gzip"_qs;
}

View File

@@ -123,7 +123,7 @@ namespace Http
HeaderMap headers;
QByteArray content;
Response(uint code = 200, const QString &text = QLatin1String("OK"))
Response(uint code = 200, const QString &text = u"OK"_qs)
: status {code, text}
{
}

View File

@@ -226,7 +226,7 @@ bool Net::DownloadManager::hasSupportedScheme(const QString &url)
const QStringList schemes = instance()->m_networkManager.supportedSchemes();
return std::any_of(schemes.cbegin(), schemes.cend(), [&url](const QString &scheme)
{
return url.startsWith((scheme + QLatin1Char(':')), Qt::CaseInsensitive);
return url.startsWith((scheme + u':'), Qt::CaseInsensitive);
});
}

View File

@@ -43,7 +43,7 @@
#include "downloadmanager.h"
#include "geoipdatabase.h"
const QString DATABASE_URL = QStringLiteral("https://download.db-ip.com/free/dbip-country-lite-%1.mmdb.gz");
const QString DATABASE_URL = u"https://download.db-ip.com/free/dbip-country-lite-%1.mmdb.gz"_qs;
const QString GEODB_FOLDER = u"GeoDB"_qs;
const QString GEODB_FILENAME = u"dbip-country-lite.mmdb"_qs;

View File

@@ -60,7 +60,7 @@ ProxyConfigurationManager::ProxyConfigurationManager(QObject *parent)
m_config.type = m_storeProxyType.get(ProxyType::None);
if ((m_config.type < ProxyType::None) || (m_config.type > ProxyType::SOCKS4))
m_config.type = ProxyType::None;
m_config.ip = m_storeProxyIP.get(QLatin1String("0.0.0.0"));
m_config.ip = m_storeProxyIP.get(u"0.0.0.0"_qs);
m_config.port = m_storeProxyPort.get(8080);
m_config.username = m_storeProxyUsername;
m_config.password = m_storeProxyPassword;
@@ -130,17 +130,17 @@ void ProxyConfigurationManager::configureProxy()
switch (m_config.type)
{
case ProxyType::HTTP_PW:
proxyStrHTTP = QString::fromLatin1("http://%1:%2@%3:%4").arg(m_config.username
proxyStrHTTP = u"http://%1:%2@%3:%4"_qs.arg(m_config.username
, m_config.password, m_config.ip, QString::number(m_config.port));
break;
case ProxyType::HTTP:
proxyStrHTTP = QString::fromLatin1("http://%1:%2").arg(m_config.ip, QString::number(m_config.port));
proxyStrHTTP = u"http://%1:%2"_qs.arg(m_config.ip, QString::number(m_config.port));
break;
case ProxyType::SOCKS5:
proxyStrSOCK = QString::fromLatin1("%1:%2").arg(m_config.ip, QString::number(m_config.port));
proxyStrSOCK = u"%1:%2"_qs.arg(m_config.ip, QString::number(m_config.port));
break;
case ProxyType::SOCKS5_PW:
proxyStrSOCK = QString::fromLatin1("%1:%2@%3:%4").arg(m_config.username
proxyStrSOCK = u"%1:%2@%3:%4"_qs.arg(m_config.username
, m_config.password, m_config.ip, QString::number(m_config.port));
break;
default:

View File

@@ -38,6 +38,8 @@
#include <QMimeDatabase>
#include <QRegularExpression>
#include "base/global.h"
#if defined(Q_OS_WIN)
const Qt::CaseSensitivity CASE_SENSITIVITY = Qt::CaseInsensitive;
#else
@@ -74,11 +76,11 @@ bool Path::isValid() const
return false;
#if defined(Q_OS_WIN)
const QRegularExpression regex {QLatin1String("[:?\"*<>|]")};
const QRegularExpression regex {u"[:?\"*<>|]"_qs};
#elif defined(Q_OS_MACOS)
const QRegularExpression regex {QLatin1String("[\\0:]")};
const QRegularExpression regex {u"[\\0:]"_qs};
#else
const QRegularExpression regex {QLatin1String("[\\0]")};
const QRegularExpression regex {u"[\\0]"_qs};
#endif
return !m_pathStr.contains(regex);
}
@@ -105,24 +107,24 @@ bool Path::exists() const
Path Path::rootItem() const
{
const int slashIndex = m_pathStr.indexOf(QLatin1Char('/'));
const int slashIndex = m_pathStr.indexOf(u'/');
if (slashIndex < 0)
return *this;
if (slashIndex == 0) // *nix absolute path
return createUnchecked(QLatin1String("/"));
return createUnchecked(u"/"_qs);
return createUnchecked(m_pathStr.left(slashIndex));
}
Path Path::parentPath() const
{
const int slashIndex = m_pathStr.lastIndexOf(QLatin1Char('/'));
const int slashIndex = m_pathStr.lastIndexOf(u'/');
if (slashIndex == -1)
return {};
if (slashIndex == 0) // *nix absolute path
return (m_pathStr.size() == 1) ? Path() : createUnchecked(QLatin1String("/"));
return (m_pathStr.size() == 1) ? Path() : createUnchecked(u"/"_qs);
return createUnchecked(m_pathStr.left(slashIndex));
}
@@ -140,17 +142,17 @@ QString Path::extension() const
{
const QString suffix = QMimeDatabase().suffixForFileName(m_pathStr);
if (!suffix.isEmpty())
return (QLatin1String(".") + suffix);
return (u"." + suffix);
const int slashIndex = m_pathStr.lastIndexOf(QLatin1Char('/'));
const int slashIndex = m_pathStr.lastIndexOf(u'/');
const auto filename = QStringView(m_pathStr).mid(slashIndex + 1);
const int dotIndex = filename.lastIndexOf(QLatin1Char('.'), -2);
const int dotIndex = filename.lastIndexOf(u'.', -2);
return ((dotIndex == -1) ? QString() : filename.mid(dotIndex).toString());
}
bool Path::hasExtension(const QString &ext) const
{
Q_ASSERT(ext.startsWith(QLatin1Char('.')) && (ext.size() >= 2));
Q_ASSERT(ext.startsWith(u'.') && (ext.size() >= 2));
return m_pathStr.endsWith(ext, Qt::CaseInsensitive);
}
@@ -160,7 +162,7 @@ bool Path::hasAncestor(const Path &other) const
if (other.isEmpty() || (m_pathStr.size() <= other.m_pathStr.size()))
return false;
return (m_pathStr[other.m_pathStr.size()] == QLatin1Char('/'))
return (m_pathStr[other.m_pathStr.size()] == u'/')
&& m_pathStr.startsWith(other.m_pathStr, CASE_SENSITIVITY);
}
@@ -300,7 +302,7 @@ Path operator/(const Path &lhs, const Path &rhs)
if (lhs.isEmpty())
return rhs;
return Path(lhs.m_pathStr + QLatin1Char('/') + rhs.m_pathStr);
return Path(lhs.m_pathStr + u'/' + rhs.m_pathStr);
}
Path operator+(const Path &lhs, const QString &rhs)

View File

@@ -46,7 +46,7 @@ QString Private::Profile::configurationName() const
QString Private::Profile::configurationSuffix() const
{
return (m_configurationName.isEmpty() ? QString() : QLatin1Char('_') + m_configurationName);
return (m_configurationName.isEmpty() ? QString() : (u'_' + m_configurationName));
}
QString Private::Profile::profileName() const
@@ -172,11 +172,11 @@ SettingsPtr Private::CustomProfile::applicationSettings(const QString &name) con
{
// here we force QSettings::IniFormat format always because we need it to be portable across platforms
#if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
const char CONF_FILE_EXTENSION[] = ".ini";
const auto CONF_FILE_EXTENSION = u".ini"_qs;
#else
const char CONF_FILE_EXTENSION[] = ".conf";
const auto CONF_FILE_EXTENSION = u".conf"_qs;
#endif
const Path settingsFilePath = configLocation() / Path(name + QLatin1String(CONF_FILE_EXTENSION));
const Path settingsFilePath = configLocation() / Path(name + CONF_FILE_EXTENSION);
return SettingsPtr(new QSettings(settingsFilePath.data(), QSettings::IniFormat));
}

View File

@@ -33,6 +33,7 @@
#include <QJsonObject>
#include <QVariant>
#include "base/global.h"
#include "rss_feed.h"
using namespace RSS;
@@ -50,14 +51,14 @@ namespace
}
}
const QString Article::KeyId(QStringLiteral("id"));
const QString Article::KeyDate(QStringLiteral("date"));
const QString Article::KeyTitle(QStringLiteral("title"));
const QString Article::KeyAuthor(QStringLiteral("author"));
const QString Article::KeyDescription(QStringLiteral("description"));
const QString Article::KeyTorrentURL(QStringLiteral("torrentURL"));
const QString Article::KeyLink(QStringLiteral("link"));
const QString Article::KeyIsRead(QStringLiteral("isRead"));
const QString Article::KeyId = u"id"_qs;
const QString Article::KeyDate = u"date"_qs;
const QString Article::KeyTitle = u"title"_qs;
const QString Article::KeyAuthor = u"author"_qs;
const QString Article::KeyDescription = u"description"_qs;
const QString Article::KeyTorrentURL = u"torrentURL"_qs;
const QString Article::KeyLink = u"link"_qs;
const QString Article::KeyIsRead = u"isRead"_qs;
Article::Article(Feed *feed, const QVariantHash &varHash)
: QObject(feed)

View File

@@ -58,8 +58,8 @@ struct ProcessingJob
QVariantHash articleData;
};
const QString CONF_FOLDER_NAME {QStringLiteral("rss")};
const QString RULES_FILE_NAME {QStringLiteral("download_rules.json")};
const QString CONF_FOLDER_NAME = u"rss"_qs;
const QString RULES_FILE_NAME = u"download_rules.json"_qs;
namespace
{
@@ -441,8 +441,8 @@ void AutoDownloader::loadRules(const QByteArray &data)
void AutoDownloader::loadRulesLegacy()
{
const SettingsPtr settings = Profile::instance()->applicationSettings(QStringLiteral("qBittorrent-rss"));
const QVariantHash rules = settings->value(QStringLiteral("download_rules")).toHash();
const SettingsPtr settings = Profile::instance()->applicationSettings(u"qBittorrent-rss"_qs);
const QVariantHash rules = settings->value(u"download_rules"_qs).toHash();
for (const QVariant &ruleVar : rules)
{
const auto rule = AutoDownloadRule::fromLegacyDict(ruleVar.toHash());

View File

@@ -101,22 +101,22 @@ namespace
}
}
const QString Str_Name(QStringLiteral("name"));
const QString Str_Enabled(QStringLiteral("enabled"));
const QString Str_UseRegex(QStringLiteral("useRegex"));
const QString Str_MustContain(QStringLiteral("mustContain"));
const QString Str_MustNotContain(QStringLiteral("mustNotContain"));
const QString Str_EpisodeFilter(QStringLiteral("episodeFilter"));
const QString Str_AffectedFeeds(QStringLiteral("affectedFeeds"));
const QString Str_SavePath(QStringLiteral("savePath"));
const QString Str_AssignedCategory(QStringLiteral("assignedCategory"));
const QString Str_LastMatch(QStringLiteral("lastMatch"));
const QString Str_IgnoreDays(QStringLiteral("ignoreDays"));
const QString Str_AddPaused(QStringLiteral("addPaused"));
const QString Str_CreateSubfolder(QStringLiteral("createSubfolder"));
const QString Str_ContentLayout(QStringLiteral("torrentContentLayout"));
const QString Str_SmartFilter(QStringLiteral("smartFilter"));
const QString Str_PreviouslyMatched(QStringLiteral("previouslyMatchedEpisodes"));
const QString Str_Name = u"name"_qs;
const QString Str_Enabled = u"enabled"_qs;
const QString Str_UseRegex = u"useRegex"_qs;
const QString Str_MustContain = u"mustContain"_qs;
const QString Str_MustNotContain = u"mustNotContain"_qs;
const QString Str_EpisodeFilter = u"episodeFilter"_qs;
const QString Str_AffectedFeeds = u"affectedFeeds"_qs;
const QString Str_SavePath = u"savePath"_qs;
const QString Str_AssignedCategory = u"assignedCategory"_qs;
const QString Str_LastMatch = u"lastMatch"_qs;
const QString Str_IgnoreDays = u"ignoreDays"_qs;
const QString Str_AddPaused = u"addPaused"_qs;
const QString Str_CreateSubfolder = u"createSubfolder"_qs;
const QString Str_ContentLayout = u"torrentContentLayout"_qs;
const QString Str_SmartFilter = u"smartFilter"_qs;
const QString Str_PreviouslyMatched = u"previouslyMatchedEpisodes"_qs;
namespace RSS
{
@@ -346,7 +346,7 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl
}
else
{ // Single number
const QString expStr {QString::fromLatin1("\\b(?:s0?%1[ -_\\.]?e0?%2|%1x0?%2)(?:\\D|\\b)").arg(season, episode)};
const QString expStr {u"\\b(?:s0?%1[ -_\\.]?e0?%2|%1x0?%2)(?:\\D|\\b)"_qs.arg(season, episode)};
if (cachedRegex(expStr).match(articleTitle).hasMatch())
return true;
}
@@ -391,8 +391,8 @@ bool AutoDownloadRule::matchesSmartEpisodeFilter(const QString &articleTitle) co
// so we don't download those
if (isRepack && isProper)
{
m_dataPtr->lastComputedEpisodes.append(episodeStr + QLatin1String("-REPACK"));
m_dataPtr->lastComputedEpisodes.append(episodeStr + QLatin1String("-PROPER"));
m_dataPtr->lastComputedEpisodes.append(episodeStr + u"-REPACK");
m_dataPtr->lastComputedEpisodes.append(episodeStr + u"-PROPER");
}
}

View File

@@ -51,13 +51,13 @@
#include "rss_parser.h"
#include "rss_session.h"
const QString KEY_UID(QStringLiteral("uid"));
const QString KEY_URL(QStringLiteral("url"));
const QString KEY_TITLE(QStringLiteral("title"));
const QString KEY_LASTBUILDDATE(QStringLiteral("lastBuildDate"));
const QString KEY_ISLOADING(QStringLiteral("isLoading"));
const QString KEY_HASERROR(QStringLiteral("hasError"));
const QString KEY_ARTICLES(QStringLiteral("articles"));
const QString KEY_UID = u"uid"_qs;
const QString KEY_URL = u"url"_qs;
const QString KEY_TITLE = u"title"_qs;
const QString KEY_LASTBUILDDATE = u"lastBuildDate"_qs;
const QString KEY_ISLOADING = u"isLoading"_qs;
const QString KEY_HASERROR = u"hasError"_qs;
const QString KEY_ARTICLES = u"articles"_qs;
using namespace RSS;
@@ -68,16 +68,16 @@ Feed::Feed(const QUuid &uid, const QString &url, const QString &path, Session *s
, m_url(url)
{
const auto uidHex = QString::fromLatin1(m_uid.toRfc4122().toHex());
m_dataFileName = Path(uidHex + QLatin1String(".json"));
m_dataFileName = Path(uidHex + u".json");
// Move to new file naming scheme (since v4.1.2)
const QString legacyFilename = Utils::Fs::toValidFileName(m_url, QLatin1String("_")) + QLatin1String(".json");
const QString legacyFilename = Utils::Fs::toValidFileName(m_url, u"_"_qs) + u".json";
const Path storageDir = m_session->dataFileStorage()->storageDir();
const Path dataFilePath = storageDir / m_dataFileName;
if (!dataFilePath.exists())
Utils::Fs::renameFile((storageDir / Path(legacyFilename)), dataFilePath);
m_iconPath = storageDir / Path(uidHex + QLatin1String(".ico"));
m_iconPath = storageDir / Path(uidHex + u".ico");
m_parser = new Private::Parser(m_lastBuildDate);
m_parser->moveToThread(m_session->workingThread());
@@ -323,16 +323,16 @@ void Feed::loadArticles(const QByteArray &data)
void Feed::loadArticlesLegacy()
{
const SettingsPtr qBTRSSFeeds = Profile::instance()->applicationSettings(QStringLiteral("qBittorrent-rss-feeds"));
const SettingsPtr qBTRSSFeeds = Profile::instance()->applicationSettings(u"qBittorrent-rss-feeds"_qs);
const QVariantHash allOldItems = qBTRSSFeeds->value(u"old_items"_qs).toHash();
for (const QVariant &var : asConst(allOldItems.value(m_url).toList()))
{
auto hash = var.toHash();
// update legacy keys
hash[Article::KeyLink] = hash.take(QLatin1String("news_link"));
hash[Article::KeyTorrentURL] = hash.take(QLatin1String("torrent_url"));
hash[Article::KeyIsRead] = hash.take(QLatin1String("read"));
hash[Article::KeyLink] = hash.take(u"news_link"_qs);
hash[Article::KeyTorrentURL] = hash.take(u"torrent_url"_qs);
hash[Article::KeyIsRead] = hash.take(u"read"_qs);
try
{
auto article = new Article(this, hash);
@@ -425,7 +425,7 @@ void Feed::downloadIcon()
// Download the RSS Feed icon
// XXX: This works for most sites but it is not perfect
const QUrl url(m_url);
const auto iconUrl = QString::fromLatin1("%1://%2/favicon.ico").arg(url.scheme(), url.host());
const auto iconUrl = u"%1://%2/favicon.ico"_qs.arg(url.scheme(), url.host());
Net::DownloadManager::instance()->download(
Net::DownloadRequest(iconUrl).saveToFile(true).destFileName(m_iconPath)
, this, &Feed::handleIconDownloadFinished);

View File

@@ -399,8 +399,8 @@ namespace
{
// Check that if date has '-' separators, both separators are '-'.
parts = rxMatch.capturedTexts();
const bool h1 = (parts[3] == QLatin1String("-"));
const bool h2 = (parts[5] == QLatin1String("-"));
const bool h1 = (parts[3] == u"-");
const bool h2 = (parts[5] == u"-");
if (h1 != h2)
return QDateTime::currentDateTime();
}
@@ -476,7 +476,7 @@ namespace
if (!ok[0] || !ok[1] || offsetMin > 59)
return {};
offset += offsetMin * 60;
negOffset = (parts[1] == QLatin1String("-"));
negOffset = (parts[1] == u"-");
if (negOffset)
offset = -offset;
}
@@ -564,12 +564,12 @@ void Parser::parse_impl(const QByteArray &feedData)
while (xml.readNextStartElement())
{
if (xml.name() == QLatin1String("rss"))
if (xml.name() == u"rss")
{
// Find channels
while (xml.readNextStartElement())
{
if (xml.name() == QLatin1String("channel"))
if (xml.name() == u"channel")
{
parseRSSChannel(xml);
foundChannel = true;
@@ -581,7 +581,7 @@ void Parser::parse_impl(const QByteArray &feedData)
}
break;
}
if (xml.name() == QLatin1String("feed"))
if (xml.name() == u"feed")
{ // Atom feed
parseAtomChannel(xml);
foundChannel = true;
@@ -618,43 +618,43 @@ void Parser::parseRssArticle(QXmlStreamReader &xml)
xml.readNext();
const QString name(xml.name().toString());
if (xml.isEndElement() && (name == QLatin1String("item")))
if (xml.isEndElement() && (name == u"item"))
break;
if (xml.isStartElement())
{
if (name == QLatin1String("title"))
if (name == u"title")
{
article[Article::KeyTitle] = xml.readElementText().trimmed();
}
else if (name == QLatin1String("enclosure"))
else if (name == u"enclosure")
{
if (xml.attributes().value(u"type"_qs) == QLatin1String("application/x-bittorrent"))
article[Article::KeyTorrentURL] = xml.attributes().value(QLatin1String("url")).toString();
if (xml.attributes().value(u"type"_qs) == u"application/x-bittorrent")
article[Article::KeyTorrentURL] = xml.attributes().value(u"url"_qs).toString();
else if (xml.attributes().value(u"type"_qs).isEmpty())
altTorrentUrl = xml.attributes().value(QLatin1String("url")).toString();
altTorrentUrl = xml.attributes().value(u"url"_qs).toString();
}
else if (name == QLatin1String("link"))
else if (name == u"link")
{
const QString text {xml.readElementText().trimmed()};
if (text.startsWith(QLatin1String("magnet:"), Qt::CaseInsensitive))
if (text.startsWith(u"magnet:", Qt::CaseInsensitive))
article[Article::KeyTorrentURL] = text; // magnet link instead of a news URL
else
article[Article::KeyLink] = text;
}
else if (name == QLatin1String("description"))
else if (name == u"description")
{
article[Article::KeyDescription] = xml.readElementText(QXmlStreamReader::IncludeChildElements);
}
else if (name == QLatin1String("pubDate"))
else if (name == u"pubDate")
{
article[Article::KeyDate] = parseDate(xml.readElementText().trimmed());
}
else if (name == QLatin1String("author"))
else if (name == u"author")
{
article[Article::KeyAuthor] = xml.readElementText().trimmed();
}
else if (name == QLatin1String("guid"))
else if (name == u"guid")
{
article[Article::KeyId] = xml.readElementText().trimmed();
}
@@ -679,11 +679,11 @@ void Parser::parseRSSChannel(QXmlStreamReader &xml)
if (xml.isStartElement())
{
if (xml.name() == QLatin1String("title"))
if (xml.name() == u"title")
{
m_result.title = xml.readElementText();
}
else if (xml.name() == QLatin1String("lastBuildDate"))
else if (xml.name() == u"lastBuildDate")
{
const QString lastBuildDate = xml.readElementText();
if (!lastBuildDate.isEmpty())
@@ -696,7 +696,7 @@ void Parser::parseRSSChannel(QXmlStreamReader &xml)
m_result.lastBuildDate = lastBuildDate;
}
}
else if (xml.name() == QLatin1String("item"))
else if (xml.name() == u"item")
{
parseRssArticle(xml);
}
@@ -714,22 +714,22 @@ void Parser::parseAtomArticle(QXmlStreamReader &xml)
xml.readNext();
const QString name(xml.name().toString());
if (xml.isEndElement() && (name == QLatin1String("entry")))
if (xml.isEndElement() && (name == u"entry"))
break;
if (xml.isStartElement())
{
if (name == QLatin1String("title"))
if (name == u"title")
{
article[Article::KeyTitle] = xml.readElementText().trimmed();
}
else if (name == QLatin1String("link"))
else if (name == u"link")
{
const QString link = (xml.attributes().isEmpty()
? xml.readElementText().trimmed()
: xml.attributes().value(QLatin1String("href")).toString());
: xml.attributes().value(u"href"_qs).toString());
if (link.startsWith(QLatin1String("magnet:"), Qt::CaseInsensitive))
if (link.startsWith(u"magnet:", Qt::CaseInsensitive))
article[Article::KeyTorrentURL] = link; // magnet link instead of a news URL
else
// Atom feeds can have relative links, work around this and
@@ -738,7 +738,7 @@ void Parser::parseAtomArticle(QXmlStreamReader &xml)
article[Article::KeyLink] = (m_baseUrl.isEmpty() ? link : m_baseUrl + link);
}
else if ((name == QLatin1String("summary")) || (name == QLatin1String("content")))
else if ((name == u"summary") || (name == u"content"))
{
if (doubleContent)
{ // Duplicate content -> ignore
@@ -755,23 +755,23 @@ void Parser::parseAtomArticle(QXmlStreamReader &xml)
doubleContent = true;
}
}
else if (name == QLatin1String("updated"))
else if (name == u"updated")
{
// ATOM uses standard compliant date, don't do fancy stuff
const QDateTime articleDate = QDateTime::fromString(xml.readElementText().trimmed(), Qt::ISODate);
article[Article::KeyDate] = (articleDate.isValid() ? articleDate : QDateTime::currentDateTime());
}
else if (name == QLatin1String("author"))
else if (name == u"author")
{
while (xml.readNextStartElement())
{
if (xml.name() == QLatin1String("name"))
if (xml.name() == u"name")
article[Article::KeyAuthor] = xml.readElementText().trimmed();
else
xml.skipCurrentElement();
}
}
else if (name == QLatin1String("id"))
else if (name == u"id")
{
article[Article::KeyId] = xml.readElementText().trimmed();
}
@@ -795,11 +795,11 @@ void Parser::parseAtomChannel(QXmlStreamReader &xml)
if (xml.isStartElement())
{
if (xml.name() == QLatin1String("title"))
if (xml.name() == u"title")
{
m_result.title = xml.readElementText();
}
else if (xml.name() == QLatin1String("updated"))
else if (xml.name() == u"updated")
{
const QString lastBuildDate = xml.readElementText();
if (!lastBuildDate.isEmpty())
@@ -812,7 +812,7 @@ void Parser::parseAtomChannel(QXmlStreamReader &xml)
m_result.lastBuildDate = lastBuildDate;
}
}
else if (xml.name() == QLatin1String("entry"))
else if (xml.name() == u"entry")
{
parseAtomArticle(xml);
}

View File

@@ -49,9 +49,9 @@
#include "rss_item.h"
const int MsecsPerMin = 60000;
const QString CONF_FOLDER_NAME(QStringLiteral("rss"));
const QString DATA_FOLDER_NAME(QStringLiteral("rss/articles"));
const QString FEEDS_FILE_NAME(QStringLiteral("feeds.json"));
const QString CONF_FOLDER_NAME = u"rss"_qs;
const QString DATA_FOLDER_NAME = u"rss/articles"_qs;
const QString FEEDS_FILE_NAME = u"feeds.json"_qs;
using namespace RSS;
@@ -326,7 +326,7 @@ void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder)
else
{
LogMsg(tr("Couldn't load RSS item. Item: \"%1\". Invalid data format.")
.arg(QString::fromLatin1("%1\\%2").arg(folder->path(), key)), Log::WARNING);
.arg(u"%1\\%2"_qs.arg(folder->path(), key)), Log::WARNING);
}
}
@@ -347,7 +347,7 @@ void Session::loadLegacy()
uint i = 0;
for (QString legacyPath : legacyFeedPaths)
{
if (Item::PathSeparator == QString(legacyPath[0]))
if (Item::PathSeparator == legacyPath[0])
legacyPath.remove(0, 1);
const QString parentFolderPath = Item::parentPath(legacyPath);
const QString feedUrl = Item::relativeName(legacyPath);

View File

@@ -64,7 +64,7 @@ namespace
for (const Path &dir : asConst(dirs))
{
// python 3: remove "__pycache__" folders
if (dir.filename() == QLatin1String("__pycache__"))
if (dir.filename() == u"__pycache__")
{
Utils::Fs::removeDirRecursively(dir);
continue;
@@ -75,7 +75,7 @@ namespace
for (const QString &file : files)
{
const Path path {file};
if (path.hasExtension(QLatin1String(".pyc")))
if (path.hasExtension(u".pyc"_qs))
Utils::Fs::removeFile(path);
}
}
@@ -85,7 +85,7 @@ namespace
QPointer<SearchPluginManager> SearchPluginManager::m_instance = nullptr;
SearchPluginManager::SearchPluginManager()
: m_updateUrl(QLatin1String("http://searchplugins.qbittorrent.org/nova3/engines/"))
: m_updateUrl(u"http://searchplugins.qbittorrent.org/nova3/engines/"_qs)
{
Q_ASSERT(!m_instance); // only one instance is allowed
m_instance = this;
@@ -195,7 +195,7 @@ void SearchPluginManager::enablePlugin(const QString &name, const bool enabled)
// Updates shipped plugin
void SearchPluginManager::updatePlugin(const QString &name)
{
installPlugin(QString::fromLatin1("%1%2.py").arg(m_updateUrl, name));
installPlugin(u"%1%2.py"_qs.arg(m_updateUrl, name));
}
// Install or update plugin from file or url
@@ -289,7 +289,7 @@ bool SearchPluginManager::uninstallPlugin(const QString &name)
// remove it from hard drive
const Path pluginsPath = pluginsLocation();
const QStringList filters {name + QLatin1String(".*")};
const QStringList filters {name + u".*"};
const QStringList files = QDir(pluginsPath.data()).entryList(filters, QDir::Files, QDir::Unsorted);
for (const QString &file : files)
Utils::Fs::removeFile(pluginsPath / Path(file));
@@ -305,14 +305,14 @@ void SearchPluginManager::updateIconPath(PluginInfo *const plugin)
if (!plugin) return;
const Path pluginsPath = pluginsLocation();
Path iconPath = pluginsPath / Path(plugin->name + QLatin1String(".png"));
Path iconPath = pluginsPath / Path(plugin->name + u".png");
if (iconPath.exists())
{
plugin->iconPath = iconPath;
}
else
{
iconPath = pluginsPath / Path(plugin->name + QLatin1String(".ico"));
iconPath = pluginsPath / Path(plugin->name + u".ico");
if (iconPath.exists())
plugin->iconPath = iconPath;
}
@@ -452,7 +452,7 @@ void SearchPluginManager::update()
QProcess nova;
nova.setProcessEnvironment(QProcessEnvironment::systemEnvironment());
const QStringList params {(engineLocation() / Path(u"/nova2.py"_qs)).toString(), QLatin1String("--capabilities")};
const QStringList params {(engineLocation() / Path(u"/nova2.py"_qs)).toString(), u"--capabilities"_qs};
nova.start(Utils::ForeignApps::pythonInfo().executableName, params, QIODevice::ReadOnly);
nova.waitForFinished();
@@ -563,7 +563,7 @@ bool SearchPluginManager::isUpdateNeeded(const QString &pluginName, const Plugin
Path SearchPluginManager::pluginPath(const QString &name)
{
return (pluginsLocation() / Path(name + QLatin1String(".py")));
return (pluginsLocation() / Path(name + u".py"));
}
PluginVersion SearchPluginManager::getPluginVersion(const Path &filePath)

View File

@@ -39,7 +39,7 @@ class SettingValue
{
public:
explicit SettingValue(const char *keyName)
: m_keyName {QLatin1String {keyName}}
: m_keyName {QString::fromLatin1(keyName)}
{
}

View File

@@ -66,25 +66,25 @@ using namespace std::chrono_literals;
const std::chrono::duration WATCH_INTERVAL = 10s;
const int MAX_FAILED_RETRIES = 5;
const QString CONF_FILE_NAME {QStringLiteral("watched_folders.json")};
const QString CONF_FILE_NAME = u"watched_folders.json"_qs;
const QString OPTION_ADDTORRENTPARAMS {QStringLiteral("add_torrent_params")};
const QString OPTION_RECURSIVE {QStringLiteral("recursive")};
const QString OPTION_ADDTORRENTPARAMS = u"add_torrent_params"_qs;
const QString OPTION_RECURSIVE = u"recursive"_qs;
const QString PARAM_CATEGORY {QStringLiteral("category")};
const QString PARAM_TAGS {QStringLiteral("tags")};
const QString PARAM_SAVEPATH {QStringLiteral("save_path")};
const QString PARAM_USEDOWNLOADPATH {QStringLiteral("use_download_path")};
const QString PARAM_DOWNLOADPATH {QStringLiteral("download_path")};
const QString PARAM_OPERATINGMODE {QStringLiteral("operating_mode")};
const QString PARAM_STOPPED {QStringLiteral("stopped")};
const QString PARAM_SKIPCHECKING {QStringLiteral("skip_checking")};
const QString PARAM_CONTENTLAYOUT {QStringLiteral("content_layout")};
const QString PARAM_AUTOTMM {QStringLiteral("use_auto_tmm")};
const QString PARAM_UPLOADLIMIT {QStringLiteral("upload_limit")};
const QString PARAM_DOWNLOADLIMIT {QStringLiteral("download_limit")};
const QString PARAM_SEEDINGTIMELIMIT {QStringLiteral("seeding_time_limit")};
const QString PARAM_RATIOLIMIT {QStringLiteral("ratio_limit")};
const QString PARAM_CATEGORY = u"category"_qs;
const QString PARAM_TAGS = u"tags"_qs;
const QString PARAM_SAVEPATH = u"save_path"_qs;
const QString PARAM_USEDOWNLOADPATH = u"use_download_path"_qs;
const QString PARAM_DOWNLOADPATH = u"download_path"_qs;
const QString PARAM_OPERATINGMODE = u"operating_mode"_qs;
const QString PARAM_STOPPED = u"stopped"_qs;
const QString PARAM_SKIPCHECKING = u"skip_checking"_qs;
const QString PARAM_CONTENTLAYOUT = u"content_layout"_qs;
const QString PARAM_AUTOTMM = u"use_auto_tmm"_qs;
const QString PARAM_UPLOADLIMIT = u"upload_limit"_qs;
const QString PARAM_DOWNLOADLIMIT = u"download_limit"_qs;
const QString PARAM_SEEDINGTIMELIMIT = u"seeding_time_limit"_qs;
const QString PARAM_RATIOLIMIT = u"ratio_limit"_qs;
namespace
{
@@ -509,7 +509,7 @@ void TorrentFilesWatcher::Worker::processFolder(const Path &path, const Path &wa
if (useAutoTMM)
{
addTorrentParams.category = addTorrentParams.category.isEmpty()
? subdirPath.data() : (addTorrentParams.category + QLatin1Char('/') + subdirPath.data());
? subdirPath.data() : (addTorrentParams.category + u'/' + subdirPath.data());
}
else
{
@@ -517,7 +517,7 @@ void TorrentFilesWatcher::Worker::processFolder(const Path &path, const Path &wa
}
}
if (filePath.hasExtension(QLatin1String(".magnet")))
if (filePath.hasExtension(u".magnet"_qs))
{
QFile file {filePath.data()};
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
@@ -587,7 +587,7 @@ void TorrentFilesWatcher::Worker::processFailedTorrents()
if (useAutoTMM)
{
addTorrentParams.category = addTorrentParams.category.isEmpty()
? subdirPath.data() : (addTorrentParams.category + QLatin1Char('/') + subdirPath.data());
? subdirPath.data() : (addTorrentParams.category + u'/' + subdirPath.data());
}
else
{

View File

@@ -80,12 +80,12 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const Path &path)
const QStringList deleteFilesList =
{
// Windows
QLatin1String("Thumbs.db"),
QLatin1String("desktop.ini"),
u"Thumbs.db"_qs,
u"desktop.ini"_qs,
// Linux
QLatin1String(".directory"),
u".directory"_qs,
// Mac OS
QLatin1String(".DS_Store")
u".DS_Store"_qs
};
// travel from the deepest folder and remove anything unwanted on the way out.
@@ -182,7 +182,7 @@ bool Utils::Fs::sameFiles(const Path &path1, const Path &path2)
QString Utils::Fs::toValidFileName(const QString &name, const QString &pad)
{
const QRegularExpression regex {QLatin1String("[\\\\/:?\"*<>|]+")};
const QRegularExpression regex {u"[\\\\/:?\"*<>|]+"_qs};
QString validName = name.trimmed();
validName.replace(regex, pad);
@@ -192,7 +192,7 @@ QString Utils::Fs::toValidFileName(const QString &name, const QString &pad)
Path Utils::Fs::toValidPath(const QString &name, const QString &pad)
{
const QRegularExpression regex {QLatin1String("[:?\"*<>|]+")};
const QRegularExpression regex {u"[:?\"*<>|]+"_qs};
QString validPathStr = name;
validPathStr.replace(regex, pad);
@@ -238,7 +238,7 @@ bool Utils::Fs::isNetworkFileSystem(const Path &path)
return false;
return (::GetDriveTypeW(volumePath.get()) == DRIVE_REMOTE);
#else
const QString file = path.toString() + QLatin1String("/.");
const QString file = (path.toString() + u"/.");
struct statfs buf {};
if (statfs(file.toLocal8Bit().constData(), &buf) != 0)
return false;

View File

@@ -35,6 +35,7 @@
#include <QString>
#include "base/global.h"
#include "base/pathfwd.h"
class QDateTime;
@@ -52,8 +53,8 @@ namespace Utils::Fs
QDateTime lastModified(const Path &path);
bool sameFiles(const Path &path1, const Path &path2);
QString toValidFileName(const QString &name, const QString &pad = QLatin1String(" "));
Path toValidPath(const QString &name, const QString &pad = QLatin1String(" "));
QString toValidFileName(const QString &name, const QString &pad = u" "_qs);
Path toValidPath(const QString &name, const QString &pad = u" "_qs);
Path toCanonicalPath(const Path &path);
bool copyFile(const Path &from, const Path &to);

View File

@@ -298,8 +298,8 @@ bool Utils::Misc::isPreviewable(const Path &filePath)
{
const QString mime = QMimeDatabase().mimeTypeForFile(filePath.data(), QMimeDatabase::MatchExtension).name();
if (mime.startsWith(QLatin1String("audio"), Qt::CaseInsensitive)
|| mime.startsWith(QLatin1String("video"), Qt::CaseInsensitive))
if (mime.startsWith(u"audio", Qt::CaseInsensitive)
|| mime.startsWith(u"video", Qt::CaseInsensitive))
{
return true;
}

View File

@@ -36,6 +36,8 @@
#include <QString>
#include <QVector>
#include "base/global.h"
namespace Utils
{
namespace Net
@@ -65,7 +67,7 @@ namespace Utils
{
return (addr == QHostAddress::LocalHost)
|| (addr == QHostAddress::LocalHostIPv6)
|| (addr == QHostAddress(QLatin1String("::ffff:127.0.0.1")));
|| (addr == QHostAddress(u"::ffff:127.0.0.1"_qs));
}
bool isIPInRange(const QHostAddress &addr, const QVector<Subnet> &subnets)

View File

@@ -34,6 +34,7 @@
#include <QString>
#include "base/exceptions.h"
#include "base/global.h"
namespace Utils
{
@@ -63,7 +64,7 @@ namespace Utils
* @throws RuntimeError if parsing fails
*/
Version(const QString &version)
: Version {version.split(QLatin1Char('.'))}
: Version {version.split(u'.')}
{
}
@@ -119,7 +120,7 @@ namespace Utils
QString res = QString::number((*this)[0]);
for (std::size_t i = 1; i <= lastSignificantIndex; ++i)
res += QLatin1Char('.') + QString::number((*this)[i]);
res += (u'.' + QString::number((*this)[i]));
return res;
}
@@ -162,7 +163,7 @@ namespace Utils
if ((static_cast<std::size_t>(versionParts.size()) > N)
|| (static_cast<std::size_t>(versionParts.size()) < Mandatory))
{
throw RuntimeError(QLatin1String("Incorrect number of version components"));
throw RuntimeError(u"Incorrect number of version components"_qs);
}
bool ok = false;
@@ -171,7 +172,7 @@ namespace Utils
{
res[i] = static_cast<T>(versionParts[static_cast<typename StringsList::size_type>(i)].toInt(&ok));
if (!ok)
throw RuntimeError(QLatin1String("Can not parse version component"));
throw RuntimeError(u"Can not parse version component"_qs);
}
return res;
}