Improve coding style

This commit is contained in:
Vladimir Golovnev (Glassez)
2020-11-16 10:02:11 +03:00
parent acad35c5bc
commit c41df9ffbd
147 changed files with 4454 additions and 2227 deletions

View File

@@ -40,7 +40,8 @@ QVector<QByteArray> Utils::ByteArray::splitToViews(const QByteArray &in, const Q
? (1 + (in.size() / sep.size()))
: (1 + (in.size() / (sep.size() + 1))));
int head = 0;
while (head < in.size()) {
while (head < in.size())
{
int end = in.indexOf(sep, head);
if (end < 0)
end = in.size();

View File

@@ -53,7 +53,8 @@ namespace
{
QProcess proc;
proc.start(exeName, {"--version"}, QIODevice::ReadOnly);
if (proc.waitForFinished() && (proc.exitCode() == QProcess::NormalExit)) {
if (proc.waitForFinished() && (proc.exitCode() == QProcess::NormalExit))
{
QByteArray procOutput = proc.readAllStandardOutput();
if (procOutput.isEmpty())
procOutput = proc.readAllStandardError();
@@ -71,10 +72,12 @@ namespace
const QString versionStr = outputSplit[1];
const int idx = versionStr.indexOf(QRegularExpression("[^\\.\\d]"));
try {
try
{
info = {exeName, versionStr.left(idx)};
}
catch (const std::runtime_error &) {
catch (const std::runtime_error &)
{
return false;
}
@@ -102,12 +105,14 @@ namespace
DWORD cMaxSubKeyLen = 0;
LONG res = ::RegQueryInfoKeyW(handle, NULL, NULL, NULL, &cSubKeys, &cMaxSubKeyLen, NULL, NULL, NULL, NULL, NULL, NULL);
if (res == ERROR_SUCCESS) {
if (res == ERROR_SUCCESS)
{
++cMaxSubKeyLen; // For null character
LPWSTR lpName = new WCHAR[cMaxSubKeyLen];
DWORD cName;
for (DWORD i = 0; i < cSubKeys; ++i) {
for (DWORD i = 0; i < cSubKeys; ++i)
{
cName = cMaxSubKeyLen;
res = ::RegEnumKeyExW(handle, i, lpName, &cName, NULL, NULL, NULL, NULL);
if (res == ERROR_SUCCESS)
@@ -127,7 +132,8 @@ namespace
DWORD type = 0;
DWORD cbData = 0;
LPWSTR lpValueName = NULL;
if (!name.isEmpty()) {
if (!name.isEmpty())
{
lpValueName = new WCHAR[name.size() + 1];
name.toWCharArray(lpValueName);
lpValueName[name.size()] = 0;
@@ -141,7 +147,8 @@ namespace
if (lpValueName)
delete[] lpValueName;
if (res == ERROR_SUCCESS) {
if (res == ERROR_SUCCESS)
{
lpData[cBuffer - 1] = 0;
result = QString::fromWCharArray(lpData);
}
@@ -169,13 +176,15 @@ namespace
HKEY hkPythonCore;
res = ::RegOpenKeyExW(hkRoot, L"SOFTWARE\\Python\\PythonCore", 0, samDesired, &hkPythonCore);
if (res == ERROR_SUCCESS) {
if (res == ERROR_SUCCESS)
{
QStringList versions = getRegSubkeys(hkPythonCore);
qDebug("Python versions nb: %d", versions.size());
versions.sort();
bool found = false;
while (!found && !versions.empty()) {
while (!found && !versions.empty())
{
const QString version = versions.takeLast() + "\\InstallPath";
LPWSTR lpSubkey = new WCHAR[version.size() + 1];
version.toWCharArray(lpSubkey);
@@ -185,19 +194,23 @@ namespace
res = ::RegOpenKeyExW(hkPythonCore, lpSubkey, 0, samDesired, &hkInstallPath);
delete[] lpSubkey;
if (res == ERROR_SUCCESS) {
if (res == ERROR_SUCCESS)
{
qDebug("Detected possible Python v%s location", qUtf8Printable(version));
path = getRegValue(hkInstallPath);
::RegCloseKey(hkInstallPath);
if (!path.isEmpty()) {
if (!path.isEmpty())
{
const QDir baseDir {path};
if (baseDir.exists("python3.exe")) {
if (baseDir.exists("python3.exe"))
{
found = true;
path = baseDir.filePath("python3.exe");
}
else if (baseDir.exists("python.exe")) {
else if (baseDir.exists("python.exe"))
{
found = true;
path = baseDir.filePath("python.exe");
}
@@ -230,7 +243,8 @@ namespace
// Fallback: Detect python from default locations
const QFileInfoList dirs = QDir("C:/").entryInfoList({"Python*"}, QDir::Dirs, (QDir::Name | QDir::Reversed));
for (const QFileInfo &info : dirs) {
for (const QFileInfo &info : dirs)
{
const QString py3Path {info.absolutePath() + "/python3.exe"};
if (QFile::exists(py3Path))
return py3Path;
@@ -258,7 +272,8 @@ bool Utils::ForeignApps::PythonInfo::isSupportedVersion() const
PythonInfo Utils::ForeignApps::pythonInfo()
{
static PythonInfo pyInfo;
if (!pyInfo.isValid()) {
if (!pyInfo.isValid())
{
if (testPythonInstallation("python3", pyInfo))
return pyInfo;

View File

@@ -113,7 +113,8 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const QString &path)
if (path.isEmpty() || !QDir(path).exists())
return true;
const QStringList deleteFilesList = {
const QStringList deleteFilesList =
{
// Windows
QLatin1String("Thumbs.db"),
QLatin1String("desktop.ini"),
@@ -132,7 +133,8 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const QString &path)
std::sort(dirList.begin(), dirList.end()
, [](const QString &l, const QString &r) { return l.count('/') > r.count('/'); });
for (const QString &p : asConst(dirList)) {
for (const QString &p : asConst(dirList))
{
const QDir dir(p);
// A deeper folder may have not been removed in the previous iteration
// so don't remove anything from this folder either.
@@ -201,7 +203,8 @@ qint64 Utils::Fs::computePathSize(const QString &path)
// Compute folder size based on its content
qint64 size = 0;
QDirIterator iter(path, QDir::Files | QDir::Hidden | QDir::NoSymLinks, QDirIterator::Subdirectories);
while (iter.hasNext()) {
while (iter.hasNext())
{
iter.next();
size += iter.fileInfo().size();
}
@@ -220,7 +223,8 @@ bool Utils::Fs::sameFiles(const QString &path1, const QString &path2)
if (!f2.open(QIODevice::ReadOnly)) return false;
const int readSize = 1024 * 1024; // 1 MiB
while (!f1.atEnd() && !f2.atEnd()) {
while (!f1.atEnd() && !f2.atEnd())
{
if (f1.read(readSize) != f2.read(readSize))
return false;
}
@@ -243,15 +247,18 @@ bool Utils::Fs::isValidFileSystemName(const QString &name, const bool allowSepar
if (name.isEmpty()) return false;
#if defined(Q_OS_WIN)
const QRegularExpression regex {allowSeparators
const QRegularExpression regex
{allowSeparators
? QLatin1String("[:?\"*<>|]")
: QLatin1String("[\\\\/:?\"*<>|]")};
#elif defined(Q_OS_MACOS)
const QRegularExpression regex {allowSeparators
const QRegularExpression regex
{allowSeparators
? QLatin1String("[\\0:]")
: QLatin1String("[\\0/:]")};
#else
const QRegularExpression regex {allowSeparators
const QRegularExpression regex
{allowSeparators
? QLatin1String("[\\0]")
: QLatin1String("[\\0/]")};
#endif
@@ -271,7 +278,8 @@ QString Utils::Fs::branchPath(const QString &filePath, QString *removed)
if (ret.endsWith('/'))
ret.chop(1);
const int slashIndex = ret.lastIndexOf('/');
if (slashIndex >= 0) {
if (slashIndex >= 0)
{
if (removed)
*removed = ret.mid(slashIndex + 1);
ret = ret.left(slashIndex);
@@ -312,7 +320,8 @@ QString Utils::Fs::tempPath()
bool Utils::Fs::isRegularFile(const QString &path)
{
struct ::stat st;
if (::stat(path.toUtf8().constData(), &st) != 0) {
if (::stat(path.toUtf8().constData(), &st) != 0)
{
// analyse erno and log the error
const auto err = errno;
qDebug("Could not get file stats for path '%s'. Error: %s"
@@ -360,7 +369,8 @@ bool Utils::Fs::isNetworkFileSystem(const QString &path)
// Magic number references:
// 1. /usr/include/linux/magic.h
// 2. https://github.com/coreutils/coreutils/blob/master/src/stat.c
switch (static_cast<unsigned int>(buf.f_type)) {
switch (static_cast<unsigned int>(buf.f_type))
{
case 0xFF534D42: // CIFS_MAGIC_NUMBER
case 0x6969: // NFS_SUPER_MAGIC
case 0x517B: // SMB_SUPER_MAGIC

View File

@@ -68,10 +68,12 @@ QByteArray Utils::Gzip::compress(const QByteArray &data, const int level, bool *
output.reserve(deflateBound(&strm, data.size()));
// feed to deflate
while (strm.avail_in > 0) {
while (strm.avail_in > 0)
{
result = deflate(&strm, Z_NO_FLUSH);
if (result != Z_OK) {
if (result != Z_OK)
{
deflateEnd(&strm);
return {};
}
@@ -82,7 +84,8 @@ QByteArray Utils::Gzip::compress(const QByteArray &data, const int level, bool *
}
// flush the rest from deflate
while (result != Z_STREAM_END) {
while (result != Z_STREAM_END)
{
result = deflate(&strm, Z_FINISH);
output.append(tmpBuf.data(), (BUFSIZE - strm.avail_out));
@@ -126,15 +129,18 @@ QByteArray Utils::Gzip::decompress(const QByteArray &data, bool *ok)
output.reserve(data.size() * 3);
// run inflate
while (true) {
while (true)
{
result = inflate(&strm, Z_NO_FLUSH);
if (result == Z_STREAM_END) {
if (result == Z_STREAM_END)
{
output.append(tmpBuf.data(), (BUFSIZE - strm.avail_out));
break;
}
if (result != Z_OK) {
if (result != Z_OK)
{
inflateEnd(&strm);
return {};
}

View File

@@ -41,7 +41,8 @@ Utils::IO::FileDeviceOutputIterator::FileDeviceOutputIterator(QFileDevice &devic
Utils::IO::FileDeviceOutputIterator::~FileDeviceOutputIterator()
{
if (m_buffer.use_count() == 1) {
if (m_buffer.use_count() == 1)
{
if (m_device->error() == QFileDevice::NoError)
m_device->write(*m_buffer);
m_buffer->clear();
@@ -51,7 +52,8 @@ Utils::IO::FileDeviceOutputIterator::~FileDeviceOutputIterator()
Utils::IO::FileDeviceOutputIterator &Utils::IO::FileDeviceOutputIterator::operator=(const char c)
{
m_buffer->append(c);
if (m_buffer->size() >= m_bufferSize) {
if (m_buffer->size() >= m_bufferSize)
{
if (m_device->error() == QFileDevice::NoError)
m_device->write(*m_buffer);
m_buffer->clear();

View File

@@ -63,7 +63,8 @@
namespace
{
const struct { const char *source; const char *comment; } units[] = {
const struct { const char *source; const char *comment; } units[] =
{
QT_TRANSLATE_NOOP3("misc", "B", "bytes"),
QT_TRANSLATE_NOOP3("misc", "KiB", "kibibytes (1024 bytes)"),
QT_TRANSLATE_NOOP3("misc", "MiB", "mebibytes (1024 kibibytes)"),
@@ -85,7 +86,8 @@ namespace
int i = 0;
val = static_cast<qreal>(sizeInBytes);
while ((val >= 1024.) && (i <= static_cast<int>(Utils::Misc::SizeUnit::ExbiByte))) {
while ((val >= 1024.) && (i <= static_cast<int>(Utils::Misc::SizeUnit::ExbiByte)))
{
val /= 1024.;
++i;
}
@@ -119,13 +121,16 @@ void Utils::Misc::shutdownComputer(const ShutdownDialogAction &action)
if (GetLastError() != ERROR_SUCCESS)
return;
if (action == ShutdownDialogAction::Suspend) {
if (action == ShutdownDialogAction::Suspend)
{
::SetSuspendState(false, false, false);
}
else if (action == ShutdownDialogAction::Hibernate) {
else if (action == ShutdownDialogAction::Hibernate)
{
::SetSuspendState(true, false, false);
}
else {
else
{
const QString msg = QCoreApplication::translate("misc", "qBittorrent will shutdown the computer now because all downloads are complete.");
auto msgWchar = std::make_unique<wchar_t[]>(msg.length() + 1);
msg.toWCharArray(msgWchar.get());
@@ -171,11 +176,13 @@ void Utils::Misc::shutdownComputer(const ShutdownDialogAction &action)
#elif (defined(Q_OS_UNIX) && defined(QT_DBUS_LIB))
// Use dbus to power off / suspend the system
if (action != ShutdownDialogAction::Shutdown) {
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());
if (login1Iface.isValid()) {
if (login1Iface.isValid())
{
if (action == ShutdownDialogAction::Suspend)
login1Iface.call("Suspend", false);
else
@@ -185,7 +192,8 @@ void Utils::Misc::shutdownComputer(const ShutdownDialogAction &action)
// Else, other recent systems use UPower
QDBusInterface upowerIface("org.freedesktop.UPower", "/org/freedesktop/UPower",
"org.freedesktop.UPower", QDBusConnection::systemBus());
if (upowerIface.isValid()) {
if (upowerIface.isValid())
{
if (action == ShutdownDialogAction::Suspend)
upowerIface.call("Suspend");
else
@@ -201,18 +209,21 @@ void Utils::Misc::shutdownComputer(const ShutdownDialogAction &action)
else
halIface.call("Hibernate");
}
else {
else
{
// Some recent systems use systemd's logind
QDBusInterface login1Iface("org.freedesktop.login1", "/org/freedesktop/login1",
"org.freedesktop.login1.Manager", QDBusConnection::systemBus());
if (login1Iface.isValid()) {
if (login1Iface.isValid())
{
login1Iface.call("PowerOff", false);
return;
}
// Else, other recent systems use ConsoleKit
QDBusInterface consolekitIface("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Manager",
"org.freedesktop.ConsoleKit.Manager", QDBusConnection::systemBus());
if (consolekitIface.isValid()) {
if (consolekitIface.isValid())
{
consolekitIface.call("Stop");
return;
}
@@ -251,7 +262,8 @@ QString Utils::Misc::friendlyUnit(const qint64 bytesValue, const bool isSpeed)
int Utils::Misc::friendlyUnitPrecision(const SizeUnit unit)
{
// friendlyUnit's number of digits after the decimal point
switch (unit) {
switch (unit)
{
case SizeUnit::Byte:
return 0;
case SizeUnit::KibiByte:
@@ -273,7 +285,8 @@ qlonglong Utils::Misc::sizeInBytes(qreal size, const Utils::Misc::SizeUnit unit)
bool Utils::Misc::isPreviewable(const QString &extension)
{
static const QSet<QString> multimediaExtensions = {
static const QSet<QString> multimediaExtensions =
{
"3GP",
"AAC",
"AC3",
@@ -338,13 +351,15 @@ QString Utils::Misc::userFriendlyDuration(const qlonglong seconds, const qlonglo
return QCoreApplication::translate("misc", "%1m", "e.g: 10minutes").arg(QString::number(minutes));
qlonglong hours = (minutes / 60);
if (hours < 24) {
if (hours < 24)
{
minutes -= (hours * 60);
return QCoreApplication::translate("misc", "%1h %2m", "e.g: 3hours 5minutes").arg(QString::number(hours), QString::number(minutes));
}
qlonglong days = (hours / 24);
if (days < 365) {
if (days < 365)
{
hours -= (days * 24);
return QCoreApplication::translate("misc", "%1d %2h", "e.g: 2days 10hours").arg(QString::number(days), QString::number(hours));
}
@@ -479,7 +494,8 @@ QString Utils::Misc::zlibVersionString()
#ifdef Q_OS_WIN
QString Utils::Misc::windowsSystemPath()
{
static const QString path = []() -> QString {
static const QString path = []() -> QString
{
WCHAR systemPath[MAX_PATH] = {0};
GetSystemDirectoryW(systemPath, sizeof(systemPath) / sizeof(WCHAR));
return QString::fromWCharArray(systemPath);

View File

@@ -70,12 +70,14 @@ namespace Utils
QHostAddress protocolEquivalentAddress;
bool addrConversionOk = false;
if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
if (addr.protocol() == QAbstractSocket::IPv4Protocol)
{
// always succeeds
protocolEquivalentAddress = QHostAddress(addr.toIPv6Address());
addrConversionOk = true;
}
else {
else
{
// only succeeds when addr is an ipv4-mapped ipv6 address
protocolEquivalentAddress = QHostAddress(addr.toIPv4Address(&addrConversionOk));
}

View File

@@ -71,7 +71,8 @@ QByteArray Utils::Password::PBKDF2::generate(const QString &password)
QByteArray Utils::Password::PBKDF2::generate(const QByteArray &password)
{
const std::array<uint32_t, 4> salt {{Random::rand(), Random::rand()
const std::array<uint32_t, 4> salt
{{Random::rand(), Random::rand()
, Random::rand(), Random::rand()}};
std::array<unsigned char, 64> outBuf {};

View File

@@ -82,7 +82,8 @@ namespace
int posL = 0;
int posR = 0;
while (true) {
while (true)
{
if ((posL == left.size()) || (posR == right.size()))
return (left.size() - right.size()); // when a shorter string is another string's prefix, shorter string place before longer string
@@ -91,12 +92,14 @@ namespace
// Compare only non-digits.
// Numbers should be compared as a whole
// otherwise the string->int conversion can yield a wrong value
if ((leftChar == rightChar) && !leftChar.isDigit()) {
if ((leftChar == rightChar) && !leftChar.isDigit())
{
// compare next character
++posL;
++posR;
}
else if (leftChar.isDigit() && rightChar.isDigit()) {
else if (leftChar.isDigit() && rightChar.isDigit())
{
// Both are digits, compare the numbers
const auto numberView = [](const QString &str, int &pos) -> QStringRef
@@ -114,7 +117,8 @@ namespace
return (numViewL.length() - numViewR.length());
// both string/view has the same length
for (int i = 0; i < numViewL.length(); ++i) {
for (int i = 0; i < numViewL.length(); ++i)
{
const QChar numL = numViewL[i];
const QChar numR = numViewR[i];
@@ -125,7 +129,8 @@ namespace
// String + digits do match and we haven't hit the end of both strings
// then continue to consume the remainings
}
else {
else
{
return (leftChar.unicode() - rightChar.unicode());
}
}
@@ -140,7 +145,8 @@ int Utils::String::naturalCompare(const QString &left, const QString &right, con
{
// provide a single `NaturalCompare` instance for easy use
// https://doc.qt.io/qt-5/threads-reentrancy.html
if (caseSensitivity == Qt::CaseSensitive) {
if (caseSensitivity == Qt::CaseSensitive)
{
#ifdef QBT_USES_QTHREADSTORAGE
static QThreadStorage<NaturalCompare> nCmp;
if (!nCmp.hasLocalData())

View File

@@ -58,7 +58,8 @@ namespace Utils
{
if (str.length() < 2) return str;
for (const QChar quote : quotes) {
for (const QChar quote : quotes)
{
if (str.startsWith(quote) && str.endsWith(quote))
return str.mid(1, (str.length() - 2));
}

View File

@@ -151,10 +151,12 @@ namespace Utils
template <typename StringClassWithSplitMethod>
static Version tryParse(const StringClassWithSplitMethod &s, const Version &defaultVersion)
{
try {
try
{
return Version(s);
}
catch (const std::runtime_error &er) {
catch (const std::runtime_error &er)
{
qDebug() << "Error parsing version:" << er.what();
return defaultVersion;
}
@@ -172,7 +174,8 @@ namespace Utils
bool ok = false;
ComponentsArray res {{}};
for (std::size_t i = 0; i < static_cast<std::size_t>(versionParts.size()); ++i) {
for (std::size_t i = 0; i < static_cast<std::size_t>(versionParts.size()); ++i)
{
res[i] = static_cast<T>(versionParts[static_cast<typename StringsList::size_type>(i)].toInt(&ok));
if (!ok)
throw std::runtime_error("Can not parse version component");