From c41df9ffbd1ebbb590201af156a38323e3568466 Mon Sep 17 00:00:00 2001 From: "Vladimir Golovnev (Glassez)" Date: Mon, 16 Nov 2020 10:02:11 +0300 Subject: [PATCH] Improve coding style --- CODING_GUIDELINES.md | 66 +- src/app/application.cpp | 84 ++- src/app/applicationinstancemanager.cpp | 12 +- src/app/cmdoptions.cpp | 105 ++- src/app/filelogger.cpp | 24 +- src/app/main.cpp | 63 +- src/app/qtlocalpeer/qtlocalpeer.cpp | 27 +- src/app/stacktrace.h | 36 +- src/app/stacktrace_win.h | 39 +- src/app/upgrade.cpp | 15 +- src/base/asyncfilestorage.cpp | 9 +- src/base/bittorrent/bandwidthscheduler.cpp | 12 +- src/base/bittorrent/customstorage.cpp | 21 +- src/base/bittorrent/downloadpriority.cpp | 3 +- src/base/bittorrent/filterparserthread.cpp | 213 ++++-- .../bittorrent/nativesessionextension.cpp | 6 +- src/base/bittorrent/peeraddress.cpp | 9 +- src/base/bittorrent/peerinfo.cpp | 60 +- src/base/bittorrent/portforwarderimpl.cpp | 15 +- .../bittorrent/resumedatasavingmanager.cpp | 9 +- src/base/bittorrent/session.cpp | 696 ++++++++++++------ src/base/bittorrent/speedmonitor.cpp | 3 +- src/base/bittorrent/statistics.cpp | 6 +- src/base/bittorrent/torrentcreatorthread.cpp | 42 +- src/base/bittorrent/torrenthandleimpl.cpp | 228 ++++-- src/base/bittorrent/torrentinfo.cpp | 36 +- src/base/bittorrent/tracker.cpp | 75 +- src/base/bittorrent/trackerentry.cpp | 9 +- src/base/filesystemwatcher.cpp | 21 +- src/base/http/connection.cpp | 21 +- src/base/http/requestparser.cpp | 90 ++- src/base/http/server.cpp | 9 +- src/base/net/dnsupdater.cpp | 72 +- src/base/net/downloadhandlerimpl.cpp | 30 +- src/base/net/downloadmanager.cpp | 36 +- src/base/net/geoipdatabase.cpp | 99 ++- src/base/net/geoipdatabase.h | 3 +- src/base/net/geoipmanager.cpp | 30 +- src/base/net/proxyconfigurationmanager.cpp | 12 +- src/base/net/reverseresolution.cpp | 6 +- src/base/net/smtp.cpp | 141 ++-- src/base/preferences.cpp | 36 +- src/base/profile.cpp | 3 +- src/base/profile_p.cpp | 6 +- src/base/rss/rss_article.cpp | 3 +- src/base/rss/rss_autodownloader.cpp | 57 +- src/base/rss/rss_autodownloadrule.cpp | 66 +- src/base/rss/rss_feed.cpp | 78 +- src/base/rss/rss_folder.cpp | 3 +- src/base/rss/rss_item.cpp | 9 +- src/base/rss/rss_parser.cpp | 183 +++-- src/base/rss/rss_session.cpp | 102 ++- src/base/rss/rss_session.h | 18 +- src/base/scanfoldersmodel.cpp | 69 +- src/base/search/searchdownloadhandler.cpp | 6 +- src/base/search/searchhandler.cpp | 9 +- src/base/search/searchpluginmanager.cpp | 108 ++- src/base/settingsstorage.cpp | 24 +- src/base/torrentfilter.cpp | 15 +- src/base/utils/bytearray.cpp | 3 +- src/base/utils/foreignapps.cpp | 45 +- src/base/utils/fs.cpp | 30 +- src/base/utils/gzip.cpp | 18 +- src/base/utils/io.cpp | 6 +- src/base/utils/misc.cpp | 48 +- src/base/utils/net.cpp | 6 +- src/base/utils/password.cpp | 3 +- src/base/utils/string.cpp | 18 +- src/base/utils/string.h | 3 +- src/base/utils/version.h | 9 +- src/gui/aboutdialog.cpp | 9 +- src/gui/addnewtorrentdialog.cpp | 99 ++- src/gui/advancedsettings.cpp | 33 +- src/gui/autoexpandabledialog.cpp | 12 +- src/gui/banlistoptionsdialog.cpp | 18 +- src/gui/categoryfiltermodel.cpp | 42 +- src/gui/categoryfilterwidget.cpp | 21 +- src/gui/cookiesmodel.cpp | 12 +- src/gui/downloadfromurldialog.cpp | 9 +- src/gui/executionlogwidget.cpp | 3 +- src/gui/fspathedit.cpp | 24 +- src/gui/fspathedit_p.cpp | 39 +- src/gui/ipsubnetwhitelistoptionsdialog.cpp | 9 +- src/gui/lineedit.cpp | 3 +- src/gui/log/logmodel.cpp | 9 +- src/gui/mainwindow.cpp | 321 +++++--- src/gui/optionsdialog.cpp | 198 +++-- src/gui/previewlistdelegate.cpp | 6 +- src/gui/previewselectdialog.cpp | 18 +- src/gui/programupdater.cpp | 30 +- src/gui/properties/downloadedpiecesbar.cpp | 30 +- src/gui/properties/peerlistsortmodel.cpp | 6 +- src/gui/properties/peerlistwidget.cpp | 66 +- src/gui/properties/peersadditiondialog.cpp | 12 +- src/gui/properties/pieceavailabilitybar.cpp | 24 +- src/gui/properties/piecesbar.cpp | 45 +- src/gui/properties/propertieswidget.cpp | 78 +- src/gui/properties/proplistdelegate.cpp | 15 +- src/gui/properties/proptabbar.cpp | 12 +- src/gui/properties/speedplotview.cpp | 39 +- src/gui/properties/speedwidget.cpp | 9 +- src/gui/properties/trackerlistwidget.cpp | 105 ++- src/gui/properties/trackersadditiondialog.cpp | 15 +- src/gui/rss/articlelistwidget.cpp | 18 +- src/gui/rss/automatedrssdownloader.cpp | 135 ++-- src/gui/rss/feedlistwidget.cpp | 27 +- src/gui/rss/htmlbrowser.cpp | 15 +- src/gui/rss/rsswidget.cpp | 75 +- src/gui/scanfoldersdelegate.cpp | 9 +- src/gui/search/pluginselectdialog.cpp | 99 ++- src/gui/search/searchjobwidget.cpp | 33 +- src/gui/search/searchsortmodel.cpp | 27 +- src/gui/search/searchwidget.cpp | 42 +- src/gui/shutdownconfirmdialog.cpp | 6 +- src/gui/speedlimitdialog.cpp | 3 +- src/gui/statusbar.cpp | 30 +- src/gui/tagfiltermodel.cpp | 12 +- src/gui/tagfilterwidget.cpp | 21 +- src/gui/torrentcategorydialog.cpp | 12 +- src/gui/torrentcontentfiltermodel.cpp | 21 +- src/gui/torrentcontentmodel.cpp | 48 +- src/gui/torrentcontentmodelfolder.cpp | 27 +- src/gui/torrentcontentmodelitem.cpp | 18 +- src/gui/torrentcontenttreeview.cpp | 72 +- src/gui/torrentcreatordialog.cpp | 21 +- src/gui/trackerentriesdialog.cpp | 9 +- src/gui/transferlistdelegate.cpp | 3 +- src/gui/transferlistfilterswidget.cpp | 81 +- src/gui/transferlistmodel.cpp | 63 +- src/gui/transferlistsortmodel.cpp | 42 +- src/gui/transferlistwidget.cpp | 171 +++-- src/gui/tristatewidget.cpp | 21 +- src/gui/uithememanager.cpp | 45 +- src/gui/updownratiodialog.cpp | 9 +- src/gui/utils.cpp | 24 +- src/webui/api/appcontroller.cpp | 75 +- src/webui/api/authcontroller.cpp | 18 +- src/webui/api/isessionmanager.h | 3 +- src/webui/api/logcontroller.cpp | 12 +- src/webui/api/rsscontroller.cpp | 15 +- src/webui/api/searchcontroller.cpp | 45 +- src/webui/api/serialize/serialize_torrent.cpp | 12 +- src/webui/api/synccontroller.cpp | 99 ++- src/webui/api/torrentscontroller.cpp | 129 ++-- src/webui/api/transfercontroller.cpp | 3 +- src/webui/webapplication.cpp | 141 ++-- src/webui/webui.cpp | 42 +- 147 files changed, 4454 insertions(+), 2227 deletions(-) diff --git a/CODING_GUIDELINES.md b/CODING_GUIDELINES.md index 1513a11d8..bd224ee06 100644 --- a/CODING_GUIDELINES.md +++ b/CODING_GUIDELINES.md @@ -47,7 +47,7 @@ int myFunction(int a) void myFunction() {} // empty body MyClass::MyClass(int *parent) - : m_parent(parent) + : m_parent {parent} { // initialize } @@ -86,15 +86,18 @@ namespace Name ### b. Other code blocks ```c++ -if (condition) { +if (condition) +{ // code } -for (int a = 0; a < b; ++b) { +for (int a = 0; a < b; ++b) +{ // code } -switch (a) { +switch (a) +{ case 1: // blah case 2: @@ -102,18 +105,25 @@ case 2: default: // blah } + +{ + // code +} ``` ### c. Blocks in switch's case labels ```c++ -switch (var) { -case 1: { +switch (var) +{ +case 1: + { // declare local variables // code } break; -case 2: { +case 2: + { // declare local variables // code } @@ -128,13 +138,16 @@ default: The `else if`/`else` must be on their own lines: ```c++ -if (condition) { +if (condition) +{ // code } -else if (condition) { +else if (condition) +{ // code } -else { +else +{ // code } ``` @@ -155,7 +168,8 @@ However you can still choose to use the first rule. ```c++ if (a > 0) return; -while (p) { +while (p) +{ // ... if (!b) continue; } @@ -178,14 +192,18 @@ else if (a > b) else do(c); -if (a < b) { +if (a < b) +{ do(a); } -else if (a > b) { // curly braces required here, then all branches should also add them +else if (a > b) +{ + // curly braces required here, then all branches should also add them do(b); do(d); } -else { +else +{ do(c); } ``` @@ -216,10 +234,10 @@ Initialization lists should be vertical. This will allow for more easily readabl ```c++ myClass::myClass(int a, int b, int c, int d) - : m_a(a) - , m_b(b) - , m_c(c) - , m_d(d) + : m_a {a} + , m_b {b} + , m_c {c} + , m_d {d} { // code } @@ -396,13 +414,15 @@ class ExampleWidget : public QWidget template void doSomethingWithList(const List &list) { - foreach (const auto &item, list) { + foreach (const auto &item, list) + { // we don't know item type here so we use 'auto' keyword // do something with item } } - for (auto it = container.begin(), end = container.end(); it != end; ++it) { + for (auto it = container.begin(), end = container.end(); it != end; ++it) + { // we don't need to know the exact iterator type, // because all iterators have the same interface } @@ -420,10 +440,12 @@ class ExampleWidget : public QWidget a = (b <= MAX_B ? b : MAX_B); ++a; --b; - for (int a = 0; a < b; ++b) { + for (int a = 0; a < b; ++b) + { } // Range-based for loop, spaces before and after the colon - for (auto i : container) { + for (auto i : container) + { } // Derived class, spaces before and after the colon class Derived : public Base diff --git a/src/app/application.cpp b/src/app/application.cpp index 9a8866086..1b0ebd683 100644 --- a/src/app/application.cpp +++ b/src/app/application.cpp @@ -181,12 +181,14 @@ Application::Application(int &argc, char **argv) m_fileLogger = new FileLogger(fileLoggerPath(), isFileLoggerBackup(), fileLoggerMaxSize(), isFileLoggerDeleteOld(), fileLoggerAge(), static_cast(fileLoggerAgeType())); Logger::instance()->addMessage(tr("qBittorrent %1 started", "qBittorrent v3.2.0alpha started").arg(QBT_VERSION)); - if (portableModeEnabled) { + if (portableModeEnabled) + { Logger::instance()->addMessage(tr("Running in portable mode. Auto detected profile folder at: %1").arg(profileDir)); 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 } - else { + else + { Logger::instance()->addMessage(tr("Using config directory: %1").arg(Profile::instance()->location(SpecialFolder::Config))); } } @@ -361,11 +363,13 @@ void Application::runExternalProgram(const BitTorrent::TorrentHandle *torrent) c proc.setArguments(argList); proc.setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments *args) { - if (Preferences::instance()->isAutoRunConsoleEnabled()) { + if (Preferences::instance()->isAutoRunConsoleEnabled()) + { args->flags |= CREATE_NEW_CONSOLE; args->flags &= ~(CREATE_NO_WINDOW | DETACHED_PROCESS); } - else { + else + { args->flags |= CREATE_NO_WINDOW; args->flags &= ~(CREATE_NEW_CONSOLE | DETACHED_PROCESS); } @@ -428,7 +432,8 @@ void Application::torrentFinished(BitTorrent::TorrentHandle *const torrent) runExternalProgram(torrent); // Mail notification - if (pref->isMailNotificationEnabled()) { + if (pref->isMailNotificationEnabled()) + { Logger::instance()->addMessage(tr("Torrent: %1, sending mail notification").arg(torrent->name())); sendNotificationEmail(torrent); } @@ -455,16 +460,19 @@ void Application::allTorrentsFinished() #ifndef DISABLE_GUI // ask confirm - if ((action == ShutdownDialogAction::Exit) && (pref->dontConfirmAutoExit())) { + if ((action == ShutdownDialogAction::Exit) && (pref->dontConfirmAutoExit())) + { // do nothing & skip confirm } - else { + else + { if (!ShutdownConfirmDialog::askForConfirmation(m_window, action)) return; } #endif // DISABLE_GUI // Actually shut down - if (action != ShutdownDialogAction::Exit) { + if (action != ShutdownDialogAction::Exit) + { qDebug("Preparing for auto-shutdown because all downloads are complete!"); // Disabling it for next time pref->setShutdownWhenDownloadsComplete(false); @@ -490,7 +498,8 @@ bool Application::sendParams(const QStringList ¶ms) void Application::processParams(const QStringList ¶ms) { #ifndef DISABLE_GUI - if (params.isEmpty()) { + if (params.isEmpty()) + { m_window->activate(); // show UI return; } @@ -498,42 +507,50 @@ void Application::processParams(const QStringList ¶ms) BitTorrent::AddTorrentParams torrentParams; TriStateBool skipTorrentDialog; - for (QString param : params) { + for (QString param : params) + { param = param.trimmed(); // Process strings indicating options specified by the user. - if (param.startsWith(QLatin1String("@savePath="))) { + if (param.startsWith(QLatin1String("@savePath="))) + { torrentParams.savePath = param.mid(10); continue; } - if (param.startsWith(QLatin1String("@addPaused="))) { + if (param.startsWith(QLatin1String("@addPaused="))) + { torrentParams.addPaused = param.midRef(11).toInt() ? TriStateBool::True : TriStateBool::False; continue; } - if (param == QLatin1String("@skipChecking")) { + if (param == QLatin1String("@skipChecking")) + { torrentParams.skipChecking = true; continue; } - if (param.startsWith(QLatin1String("@category="))) { + if (param.startsWith(QLatin1String("@category="))) + { torrentParams.category = param.mid(10); continue; } - if (param == QLatin1String("@sequential")) { + if (param == QLatin1String("@sequential")) + { torrentParams.sequential = true; continue; } - if (param == QLatin1String("@firstLastPiecePriority")) { + if (param == QLatin1String("@firstLastPiecePriority")) + { torrentParams.firstLastPiecePriority = true; continue; } - if (param.startsWith(QLatin1String("@skipDialog="))) { + if (param.startsWith(QLatin1String("@skipDialog="))) + { skipTorrentDialog = param.midRef(12).toInt() ? TriStateBool::True : TriStateBool::False; continue; } @@ -561,7 +578,8 @@ int Application::exec(const QStringList ¶ms) Net::DownloadManager::initInstance(); IconProvider::initInstance(); - try { + try + { BitTorrent::Session::initInstance(); connect(BitTorrent::Session::instance(), &BitTorrent::Session::torrentFinished, this, &Application::torrentFinished); connect(BitTorrent::Session::instance(), &BitTorrent::Session::allTorrentsFinished, this, &Application::allTorrentsFinished, Qt::QueuedConnection); @@ -581,7 +599,8 @@ int Application::exec(const QStringList ¶ms) new RSS::Session; // create RSS::Session singleton new RSS::AutoDownloader; // create RSS::AutoDownloader singleton } - catch (const RuntimeError &err) { + catch (const RuntimeError &err) + { #ifdef DISABLE_GUI fprintf(stderr, "%s", err.what()); #else @@ -605,7 +624,8 @@ int Application::exec(const QStringList ¶ms) .arg(QString("http://localhost:") + QString::number(pref->getWebUiPort())) + '\n'; printf("%s", qUtf8Printable(mesg)); - if (pref->getWebUIPassword() == "ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsJRJPaCU51dEiz+dTzh8qbPsL8WkFljQYFQ==") { + if (pref->getWebUIPassword() == "ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsJRJPaCU51dEiz+dTzh8qbPsL8WkFljQYFQ==") + { const QString warning = tr("The Web UI administrator username is: %1").arg(pref->getWebUiUsername()) + '\n' + tr("The Web UI administrator password is still the default one: %1").arg("adminadmin") + '\n' + tr("This is a security risk, please consider changing your password from program preferences.") + '\n'; @@ -623,7 +643,8 @@ int Application::exec(const QStringList ¶ms) BitTorrent::Session::instance()->startUpTorrents(); m_paramsQueue = params + m_paramsQueue; - if (!m_paramsQueue.isEmpty()) { + if (!m_paramsQueue.isEmpty()) + { processParams(m_paramsQueue); m_paramsQueue.clear(); } @@ -639,7 +660,8 @@ bool Application::isRunning() #ifdef Q_OS_MACOS bool Application::event(QEvent *ev) { - if (ev->type() == QEvent::FileOpen) { + if (ev->type() == QEvent::FileOpen) + { QString path = static_cast(ev)->file(); if (path.isEmpty()) // Get the url instead @@ -651,7 +673,8 @@ bool Application::event(QEvent *ev) m_paramsQueue.append(path); return true; } - else { + else + { return BaseApplication::event(ev); } } @@ -679,11 +702,13 @@ void Application::initializeTranslation() installTranslator(&m_translator); #ifndef DISABLE_GUI - if (localeStr.startsWith("ar") || localeStr.startsWith("he")) { + if (localeStr.startsWith("ar") || localeStr.startsWith("he")) + { qDebug("Right to Left mode"); setLayoutDirection(Qt::RightToLeft); } - else { + else + { setLayoutDirection(Qt::LeftToRight); } #endif @@ -725,7 +750,8 @@ void Application::cleanup() return; #ifndef DISABLE_GUI - if (m_window) { + if (m_window) + { // Hide the window and don't leave it on screen as // unresponsive. Also for Windows take the WinId // after it's hidden, because hide() may cause a @@ -769,7 +795,8 @@ void Application::cleanup() Utils::Fs::removeDirRecursive(Utils::Fs::tempPath()); #ifndef DISABLE_GUI - if (m_window) { + if (m_window) + { #ifdef Q_OS_WIN ::ShutdownBlockReasonDestroy(reinterpret_cast(m_window->effectiveWinId())); #endif // Q_OS_WIN @@ -780,7 +807,8 @@ void Application::cleanup() Profile::freeInstance(); - if (m_shutdownAct != ShutdownDialogAction::Exit) { + if (m_shutdownAct != ShutdownDialogAction::Exit) + { qDebug() << "Sending computer shutdown/suspend/hibernate signal..."; Utils::Misc::shutdownComputer(m_shutdownAct); } diff --git a/src/app/applicationinstancemanager.cpp b/src/app/applicationinstancemanager.cpp index 007ee21df..0feed1586 100644 --- a/src/app/applicationinstancemanager.cpp +++ b/src/app/applicationinstancemanager.cpp @@ -46,16 +46,20 @@ ApplicationInstanceManager::ApplicationInstanceManager(const QString &appId, QOb #ifdef Q_OS_WIN auto sharedMem = new QSharedMemory {appId + QLatin1String {"-shared-memory-key"}, this}; - if (m_isFirstInstance) { + if (m_isFirstInstance) + { // First instance creates shared memory and store PID - if (sharedMem->create(sizeof(DWORD)) && sharedMem->lock()) { + if (sharedMem->create(sizeof(DWORD)) && sharedMem->lock()) + { *(static_cast(sharedMem->data())) = ::GetCurrentProcessId(); sharedMem->unlock(); } } - else { + else + { // Later instances attach to shared memory and retrieve PID - if (sharedMem->attach() && sharedMem->lock()) { + if (sharedMem->attach() && sharedMem->lock()) + { ::AllowSetForegroundWindow(*(static_cast(sharedMem->data()))); sharedMem->unlock(); } diff --git a/src/app/cmdoptions.cpp b/src/app/cmdoptions.cpp index 90c1fcd6a..8fe86fbf4 100644 --- a/src/app/cmdoptions.cpp +++ b/src/app/cmdoptions.cpp @@ -217,7 +217,8 @@ namespace bool ok; int res = val.toInt(&ok); - if (!ok) { + if (!ok) + { qDebug() << QObject::tr("Expected integer number in environment variable '%1', but got '%2'") .arg(envVarName(), val); return defaultValue; @@ -257,16 +258,20 @@ namespace { QStringList parts = arg.split(QLatin1Char('=')); - if (parts.size() == 1) { + if (parts.size() == 1) + { return TriStateBool(m_defaultValue); } - if (parts.size() == 2) { + if (parts.size() == 2) + { QString val = parts[1]; - if ((val.toUpper() == QLatin1String("TRUE")) || (val == QLatin1String("1"))) { + if ((val.toUpper() == QLatin1String("TRUE")) || (val == QLatin1String("1"))) + { return TriStateBool::True; } - if ((val.toUpper() == QLatin1String("FALSE")) || (val == QLatin1String("0"))) { + if ((val.toUpper() == QLatin1String("FALSE")) || (val == QLatin1String("0"))) + { return TriStateBool::False; } } @@ -281,16 +286,20 @@ namespace { const QString val = env.value(envVarName(), "-1"); - if (val.isEmpty()) { + if (val.isEmpty()) + { return TriStateBool(m_defaultValue); } - if (val == QLatin1String("-1")) { + if (val == QLatin1String("-1")) + { return TriStateBool::Undefined; } - if ((val.toUpper() == QLatin1String("TRUE")) || (val == QLatin1String("1"))) { + if ((val.toUpper() == QLatin1String("TRUE")) || (val == QLatin1String("1"))) + { return TriStateBool::True; } - if ((val.toUpper() == QLatin1String("FALSE")) || (val == QLatin1String("0"))) { + if ((val.toUpper() == QLatin1String("FALSE")) || (val == QLatin1String("0"))) + { return TriStateBool::False; } @@ -365,10 +374,12 @@ QStringList QBtCommandLineParameters::paramList() const if (!savePath.isEmpty()) result.append(QLatin1String("@savePath=") + savePath); - if (addPaused == TriStateBool::True) { + if (addPaused == TriStateBool::True) + { result.append(QLatin1String("@addPaused=1")); } - else if (addPaused == TriStateBool::False) { + else if (addPaused == TriStateBool::False) + { result.append(QLatin1String("@addPaused=0")); } @@ -384,10 +395,12 @@ QStringList QBtCommandLineParameters::paramList() const if (firstLastPiecePriority) result.append(QLatin1String("@firstLastPiecePriority")); - if (skipDialog == TriStateBool::True) { + if (skipDialog == TriStateBool::True) + { result.append(QLatin1String("@skipDialog=1")); } - else if (skipDialog == TriStateBool::False) { + else if (skipDialog == TriStateBool::False) + { result.append(QLatin1String("@skipDialog=0")); } @@ -399,72 +412,91 @@ QBtCommandLineParameters parseCommandLine(const QStringList &args) { QBtCommandLineParameters result {QProcessEnvironment::systemEnvironment()}; - for (int i = 1; i < args.count(); ++i) { + for (int i = 1; i < args.count(); ++i) + { const QString &arg = args[i]; if ((arg.startsWith("--") && !arg.endsWith(".torrent")) - || (arg.startsWith('-') && (arg.size() == 2))) { + || (arg.startsWith('-') && (arg.size() == 2))) + { // Parse known parameters - if (arg == SHOW_HELP_OPTION) { + if (arg == SHOW_HELP_OPTION) + { result.showHelp = true; } #if !defined(Q_OS_WIN) || defined(DISABLE_GUI) - else if (arg == SHOW_VERSION_OPTION) { + else if (arg == SHOW_VERSION_OPTION) + { result.showVersion = true; } #endif - else if (arg == WEBUI_PORT_OPTION) { + else if (arg == WEBUI_PORT_OPTION) + { result.webUiPort = WEBUI_PORT_OPTION.value(arg); if ((result.webUiPort < 1) || (result.webUiPort > 65535)) throw CommandLineParameterError(QObject::tr("%1 must specify a valid port (1 to 65535).") .arg(QLatin1String("--webui-port"))); } #ifndef DISABLE_GUI - else if (arg == NO_SPLASH_OPTION) { + else if (arg == NO_SPLASH_OPTION) + { result.noSplash = true; } #elif !defined(Q_OS_WIN) - else if (arg == DAEMON_OPTION) { + else if (arg == DAEMON_OPTION) + { result.shouldDaemonize = true; } #endif - else if (arg == PROFILE_OPTION) { + else if (arg == PROFILE_OPTION) + { result.profileDir = PROFILE_OPTION.value(arg); } - else if (arg == RELATIVE_FASTRESUME) { + else if (arg == RELATIVE_FASTRESUME) + { result.relativeFastresumePaths = true; } - else if (arg == CONFIGURATION_OPTION) { + else if (arg == CONFIGURATION_OPTION) + { result.configurationName = CONFIGURATION_OPTION.value(arg); } - else if (arg == SAVE_PATH_OPTION) { + else if (arg == SAVE_PATH_OPTION) + { result.savePath = SAVE_PATH_OPTION.value(arg); } - else if (arg == PAUSED_OPTION) { + else if (arg == PAUSED_OPTION) + { result.addPaused = PAUSED_OPTION.value(arg); } - else if (arg == SKIP_HASH_CHECK_OPTION) { + else if (arg == SKIP_HASH_CHECK_OPTION) + { result.skipChecking = true; } - else if (arg == CATEGORY_OPTION) { + else if (arg == CATEGORY_OPTION) + { result.category = CATEGORY_OPTION.value(arg); } - else if (arg == SEQUENTIAL_OPTION) { + else if (arg == SEQUENTIAL_OPTION) + { result.sequential = true; } - else if (arg == FIRST_AND_LAST_OPTION) { + else if (arg == FIRST_AND_LAST_OPTION) + { result.firstLastPiecePriority = true; } - else if (arg == SKIP_DIALOG_OPTION) { + else if (arg == SKIP_DIALOG_OPTION) + { result.skipDialog = SKIP_DIALOG_OPTION.value(arg); } - else { + else + { // Unknown argument result.unknownParameter = arg; break; } } - else { + else + { QFileInfo torrentPath; torrentPath.setFile(arg); @@ -495,11 +527,14 @@ QString wrapText(const QString &text, int initialIndentation = USAGE_TEXT_COLUMN QStringList lines = {words.first()}; int currentLineMaxLength = wrapAtColumn - initialIndentation; - for (const QString &word : asConst(words.mid(1))) { - if (lines.last().length() + word.length() + 1 < currentLineMaxLength) { + for (const QString &word : asConst(words.mid(1))) + { + if (lines.last().length() + word.length() + 1 < currentLineMaxLength) + { lines.last().append(' ' + word); } - else { + else + { lines.append(QString(initialIndentation, ' ') + word); currentLineMaxLength = wrapAtColumn; } diff --git a/src/app/filelogger.cpp b/src/app/filelogger.cpp index 31577255d..9199cb45a 100644 --- a/src/app/filelogger.cpp +++ b/src/app/filelogger.cpp @@ -73,7 +73,8 @@ void FileLogger::changePath(const QString &newPath) dir.mkpath(newPath); const QString tmpPath = dir.absoluteFilePath("qbittorrent.log"); - if (tmpPath != m_path) { + if (tmpPath != m_path) + { m_path = tmpPath; closeLogFile(); @@ -89,9 +90,11 @@ void FileLogger::deleteOld(const int age, const FileLogAgeType ageType) const QFileInfoList fileList = dir.entryInfoList(QStringList("qbittorrent.log.bak*") , (QDir::Files | QDir::Writable), (QDir::Time | QDir::Reversed)); - for (const QFileInfo &file : fileList) { + for (const QFileInfo &file : fileList) + { QDateTime modificationDate = file.lastModified(); - switch (ageType) { + switch (ageType) + { case DAYS: modificationDate = modificationDate.addDays(age); break; @@ -124,7 +127,8 @@ void FileLogger::addLogMessage(const Log::Msg &msg) QTextStream stream(&m_logFile); stream.setCodec("UTF-8"); - switch (msg.type) { + switch (msg.type) + { case Log::INFO: stream << "(I) "; break; @@ -140,12 +144,14 @@ void FileLogger::addLogMessage(const Log::Msg &msg) stream << QDateTime::fromMSecsSinceEpoch(msg.timestamp).toString(Qt::ISODate) << " - " << msg.message << '\n'; - if (m_backup && (m_logFile.size() >= m_maxSize)) { + if (m_backup && (m_logFile.size() >= m_maxSize)) + { closeLogFile(); int counter = 0; QString backupLogFilename = m_path + ".bak"; - while (QFile::exists(backupLogFilename)) { + while (QFile::exists(backupLogFilename)) + { ++counter; backupLogFilename = m_path + ".bak" + QString::number(counter); } @@ -153,7 +159,8 @@ void FileLogger::addLogMessage(const Log::Msg &msg) QFile::rename(m_path, backupLogFilename); openLogFile(); } - else { + else + { if (!m_flusher.isActive()) m_flusher.start(); } @@ -168,7 +175,8 @@ void FileLogger::flushLog() void FileLogger::openLogFile() { if (!m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text) - || !m_logFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner)) { + || !m_logFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner)) + { m_logFile.close(); LogMsg(tr("An error occurred while trying to open the log file. Logging to file is disabled."), Log::CRITICAL); } diff --git a/src/app/main.cpp b/src/app/main.cpp index bec7cdb85..16581f082 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -92,7 +92,8 @@ void sigNormalHandler(int signum); void sigAbnormalHandler(int signum); #endif // sys_signame[] is only defined in BSD -const char *const sysSigName[] = { +const char *const sysSigName[] = +{ #if defined(Q_OS_WIN) "", "", "SIGINT", "", "SIGILL", "", "SIGABRT_COMPAT", "", "SIGFPE", "", "", "SIGSEGV", "", "", "", "SIGTERM", "", "", "", "", @@ -141,19 +142,23 @@ int main(int argc, char *argv[]) Application::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); #endif - try { + try + { // Create Application auto app = std::make_unique(argc, argv); const QBtCommandLineParameters params = app->commandLineArgs(); - if (!params.unknownParameter.isEmpty()) { + if (!params.unknownParameter.isEmpty()) + { throw CommandLineParameterError(QObject::tr("%1 is an unknown command line parameter.", "--random-parameter is an unknown command line parameter.") .arg(params.unknownParameter)); } #if !defined(Q_OS_WIN) || defined(DISABLE_GUI) - if (params.showVersion) { - if (isOneArg) { + if (params.showVersion) + { + if (isOneArg) + { displayVersion(); return EXIT_SUCCESS; } @@ -161,8 +166,10 @@ int main(int argc, char *argv[]) .arg(QLatin1String("-v (or --version)"))); } #endif - if (params.showHelp) { - if (isOneArg) { + if (params.showHelp) + { + if (isOneArg) + { displayUsage(argv[0]); return EXIT_SUCCESS; } @@ -175,7 +182,8 @@ int main(int argc, char *argv[]) fprintf(stderr, "Couldn't set environment variable...\n"); const bool firstTimeUser = !Preferences::instance()->getAcceptedLegal(); - if (firstTimeUser) { + if (firstTimeUser) + { #ifndef DISABLE_GUI if (!userAgreesWithLegalNotice()) return EXIT_SUCCESS; @@ -195,9 +203,11 @@ int main(int argc, char *argv[]) } // Check if qBittorrent is already running for this user - if (app->isRunning()) { + if (app->isRunning()) + { #if defined(DISABLE_GUI) && !defined(Q_OS_WIN) - if (params.shouldDaemonize) { + if (params.shouldDaemonize) + { throw CommandLineParameterError(QObject::tr("You cannot use %1: qBittorrent is already running for this user.") .arg(QLatin1String("-d (or --daemon)"))); } @@ -242,7 +252,8 @@ int main(int argc, char *argv[]) app->setAttribute(Qt::AA_DontShowIconsInMenus); #endif - if (!firstTimeUser) { + if (!firstTimeUser) + { handleChangedDefaults(DefaultPreferencesMode::Legacy); #ifndef DISABLE_GUI @@ -256,21 +267,26 @@ int main(int argc, char *argv[]) && isatty(fileno(stdout)))) return EXIT_FAILURE; #endif } - else { + else + { handleChangedDefaults(DefaultPreferencesMode::Current); } #if defined(DISABLE_GUI) && !defined(Q_OS_WIN) - if (params.shouldDaemonize) { + if (params.shouldDaemonize) + { app.reset(); // Destroy current application - if (daemon(1, 0) == 0) { + if (daemon(1, 0) == 0) + { app = std::make_unique(argc, argv); - if (app->isRunning()) { + if (app->isRunning()) + { // Another instance had time to start. return EXIT_FAILURE; } } - else { + else + { qCritical("Something went wrong while daemonizing, exiting..."); return EXIT_FAILURE; } @@ -289,7 +305,8 @@ int main(int argc, char *argv[]) return app->exec(params.paramList()); } - catch (const CommandLineParameterError &er) { + catch (const CommandLineParameterError &er) + { displayBadArgMessage(er.messageForUser()); return EXIT_FAILURE; } @@ -300,10 +317,12 @@ void reportToUser(const char *str) { const size_t strLen = strlen(str); #ifndef Q_OS_WIN - if (write(STDERR_FILENO, str, strLen) < static_cast(strLen)) { + if (write(STDERR_FILENO, str, strLen) < static_cast(strLen)) + { const auto dummy = write(STDOUT_FILENO, str, strLen); #else - if (_write(STDERR_FILENO, str, strLen) < static_cast(strLen)) { + if (_write(STDERR_FILENO, str, strLen) < static_cast(strLen)) + { const auto dummy = _write(STDOUT_FILENO, str, strLen); #endif Q_UNUSED(dummy); @@ -405,7 +424,8 @@ bool userAgreesWithLegalNotice() printf("%s", qUtf8Printable(eula)); const char ret = getchar(); // Read pressed key - if ((ret == 'y') || (ret == 'Y')) { + if ((ret == 'y') || (ret == 'Y')) + { // Save the answer pref->setAcceptedLegal(true); return true; @@ -419,7 +439,8 @@ bool userAgreesWithLegalNotice() msgBox.show(); // Need to be shown or to moveToCenter does not work msgBox.move(Utils::Gui::screenCenter(&msgBox)); msgBox.exec(); - if (msgBox.clickedButton() == agreeButton) { + if (msgBox.clickedButton() == agreeButton) + { // Save the answer pref->setAcceptedLegal(true); return true; diff --git a/src/app/qtlocalpeer/qtlocalpeer.cpp b/src/app/qtlocalpeer/qtlocalpeer.cpp index 71843de4f..c7461b0aa 100644 --- a/src/app/qtlocalpeer/qtlocalpeer.cpp +++ b/src/app/qtlocalpeer/qtlocalpeer.cpp @@ -100,7 +100,8 @@ QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId) , id(appId) { QString prefix = id; - if (id.isEmpty()) { + if (id.isEmpty()) + { id = QCoreApplication::applicationFilePath(); #if defined(Q_OS_WIN) id = id.toLower(); @@ -143,7 +144,8 @@ bool QtLocalPeer::isClient() bool res = server->listen(socketName); #if defined(Q_OS_UNIX) // ### Workaround - if (!res && server->serverError() == QAbstractSocket::AddressInUseError) { + if (!res && server->serverError() == QAbstractSocket::AddressInUseError) + { QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName); res = server->listen(socketName); } @@ -161,7 +163,8 @@ bool QtLocalPeer::sendMessage(const QString &message, const int timeout) QLocalSocket socket; bool connOk = false; - for(int i = 0; i < 2; i++) { + for(int i = 0; i < 2; i++) + { // Try twice, in case the other instance is just starting up socket.connectToServer(socketName); connOk = socket.waitForConnected(timeout/2); @@ -182,7 +185,8 @@ bool QtLocalPeer::sendMessage(const QString &message, const int timeout) QDataStream ds(&socket); ds.writeBytes(uMsg.constData(), uMsg.size()); bool res = socket.waitForBytesWritten(timeout); - if (res) { + if (res) + { res &= socket.waitForReadyRead(timeout); // wait for ack if (res) res &= (socket.read(qstrlen(ack)) == ack); @@ -201,8 +205,10 @@ void QtLocalPeer::receiveConnection() if (!socket) return; - while (true) { - if (socket->state() == QLocalSocket::UnconnectedState) { + while (true) + { + if (socket->state() == QLocalSocket::UnconnectedState) + { qWarning("QtLocalPeer: Peer disconnected"); delete socket; return; @@ -216,7 +222,8 @@ void QtLocalPeer::receiveConnection() QByteArray uMsg; quint32 remaining; ds >> remaining; - if (remaining > 65535) { + if (remaining > 65535) + { // drop suspiciously large data delete socket; return; @@ -225,12 +232,14 @@ void QtLocalPeer::receiveConnection() uMsg.resize(remaining); int got = 0; char* uMsgBuf = uMsg.data(); - do { + do + { got = ds.readRawData(uMsgBuf, remaining); remaining -= got; uMsgBuf += got; } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); - if (got < 0) { + if (got < 0) + { qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); delete socket; return; diff --git a/src/app/stacktrace.h b/src/app/stacktrace.h index 78a177f13..5ba3c5d43 100644 --- a/src/app/stacktrace.h +++ b/src/app/stacktrace.h @@ -22,7 +22,8 @@ static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames // retrieve current stack addresses int addrlen = backtrace(addrlist.data(), addrlist.size()); - if (addrlen == 0) { + if (addrlen == 0) + { fprintf(out, " \n"); return; } @@ -38,27 +39,33 @@ static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames int functionNamesFound = 0; // iterate over the returned symbol lines. skip the first, it is the // address of this function. - for (int i = 2; i < addrlen; i++) { + for (int i = 2; i < addrlen; i++) + { char *begin_name = 0, *begin_offset = 0, *end_offset = 0; // find parentheses and +address offset surrounding the mangled name: // ./module(function+0x15c) [0x8048a6d] // fprintf(out, "%s TT\n", symbollist[i]); - for (char *p = symbollist[i]; *p; ++p) { - if (*p == '(') { + for (char *p = symbollist[i]; *p; ++p) + { + if (*p == '(') + { begin_name = p; } - else if (*p == '+') { + else if (*p == '+') + { begin_offset = p; } - else if ((*p == ')') && begin_offset) { + else if ((*p == ')') && begin_offset) + { end_offset = p; break; } } if (begin_name && begin_offset && end_offset - && (begin_name < begin_offset)) { + && (begin_name < begin_offset)) + { *begin_name++ = '\0'; *begin_offset++ = '\0'; *end_offset = '\0'; @@ -70,12 +77,14 @@ static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames int status; char *ret = abi::__cxa_demangle(begin_name, funcname, &funcnamesize, &status); - if (status == 0) { + if (status == 0) + { funcname = ret; // use possibly realloc()-ed string fprintf(out, " %s : %s+%s %s\n", symbollist[i], funcname, begin_offset, ++end_offset); } - else { + else + { // demangling failed. Output function name as a C function with // no arguments. fprintf(out, " %s : %s()+%s %s\n", @@ -83,17 +92,20 @@ static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames } ++functionNamesFound; } - else { + else + { // couldn't parse the line? print the whole line. fprintf(out, " %s\n", symbollist[i]); } } - if (!functionNamesFound) { + if (!functionNamesFound) + { fprintf(out, "There were no function names found in the stack trace\n." "Seems like debug symbols are not installed, and the stack trace is useless.\n"); } - if (functionNamesFound < addrlen - 2) { + if (functionNamesFound < addrlen - 2) + { fprintf(out, "Consider installing debug symbols for packages containing files with empty" " function names (i.e. empty braces \"()\") to make your stack trace more useful\n"); } diff --git a/src/app/stacktrace_win.h b/src/app/stacktrace_win.h index 1d37c4703..a889506f5 100644 --- a/src/app/stacktrace_win.h +++ b/src/app/stacktrace_win.h @@ -54,7 +54,8 @@ void straceWin::demangle(QString& str) int status = 0; size_t outSz = 0; char* demangled_name = abi::__cxa_demangle(inStr, 0, &outSz, &status); - if (status == 0) { + if (status == 0) + { str = QString::fromLocal8Bit(demangled_name); if (outSz > 0) free(demangled_name); @@ -92,7 +93,8 @@ BOOL CALLBACK straceWin::EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVO IMAGEHLP_MODULE64 mod; EnumModulesContext* context = (EnumModulesContext*)UserContext; mod.SizeOfStruct = sizeof(IMAGEHLP_MODULE64); - if(SymGetModuleInfo64(context->hProcess, BaseOfDll, &mod)) { + if(SymGetModuleInfo64(context->hProcess, BaseOfDll, &mod)) + { QString moduleBase = QString::fromLatin1("0x%1").arg(BaseOfDll, 16, 16, QLatin1Char('0')); QString line = QString::fromLatin1("%1 %2 Image: %3") .arg(mod.ModuleName, -25) @@ -101,7 +103,8 @@ BOOL CALLBACK straceWin::EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVO context->stream << line << '\n'; QString pdbName(mod.LoadedPdbName); - if(!pdbName.isEmpty()) { + if(!pdbName.isEmpty()) + { QString line2 = QString::fromLatin1("%1 %2") .arg("", 35) .arg(pdbName); @@ -126,7 +129,8 @@ bool straceWin::makeRelativePath(const QString& dir, QString& file) if (!d.isEmpty() && (d[d.length() - 1] != separator)) d += separator; - if (f.startsWith(d, Qt::CaseInsensitive)) { + if (f.startsWith(d, Qt::CaseInsensitive)) + { f.remove(0, d.length()); file.swap(f); @@ -142,7 +146,8 @@ QString straceWin::getSourcePathAndLineNumber(HANDLE hProcess, DWORD64 addr) line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); DWORD dwDisplacement = 0; - if (SymGetLineFromAddr64(hProcess, addr, &dwDisplacement, &line)) { + if (SymGetLineFromAddr64(hProcess, addr, &dwDisplacement, &line)) + { QString path(line.FileName); #if defined STACKTRACE_WIN_PROJECT_PATH || defined STACKTRACE_WIN_MAKEFILE_PATH @@ -159,7 +164,8 @@ QString straceWin::getSourcePathAndLineNumber(HANDLE hProcess, DWORD64 addr) #endif #ifdef STACKTRACE_WIN_MAKEFILE_PATH - if (!success) { + if (!success) + { QString targetPath(STACKTRACE_WIN_STRING(STACKTRACE_WIN_MAKEFILE_PATH)); makeRelativePath(targetPath, path); } @@ -201,7 +207,8 @@ const QString straceWin::getBacktrace() : //no input : "eax"); #else - _asm { + _asm + { Label: mov [Context.Ebp], ebp; mov [Context.Esp], esp; @@ -269,15 +276,18 @@ const QString straceWin::getBacktrace() int i = 0; - while(StackWalk64(MachineType, hProcess, hThread, &StackFrame, &Context, NULL, NULL, NULL, NULL)) { + while(StackWalk64(MachineType, hProcess, hThread, &StackFrame, &Context, NULL, NULL, NULL, NULL)) + { if(i == 128) break; loadHelpStackFrame(ihsf, StackFrame); - if(StackFrame.AddrPC.Offset != 0) { // Valid frame. + if(StackFrame.AddrPC.Offset != 0) + { // Valid frame. QString fileName("???"); - if(SymGetModuleInfo64(hProcess, ihsf.InstructionOffset, &mod)) { + if(SymGetModuleInfo64(hProcess, ihsf.InstructionOffset, &mod)) + { fileName = QString(mod.ImageName); int slashPos = fileName.lastIndexOf('\\'); if(slashPos != -1) @@ -285,7 +295,8 @@ const QString straceWin::getBacktrace() } QString funcName; QString sourceFile; - if(SymFromAddr(hProcess, ihsf.InstructionOffset, &dwDisplacement, pSymbol)) { + if(SymFromAddr(hProcess, ihsf.InstructionOffset, &dwDisplacement, pSymbol)) + { funcName = QString(pSymbol->Name); #ifdef __MINGW32__ demangle(funcName); @@ -295,7 +306,8 @@ const QString straceWin::getBacktrace() // decrease the query address by one byte to point somewhere in the CALL instruction byte sequence sourceFile = getSourcePathAndLineNumber(hProcess, ihsf.InstructionOffset - 1); } - else { + else + { funcName = QString::fromLatin1("0x%1").arg(ihsf.InstructionOffset, 8, 16, QLatin1Char('0')); } SymSetContext(hProcess, &ihsf, NULL); @@ -325,7 +337,8 @@ const QString straceWin::getBacktrace() logStream << debugLine << '\n'; i++; } - else { + else + { break; // we're at the end. } } diff --git a/src/app/upgrade.cpp b/src/app/upgrade.cpp index e0a1060cc..0c49c2988 100644 --- a/src/app/upgrade.cpp +++ b/src/app/upgrade.cpp @@ -39,7 +39,8 @@ namespace { void exportWebUIHttpsFiles() { - const auto migrate = [](const QString &oldKey, const QString &newKey, const QString &savePath) { + const auto migrate = [](const QString &oldKey, const QString &newKey, const QString &savePath) + { SettingsStorage *settingsStorage {SettingsStorage::instance()}; const QByteArray oldData {settingsStorage->loadValue(oldKey).toByteArray()}; const QString newData {settingsStorage->loadValue(newKey).toString()}; @@ -49,11 +50,13 @@ namespace return; QFile file(savePath); - if (!file.open(QIODevice::WriteOnly)) { + if (!file.open(QIODevice::WriteOnly)) + { LogMsg(errorMsgFormat.arg(savePath, file.errorString()) , Log::WARNING); return; } - if (file.write(oldData) != oldData.size()) { + if (file.write(oldData) != oldData.size()) + { file.close(); Utils::Fs::forceRemove(savePath); LogMsg(errorMsgFormat.arg(savePath, QLatin1String("Write incomplete.")) , Log::WARNING); @@ -92,12 +95,14 @@ void handleChangedDefaults(const DefaultPreferencesMode mode) QVariant current; }; - const QVector changedDefaults { + const QVector changedDefaults + { {QLatin1String {"BitTorrent/Session/QueueingSystemEnabled"}, true, false} }; SettingsStorage *settingsStorage {SettingsStorage::instance()}; - for (auto it = changedDefaults.cbegin(); it != changedDefaults.cend(); ++it) { + for (auto it = changedDefaults.cbegin(); it != changedDefaults.cend(); ++it) + { if (settingsStorage->loadValue(it->name).isNull()) settingsStorage->storeValue(it->name, (mode == DefaultPreferencesMode::Legacy ? it->legacy : it->current)); } diff --git a/src/base/asyncfilestorage.cpp b/src/base/asyncfilestorage.cpp index eccd2b491..3b9f61e7b 100644 --- a/src/base/asyncfilestorage.cpp +++ b/src/base/asyncfilestorage.cpp @@ -38,7 +38,8 @@ AsyncFileStorage::AsyncFileStorage(const QString &storageFolderPath, QObject *pa , m_lockFile(m_storageDir.absoluteFilePath(QStringLiteral("storage.lock"))) { if (!m_storageDir.mkpath(m_storageDir.absolutePath())) - throw AsyncFileStorageError {tr("Could not create directory '%1'.") + throw AsyncFileStorageError + {tr("Could not create directory '%1'.") .arg(m_storageDir.absolutePath())}; // TODO: This folder locking approach does not work for UNIX systems. Implement it. @@ -73,9 +74,11 @@ void AsyncFileStorage::store_impl(const QString &fileName, const QByteArray &dat const QString filePath = m_storageDir.absoluteFilePath(fileName); QSaveFile file(filePath); qDebug() << "AsyncFileStorage: Saving data to" << filePath; - if (file.open(QIODevice::WriteOnly)) { + if (file.open(QIODevice::WriteOnly)) + { file.write(data); - if (!file.commit()) { + if (!file.commit()) + { qDebug() << "AsyncFileStorage: Failed to save data"; emit failed(filePath, file.errorString()); } diff --git a/src/base/bittorrent/bandwidthscheduler.cpp b/src/base/bittorrent/bandwidthscheduler.cpp index a541a2427..bf0f493bc 100644 --- a/src/base/bittorrent/bandwidthscheduler.cpp +++ b/src/base/bittorrent/bandwidthscheduler.cpp @@ -65,13 +65,16 @@ bool BandwidthScheduler::isTimeForAlternative() const const int day = QDate::currentDate().dayOfWeek(); bool alternative = false; - if (start > end) { + if (start > end) + { std::swap(start, end); alternative = true; } - if ((start <= now) && (end >= now)) { - switch (schedulerDays) { + if ((start <= now) && (end >= now)) + { + switch (schedulerDays) + { case EVERY_DAY: alternative = !alternative; break; @@ -96,7 +99,8 @@ void BandwidthScheduler::onTimeout() { const bool alternative = isTimeForAlternative(); - if (alternative != m_lastAlternative) { + if (alternative != m_lastAlternative) + { m_lastAlternative = alternative; emit bandwidthLimitRequested(alternative); } diff --git a/src/base/bittorrent/customstorage.cpp b/src/base/bittorrent/customstorage.cpp index 9157444f4..2673ec43b 100644 --- a/src/base/bittorrent/customstorage.cpp +++ b/src/base/bittorrent/customstorage.cpp @@ -54,7 +54,8 @@ lt::storage_holder CustomDiskIOThread::new_torrent(const lt::storage_params &sto lt::storage_holder storageHolder = m_nativeDiskIO->new_torrent(storageParams, torrent); const QString savePath = Utils::Fs::expandPathAbs(QString::fromStdString(storageParams.path)); - m_storageData[storageHolder] = { + m_storageData[storageHolder] = + { savePath , storageParams.mapped_files ? *storageParams.mapped_files : storageParams.files , storageParams.priorities}; @@ -196,7 +197,8 @@ void CustomDiskIOThread::handleCompleteFiles(lt::storage_index_t storage, const const QDir saveDir {savePath}; const StorageData storageData = m_storageData[storage]; const lt::file_storage &fileStorage = storageData.files; - for (const lt::file_index_t fileIndex : fileStorage.file_range()) { + for (const lt::file_index_t fileIndex : fileStorage.file_range()) + { // ignore files that have priority 0 if ((storageData.filePriorities.end_index() > fileIndex) && (storageData.filePriorities[fileIndex] == lt::dont_download)) continue; @@ -205,10 +207,12 @@ void CustomDiskIOThread::handleCompleteFiles(lt::storage_index_t storage, const if (fileStorage.pad_file_at(fileIndex)) continue; const QString filePath = QString::fromStdString(fileStorage.file_path(fileIndex)); - if (filePath.endsWith(QB_EXT)) { + if (filePath.endsWith(QB_EXT)) + { const QString completeFilePath = filePath.left(filePath.size() - QB_EXT.size()); QFile completeFile {saveDir.absoluteFilePath(completeFilePath)}; - if (completeFile.exists()) { + if (completeFile.exists()) + { QFile incompleteFile {saveDir.absoluteFilePath(filePath)}; incompleteFile.remove(); completeFile.rename(incompleteFile.fileName()); @@ -261,7 +265,8 @@ void CustomStorage::handleCompleteFiles(const QString &savePath) const QDir saveDir {savePath}; const lt::file_storage &fileStorage = files(); - for (const lt::file_index_t fileIndex : fileStorage.file_range()) { + for (const lt::file_index_t fileIndex : fileStorage.file_range()) + { // ignore files that have priority 0 if ((m_filePriorities.end_index() > fileIndex) && (m_filePriorities[fileIndex] == lt::dont_download)) continue; @@ -270,10 +275,12 @@ void CustomStorage::handleCompleteFiles(const QString &savePath) if (fileStorage.pad_file_at(fileIndex)) continue; const QString filePath = QString::fromStdString(fileStorage.file_path(fileIndex)); - if (filePath.endsWith(QB_EXT)) { + if (filePath.endsWith(QB_EXT)) + { const QString completeFilePath = filePath.left(filePath.size() - QB_EXT.size()); QFile completeFile {saveDir.absoluteFilePath(completeFilePath)}; - if (completeFile.exists()) { + if (completeFile.exists()) + { QFile incompleteFile {saveDir.absoluteFilePath(filePath)}; incompleteFile.remove(); completeFile.rename(incompleteFile.fileName()); diff --git a/src/base/bittorrent/downloadpriority.cpp b/src/base/bittorrent/downloadpriority.cpp index 090ed86fb..bf3ad3b79 100644 --- a/src/base/bittorrent/downloadpriority.cpp +++ b/src/base/bittorrent/downloadpriority.cpp @@ -32,7 +32,8 @@ namespace BitTorrent { bool isValidDownloadPriority(const DownloadPriority priority) { - switch (priority) { + switch (priority) + { case DownloadPriority::Ignored: case DownloadPriority::Normal: case DownloadPriority::High: diff --git a/src/base/bittorrent/filterparserthread.cpp b/src/base/bittorrent/filterparserthread.cpp index e5b913c4b..05e2b2719 100644 --- a/src/base/bittorrent/filterparserthread.cpp +++ b/src/base/bittorrent/filterparserthread.cpp @@ -48,8 +48,10 @@ namespace const char *octetStart = str; char *endptr; - for (; *str; ++str) { - if (*str == '.') { + for (; *str; ++str) + { + if (*str == '.') + { const long int extractedNum = strtol(octetStart, &endptr, 10); if ((extractedNum >= 0L) && (extractedNum <= 255L)) m_buf[octetIndex++] = static_cast(extractedNum); @@ -65,7 +67,8 @@ namespace } } - if (str != octetStart) { + if (str != octetStart) + { const long int extractedNum = strtol(octetStart, &endptr, 10); if ((extractedNum >= 0L) && (extractedNum <= 255L)) m_buf[octetIndex] = static_cast(strtol(octetStart, &endptr, 10)); @@ -124,7 +127,8 @@ int FilterParserThread::parseDATFilterFile() QFile file(m_filePath); if (!file.exists()) return ruleCount; - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + { LogMsg(tr("I/O Error: Could not open IP filter file in read mode."), Log::CRITICAL); return ruleCount; } @@ -142,7 +146,8 @@ int FilterParserThread::parseDATFilterFile() LogMsg(msg, Log::CRITICAL); }; - while (true) { + while (true) + { bytesRead = file.read(buffer.data() + offset, BUFFER_SIZE - offset - 1); if (bytesRead < 0) break; @@ -150,12 +155,16 @@ int FilterParserThread::parseDATFilterFile() if ((bytesRead == 0) && (dataSize == 0)) break; - for (start = 0; start < dataSize; ++start) { + for (start = 0; start < dataSize; ++start) + { endOfLine = -1; // The file might have ended without the last line having a newline - if (!((bytesRead == 0) && (dataSize > 0))) { - for (int i = start; i < dataSize; ++i) { - if (buffer[i] == '\n') { + if (!((bytesRead == 0) && (dataSize > 0))) + { + for (int i = start; i < dataSize; ++i) + { + if (buffer[i] == '\n') + { endOfLine = i; // We need to NULL the newline in case the line has only an IP range. // In that case the parser won't work for the end IP, because it ends @@ -165,12 +174,14 @@ int FilterParserThread::parseDATFilterFile() } } } - else { + else + { endOfLine = dataSize; buffer[dataSize] = '\0'; } - if (endOfLine == -1) { + if (endOfLine == -1) + { // read the next chunk from file // but first move(copy) the leftover data to the front of the buffer offset = dataSize - start; @@ -181,7 +192,8 @@ int FilterParserThread::parseDATFilterFile() ++nbLine; if ((buffer[start] == '#') - || ((buffer[start] == '/') && ((start + 1 < dataSize) && (buffer[start + 1] == '/')))) { + || ((buffer[start] == '/') && ((start + 1 < dataSize) && (buffer[start + 1] == '/')))) + { start = endOfLine; continue; } @@ -194,11 +206,13 @@ int FilterParserThread::parseDATFilterFile() findAndNullDelimiter(buffer.data(), ',', firstComma + 1, endOfLine); // Check if there is an access value (apparently not mandatory) - if (firstComma != -1) { + if (firstComma != -1) + { // There is possibly one const long int nbAccess = strtol(buffer.data() + firstComma + 1, nullptr, 10); // Ignoring this rule because access value is too high - if (nbAccess > 127L) { + if (nbAccess > 127L) + { start = endOfLine; continue; } @@ -207,7 +221,8 @@ int FilterParserThread::parseDATFilterFile() // IP Range should be split by a dash const int endOfIPRange = ((firstComma == -1) ? (endOfLine - 1) : (firstComma - 1)); const int delimIP = findAndNullDelimiter(buffer.data(), '-', start, endOfIPRange); - if (delimIP == -1) { + if (delimIP == -1) + { ++parseErrorCount; addLog(tr("IP filter line %1 is malformed.").arg(nbLine)); start = endOfLine; @@ -216,7 +231,8 @@ int FilterParserThread::parseDATFilterFile() lt::address startAddr; int newStart = trim(buffer.data(), start, delimIP - 1); - if (!parseIPAddress(buffer.data() + newStart, startAddr)) { + if (!parseIPAddress(buffer.data() + newStart, startAddr)) + { ++parseErrorCount; addLog(tr("IP filter line %1 is malformed. Start IP of the range is malformed.").arg(nbLine)); start = endOfLine; @@ -225,7 +241,8 @@ int FilterParserThread::parseDATFilterFile() lt::address endAddr; newStart = trim(buffer.data(), delimIP + 1, endOfIPRange); - if (!parseIPAddress(buffer.data() + newStart, endAddr)) { + if (!parseIPAddress(buffer.data() + newStart, endAddr)) + { ++parseErrorCount; addLog(tr("IP filter line %1 is malformed. End IP of the range is malformed.").arg(nbLine)); start = endOfLine; @@ -233,7 +250,8 @@ int FilterParserThread::parseDATFilterFile() } if ((startAddr.is_v4() != endAddr.is_v4()) - || (startAddr.is_v6() != endAddr.is_v6())) { + || (startAddr.is_v6() != endAddr.is_v6())) + { ++parseErrorCount; addLog(tr("IP filter line %1 is malformed. One IP is IPv4 and the other is IPv6!").arg(nbLine)); start = endOfLine; @@ -243,11 +261,13 @@ int FilterParserThread::parseDATFilterFile() start = endOfLine; // Now Add to the filter - try { + try + { m_filter.add_rule(startAddr, endAddr, lt::ip_filter::blocked); ++ruleCount; } - catch (const std::exception &e) { + catch (const std::exception &e) + { ++parseErrorCount; addLog(tr("IP filter exception thrown for line %1. Exception is: %2") .arg(nbLine).arg(QString::fromLocal8Bit(e.what()))); @@ -271,7 +291,8 @@ int FilterParserThread::parseP2PFilterFile() QFile file(m_filePath); if (!file.exists()) return ruleCount; - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + { LogMsg(tr("I/O Error: Could not open IP filter file in read mode."), Log::CRITICAL); return ruleCount; } @@ -289,7 +310,8 @@ int FilterParserThread::parseP2PFilterFile() LogMsg(msg, Log::CRITICAL); }; - while (true) { + while (true) + { bytesRead = file.read(buffer.data() + offset, BUFFER_SIZE - offset - 1); if (bytesRead < 0) break; @@ -297,12 +319,16 @@ int FilterParserThread::parseP2PFilterFile() if ((bytesRead == 0) && (dataSize == 0)) break; - for (start = 0; start < dataSize; ++start) { + for (start = 0; start < dataSize; ++start) + { endOfLine = -1; // The file might have ended without the last line having a newline - if (!((bytesRead == 0) && (dataSize > 0))) { - for (int i = start; i < dataSize; ++i) { - if (buffer[i] == '\n') { + if (!((bytesRead == 0) && (dataSize > 0))) + { + for (int i = start; i < dataSize; ++i) + { + if (buffer[i] == '\n') + { endOfLine = i; // We need to NULL the newline in case the line has only an IP range. // In that case the parser won't work for the end IP, because it ends @@ -312,12 +338,14 @@ int FilterParserThread::parseP2PFilterFile() } } } - else { + else + { endOfLine = dataSize; buffer[dataSize] = '\0'; } - if (endOfLine == -1) { + if (endOfLine == -1) + { // read the next chunk from file // but first move(copy) the leftover data to the front of the buffer offset = dataSize - start; @@ -328,7 +356,8 @@ int FilterParserThread::parseP2PFilterFile() ++nbLine; if ((buffer[start] == '#') - || ((buffer[start] == '/') && ((start + 1 < dataSize) && (buffer[start + 1] == '/')))) { + || ((buffer[start] == '/') && ((start + 1 < dataSize) && (buffer[start + 1] == '/')))) + { start = endOfLine; continue; } @@ -337,7 +366,8 @@ int FilterParserThread::parseP2PFilterFile() // Some organization:1.0.0.0-1.255.255.255 // The "Some organization" part might contain a ':' char itself so we find the last occurrence const int partsDelimiter = findAndNullDelimiter(buffer.data(), ':', start, endOfLine, true); - if (partsDelimiter == -1) { + if (partsDelimiter == -1) + { ++parseErrorCount; addLog(tr("IP filter line %1 is malformed.").arg(nbLine)); start = endOfLine; @@ -346,7 +376,8 @@ int FilterParserThread::parseP2PFilterFile() // IP Range should be split by a dash const int delimIP = findAndNullDelimiter(buffer.data(), '-', partsDelimiter + 1, endOfLine); - if (delimIP == -1) { + if (delimIP == -1) + { ++parseErrorCount; addLog(tr("IP filter line %1 is malformed.").arg(nbLine)); start = endOfLine; @@ -355,7 +386,8 @@ int FilterParserThread::parseP2PFilterFile() lt::address startAddr; int newStart = trim(buffer.data(), partsDelimiter + 1, delimIP - 1); - if (!parseIPAddress(buffer.data() + newStart, startAddr)) { + if (!parseIPAddress(buffer.data() + newStart, startAddr)) + { ++parseErrorCount; addLog(tr("IP filter line %1 is malformed. Start IP of the range is malformed.").arg(nbLine)); start = endOfLine; @@ -364,7 +396,8 @@ int FilterParserThread::parseP2PFilterFile() lt::address endAddr; newStart = trim(buffer.data(), delimIP + 1, endOfLine); - if (!parseIPAddress(buffer.data() + newStart, endAddr)) { + if (!parseIPAddress(buffer.data() + newStart, endAddr)) + { ++parseErrorCount; addLog(tr("IP filter line %1 is malformed. End IP of the range is malformed.").arg(nbLine)); start = endOfLine; @@ -372,7 +405,8 @@ int FilterParserThread::parseP2PFilterFile() } if ((startAddr.is_v4() != endAddr.is_v4()) - || (startAddr.is_v6() != endAddr.is_v6())) { + || (startAddr.is_v6() != endAddr.is_v6())) + { ++parseErrorCount; addLog(tr("IP filter line %1 is malformed. One IP is IPv4 and the other is IPv6!").arg(nbLine)); start = endOfLine; @@ -381,11 +415,13 @@ int FilterParserThread::parseP2PFilterFile() start = endOfLine; - try { + try + { m_filter.add_rule(startAddr, endAddr, lt::ip_filter::blocked); ++ruleCount; } - catch (const std::exception &e) { + catch (const std::exception &e) + { ++parseErrorCount; addLog(tr("IP filter exception thrown for line %1. Exception is: %2") .arg(nbLine).arg(QString::fromLocal8Bit(e.what()))); @@ -407,14 +443,18 @@ int FilterParserThread::getlineInStream(QDataStream &stream, std::string &name, char c; int totalRead = 0; int read; - do { + do + { read = stream.readRawData(&c, 1); totalRead += read; - if (read > 0) { - if (c != delim) { + if (read > 0) + { + if (c != delim) + { name += c; } - else { + else + { // Delim found return totalRead; } @@ -432,7 +472,8 @@ int FilterParserThread::parseP2BFilterFile() QFile file(m_filePath); if (!file.exists()) return ruleCount; - if (!file.open(QIODevice::ReadOnly)) { + if (!file.open(QIODevice::ReadOnly)) + { LogMsg(tr("I/O Error: Could not open IP filter file in read mode."), Log::CRITICAL); return ruleCount; } @@ -443,19 +484,23 @@ int FilterParserThread::parseP2BFilterFile() unsigned char version; if (!stream.readRawData(buf, sizeof(buf)) || memcmp(buf, "\xFF\xFF\xFF\xFFP2B", 7) - || !stream.readRawData(reinterpret_cast(&version), sizeof(version))) { + || !stream.readRawData(reinterpret_cast(&version), sizeof(version))) + { LogMsg(tr("Parsing Error: The filter file is not a valid PeerGuardian P2B file."), Log::CRITICAL); return ruleCount; } - if ((version == 1) || (version == 2)) { + if ((version == 1) || (version == 2)) + { qDebug ("p2b version 1 or 2"); unsigned int start, end; std::string name; - while (getlineInStream(stream, name, '\0') && !m_abort) { + while (getlineInStream(stream, name, '\0') && !m_abort) + { if (!stream.readRawData(reinterpret_cast(&start), sizeof(start)) - || !stream.readRawData(reinterpret_cast(&end), sizeof(end))) { + || !stream.readRawData(reinterpret_cast(&end), sizeof(end))) + { LogMsg(tr("Parsing Error: The filter file is not a valid PeerGuardian P2B file."), Log::CRITICAL); return ruleCount; } @@ -466,26 +511,31 @@ int FilterParserThread::parseP2BFilterFile() const lt::address_v4 first(ntohl(start)); const lt::address_v4 last(ntohl(end)); // Apply to bittorrent session - try { + try + { m_filter.add_rule(first, last, lt::ip_filter::blocked); ++ruleCount; } catch (const std::exception &) {} } } - else if (version == 3) { + else if (version == 3) + { qDebug ("p2b version 3"); unsigned int namecount; - if (!stream.readRawData(reinterpret_cast(&namecount), sizeof(namecount))) { + if (!stream.readRawData(reinterpret_cast(&namecount), sizeof(namecount))) + { LogMsg(tr("Parsing Error: The filter file is not a valid PeerGuardian P2B file."), Log::CRITICAL); return ruleCount; } namecount = ntohl(namecount); // Reading names although, we don't really care about them - for (unsigned int i = 0; i < namecount; ++i) { + for (unsigned int i = 0; i < namecount; ++i) + { std::string name; - if (!getlineInStream(stream, name, '\0')) { + if (!getlineInStream(stream, name, '\0')) + { LogMsg(tr("Parsing Error: The filter file is not a valid PeerGuardian P2B file."), Log::CRITICAL); return ruleCount; } @@ -495,17 +545,20 @@ int FilterParserThread::parseP2BFilterFile() // Reading the ranges unsigned int rangecount; - if (!stream.readRawData(reinterpret_cast(&rangecount), sizeof(rangecount))) { + if (!stream.readRawData(reinterpret_cast(&rangecount), sizeof(rangecount))) + { LogMsg(tr("Parsing Error: The filter file is not a valid PeerGuardian P2B file."), Log::CRITICAL); return ruleCount; } rangecount = ntohl(rangecount); unsigned int name, start, end; - for (unsigned int i = 0; i < rangecount; ++i) { + for (unsigned int i = 0; i < rangecount; ++i) + { if (!stream.readRawData(reinterpret_cast(&name), sizeof(name)) || !stream.readRawData(reinterpret_cast(&start), sizeof(start)) - || !stream.readRawData(reinterpret_cast(&end), sizeof(end))) { + || !stream.readRawData(reinterpret_cast(&end), sizeof(end))) + { LogMsg(tr("Parsing Error: The filter file is not a valid PeerGuardian P2B file."), Log::CRITICAL); return ruleCount; } @@ -516,7 +569,8 @@ int FilterParserThread::parseP2BFilterFile() const lt::address_v4 first(ntohl(start)); const lt::address_v4 last(ntohl(end)); // Apply to bittorrent session - try { + try + { m_filter.add_rule(first, last, lt::ip_filter::blocked); ++ruleCount; } @@ -525,7 +579,8 @@ int FilterParserThread::parseP2BFilterFile() if (m_abort) return ruleCount; } } - else { + else + { LogMsg(tr("Parsing Error: The filter file is not a valid PeerGuardian P2B file."), Log::CRITICAL); } @@ -539,7 +594,8 @@ int FilterParserThread::parseP2BFilterFile() // * PeerGuardian Binary (P2B): http://wiki.phoenixlabs.org/wiki/P2B_Format void FilterParserThread::processFilterFile(const QString &filePath) { - if (isRunning()) { + if (isRunning()) + { // Already parsing a filter, m_abort first m_abort = true; wait(); @@ -561,25 +617,30 @@ void FilterParserThread::run() { qDebug("Processing filter file"); int ruleCount = 0; - if (m_filePath.endsWith(".p2p", Qt::CaseInsensitive)) { + if (m_filePath.endsWith(".p2p", Qt::CaseInsensitive)) + { // PeerGuardian p2p file ruleCount = parseP2PFilterFile(); } - else if (m_filePath.endsWith(".p2b", Qt::CaseInsensitive)) { + else if (m_filePath.endsWith(".p2b", Qt::CaseInsensitive)) + { // PeerGuardian p2b file ruleCount = parseP2BFilterFile(); } - else if (m_filePath.endsWith(".dat", Qt::CaseInsensitive)) { + else if (m_filePath.endsWith(".dat", Qt::CaseInsensitive)) + { // eMule DAT format ruleCount = parseDATFilterFile(); } if (m_abort) return; - try { + try + { emit IPFilterParsed(ruleCount); } - catch (const std::exception &) { + catch (const std::exception &) + { emit IPFilterError(); } @@ -588,17 +649,23 @@ void FilterParserThread::run() int FilterParserThread::findAndNullDelimiter(char *const data, const char delimiter, const int start, const int end, const bool reverse) { - if (!reverse) { - for (int i = start; i <= end; ++i) { - if (data[i] == delimiter) { + if (!reverse) + { + for (int i = start; i <= end; ++i) + { + if (data[i] == delimiter) + { data[i] = '\0'; return i; } } } - else { - for (int i = end; i >= start; --i) { - if (data[i] == delimiter) { + else + { + for (int i = end; i >= start; --i) + { + if (data[i] == delimiter) + { data[i] = '\0'; return i; } @@ -613,17 +680,21 @@ int FilterParserThread::trim(char *const data, const int start, const int end) if (start >= end) return start; int newStart = start; - for (int i = start; i <= end; ++i) { - if (isspace(data[i]) != 0) { + for (int i = start; i <= end; ++i) + { + if (isspace(data[i]) != 0) + { data[i] = '\0'; } - else { + else + { newStart = i; break; } } - for (int i = end; i >= start; --i) { + for (int i = end; i >= start; --i) + { if (isspace(data[i]) != 0) data[i] = '\0'; else diff --git a/src/base/bittorrent/nativesessionextension.cpp b/src/base/bittorrent/nativesessionextension.cpp index dc27e8c1f..451c7364f 100644 --- a/src/base/bittorrent/nativesessionextension.cpp +++ b/src/base/bittorrent/nativesessionextension.cpp @@ -36,7 +36,8 @@ namespace { void handleFastresumeRejectedAlert(const lt::fastresume_rejected_alert *alert) { - if (alert->error.value() == lt::errors::mismatching_file_size) { + if (alert->error.value() == lt::errors::mismatching_file_size) + { alert->handle.unset_flags(lt::torrent_flags::auto_managed); alert->handle.pause(); } @@ -55,7 +56,8 @@ std::shared_ptr NativeSessionExtension::new_torrent(const lt void NativeSessionExtension::on_alert(const lt::alert *alert) { - switch (alert->type()) { + switch (alert->type()) + { case lt::fastresume_rejected_alert::alert_type: handleFastresumeRejectedAlert(static_cast(alert)); break; diff --git a/src/base/bittorrent/peeraddress.cpp b/src/base/bittorrent/peeraddress.cpp index a9a70f0bf..79ba90ee9 100644 --- a/src/base/bittorrent/peeraddress.cpp +++ b/src/base/bittorrent/peeraddress.cpp @@ -36,14 +36,17 @@ PeerAddress PeerAddress::parse(const QString &address) { QVector ipPort; - if (address.startsWith('[') && address.contains("]:")) { // IPv6 + if (address.startsWith('[') && address.contains("]:")) + { // IPv6 ipPort = address.splitRef("]:"); ipPort[0] = ipPort[0].mid(1); // chop '[' } - else if (address.contains(':')) { // IPv4 + else if (address.contains(':')) + { // IPv4 ipPort = address.splitRef(':'); } - else { + else + { return {}; } diff --git a/src/base/bittorrent/peerinfo.cpp b/src/base/bittorrent/peerinfo.cpp index f3eec84d4..3c2bcbc14 100644 --- a/src/base/bittorrent/peerinfo.cpp +++ b/src/base/bittorrent/peerinfo.cpp @@ -208,7 +208,8 @@ qlonglong PeerInfo::totalDownload() const QBitArray PeerInfo::pieces() const { QBitArray result(m_nativeInfo.pieces.size()); - for (int i = 0; i < result.size(); ++i) { + for (int i = 0; i < result.size(); ++i) + { if (m_nativeInfo.pieces[lt::piece_index_t {i}]) result.setBit(i, true); } @@ -233,8 +234,10 @@ void PeerInfo::calcRelevance(const TorrentHandle *torrent) int localMissing = 0; int remoteHaves = 0; - for (int i = 0; i < allPieces.size(); ++i) { - if (!allPieces[i]) { + for (int i = 0; i < allPieces.size(); ++i) + { + if (!allPieces[i]) + { ++localMissing; if (peerPieces[i]) ++remoteHaves; @@ -254,14 +257,17 @@ qreal PeerInfo::relevance() const void PeerInfo::determineFlags() { - if (isInteresting()) { + if (isInteresting()) + { // d = Your client wants to download, but peer doesn't want to send (interested and choked) - if (isRemoteChocked()) { + if (isRemoteChocked()) + { m_flags += "d "; m_flagsDescription += ("d = " + tr("Interested(local) and Choked(peer)") + '\n'); } - else { + else + { // D = Currently downloading (interested and not choked) m_flags += "D "; m_flagsDescription += ("D = " @@ -269,14 +275,17 @@ void PeerInfo::determineFlags() } } - if (isRemoteInterested()) { + if (isRemoteInterested()) + { // u = Peer wants your client to upload, but your client doesn't want to (interested and choked) - if (isChocked()) { + if (isChocked()) + { m_flags += "u "; m_flagsDescription += ("u = " + tr("interested(peer) and choked(local)") + '\n'); } - else { + else + { // U = Currently uploading (interested and not choked) m_flags += "U "; m_flagsDescription += ("U = " @@ -285,69 +294,80 @@ void PeerInfo::determineFlags() } // O = Optimistic unchoke - if (optimisticUnchoke()) { + if (optimisticUnchoke()) + { m_flags += "O "; m_flagsDescription += ("O = " + tr("optimistic unchoke") + '\n'); } // S = Peer is snubbed - if (isSnubbed()) { + if (isSnubbed()) + { m_flags += "S "; m_flagsDescription += ("S = " + tr("peer snubbed") + '\n'); } // I = Peer is an incoming connection - if (!isLocalConnection()) { + if (!isLocalConnection()) + { m_flags += "I "; m_flagsDescription += ("I = " + tr("incoming connection") + '\n'); } // K = Peer is unchoking your client, but your client is not interested - if (!isRemoteChocked() && !isInteresting()) { + if (!isRemoteChocked() && !isInteresting()) + { m_flags += "K "; m_flagsDescription += ("K = " + tr("not interested(local) and unchoked(peer)") + '\n'); } // ? = Your client unchoked the peer but the peer is not interested - if (!isChocked() && !isRemoteInterested()) { + if (!isChocked() && !isRemoteInterested()) + { m_flags += "? "; m_flagsDescription += ("? = " + tr("not interested(peer) and unchoked(local)") + '\n'); } // X = Peer was included in peerlists obtained through Peer Exchange (PEX) - if (fromPeX()) { + if (fromPeX()) + { m_flags += "X "; m_flagsDescription += ("X = " + tr("peer from PEX") + '\n'); } // H = Peer was obtained through DHT - if (fromDHT()) { + if (fromDHT()) + { m_flags += "H "; m_flagsDescription += ("H = " + tr("peer from DHT") + '\n'); } // E = Peer is using Protocol Encryption (all traffic) - if (isRC4Encrypted()) { + if (isRC4Encrypted()) + { m_flags += "E "; m_flagsDescription += ("E = " + tr("encrypted traffic") + '\n'); } // e = Peer is using Protocol Encryption (handshake) - if (isPlaintextEncrypted()) { + if (isPlaintextEncrypted()) + { m_flags += "e "; m_flagsDescription += ("e = " + tr("encrypted handshake") + '\n'); } // P = Peer is using uTorrent uTP - if (useUTPSocket()) { + if (useUTPSocket()) + { m_flags += "P "; m_flagsDescription += ("P = " + QString::fromUtf8(C_UTP) + '\n'); } // L = Peer is local - if (fromLSD()) { + if (fromLSD()) + { m_flags += "L "; m_flagsDescription += ("L = " + tr("peer from LSD") + '\n'); } diff --git a/src/base/bittorrent/portforwarderimpl.cpp b/src/base/bittorrent/portforwarderimpl.cpp index d8da2b1e8..4ac399d0e 100644 --- a/src/base/bittorrent/portforwarderimpl.cpp +++ b/src/base/bittorrent/portforwarderimpl.cpp @@ -58,7 +58,8 @@ bool PortForwarderImpl::isEnabled() const void PortForwarderImpl::setEnabled(const bool enabled) { - if (m_active != enabled) { + if (m_active != enabled) + { if (enabled) start(); else @@ -71,7 +72,8 @@ void PortForwarderImpl::setEnabled(const bool enabled) void PortForwarderImpl::addPort(const quint16 port) { - if (!m_mappedPorts.contains(port)) { + if (!m_mappedPorts.contains(port)) + { m_mappedPorts.insert(port, {}); if (isEnabled()) m_mappedPorts[port] = {m_provider->add_port_mapping(lt::session::tcp, port, port)}; @@ -80,8 +82,10 @@ void PortForwarderImpl::addPort(const quint16 port) void PortForwarderImpl::deletePort(const quint16 port) { - if (m_mappedPorts.contains(port)) { - if (isEnabled()) { + if (m_mappedPorts.contains(port)) + { + if (isEnabled()) + { for (const lt::port_mapping_t &portMapping : m_mappedPorts[port]) m_provider->delete_port_mapping(portMapping); } @@ -96,7 +100,8 @@ void PortForwarderImpl::start() settingsPack.set_bool(lt::settings_pack::enable_upnp, true); settingsPack.set_bool(lt::settings_pack::enable_natpmp, true); m_provider->apply_settings(settingsPack); - for (auto i = m_mappedPorts.begin(); i != m_mappedPorts.end(); ++i) { + for (auto i = m_mappedPorts.begin(); i != m_mappedPorts.end(); ++i) + { // quint16 port = i.key(); i.value() = {m_provider->add_port_mapping(lt::session::tcp, i.key(), i.key())}; } diff --git a/src/base/bittorrent/resumedatasavingmanager.cpp b/src/base/bittorrent/resumedatasavingmanager.cpp index 17784c5ad..461900783 100644 --- a/src/base/bittorrent/resumedatasavingmanager.cpp +++ b/src/base/bittorrent/resumedatasavingmanager.cpp @@ -48,7 +48,8 @@ void ResumeDataSavingManager::save(const QString &filename, const QByteArray &da const QString filepath = m_resumeDataDir.absoluteFilePath(filename); QSaveFile file {filepath}; - if (!file.open(QIODevice::WriteOnly) || (file.write(data) != data.size()) || !file.commit()) { + if (!file.open(QIODevice::WriteOnly) || (file.write(data) != data.size()) || !file.commit()) + { LogMsg(tr("Couldn't save data to '%1'. Error: %2") .arg(filepath, file.errorString()), Log::CRITICAL); } @@ -59,14 +60,16 @@ void ResumeDataSavingManager::save(const QString &filename, const std::shared_pt const QString filepath = m_resumeDataDir.absoluteFilePath(filename); QSaveFile file {filepath}; - if (!file.open(QIODevice::WriteOnly)) { + if (!file.open(QIODevice::WriteOnly)) + { LogMsg(tr("Couldn't save data to '%1'. Error: %2") .arg(filepath, file.errorString()), Log::CRITICAL); return; } lt::bencode(Utils::IO::FileDeviceOutputIterator {file}, *data); - if ((file.error() != QFileDevice::NoError) || !file.commit()) { + if ((file.error() != QFileDevice::NoError) || !file.commit()) + { LogMsg(tr("Couldn't save data to '%1'. Error: %2") .arg(filepath, file.errorString()), Log::CRITICAL); } diff --git a/src/base/bittorrent/session.cpp b/src/base/bittorrent/session.cpp index 7d00eef32..81c61df5d 100644 --- a/src/base/bittorrent/session.cpp +++ b/src/base/bittorrent/session.cpp @@ -115,40 +115,48 @@ namespace void torrentQueuePositionUp(const lt::torrent_handle &handle) { - try { + try + { handle.queue_position_up(); } - catch (const std::exception &exc) { + catch (const std::exception &exc) + { qDebug() << Q_FUNC_INFO << " fails: " << exc.what(); } } void torrentQueuePositionDown(const lt::torrent_handle &handle) { - try { + try + { handle.queue_position_down(); } - catch (const std::exception &exc) { + catch (const std::exception &exc) + { qDebug() << Q_FUNC_INFO << " fails: " << exc.what(); } } void torrentQueuePositionTop(const lt::torrent_handle &handle) { - try { + try + { handle.queue_position_top(); } - catch (const std::exception &exc) { + catch (const std::exception &exc) + { qDebug() << Q_FUNC_INFO << " fails: " << exc.what(); } } void torrentQueuePositionBottom(const lt::torrent_handle &handle) { - try { + try + { handle.queue_position_bottom(); } - catch (const std::exception &exc) { + catch (const std::exception &exc) + { qDebug() << Q_FUNC_INFO << " fails: " << exc.what(); } } @@ -190,9 +198,11 @@ namespace { QStringMap expanded = categories; - for (auto i = categories.cbegin(); i != categories.cend(); ++i) { + for (auto i = categories.cbegin(); i != categories.cend(); ++i) + { const QString &category = i.key(); - for (const QString &subcat : asConst(Session::expandCategory(category))) { + for (const QString &subcat : asConst(Session::expandCategory(category))) + { if (!expanded.contains(subcat)) expanded[subcat] = ""; } @@ -238,10 +248,12 @@ namespace QString toString(const lt::address &address) { - try { + try + { return QString::fromLatin1(address.to_string().c_str()); } - catch (const std::exception &) { + catch (const std::exception &) + { // suppress conversion error } return {}; @@ -301,7 +313,8 @@ namespace NET_LUID luid {}; const LONG res = ::ConvertInterfaceNameToLuidW(name.toStdWString().c_str(), &luid); - if (res == 0) { + if (res == 0) + { GUID guid; if (::ConvertInterfaceLuidToGuid(&luid, &guid) == 0) return QUuid(guid).toString().toUpper(); @@ -468,7 +481,8 @@ Session::Session(QObject *parent) enableBandwidthScheduler(); m_categories = map_cast(m_storedCategories); - if (isSubcategoriesEnabled()) { + if (isSubcategoriesEnabled()) + { // if subcategories support changed manually m_categories = expandCategories(m_categories); m_storedCategories = map_cast(m_categories); @@ -500,7 +514,8 @@ Session::Session(QObject *parent) // Regular saving of fastresume data connect(m_resumeDataTimer, &QTimer::timeout, this, [this]() { generateResumeData(); }); const int saveInterval = saveResumeDataInterval(); - if (saveInterval > 0) { + if (saveInterval > 0) + { m_resumeDataTimer->setInterval(saveInterval * 60 * 1000); m_resumeDataTimer->start(); } @@ -518,7 +533,8 @@ bool Session::isDHTEnabled() const void Session::setDHTEnabled(bool enabled) { - if (enabled != m_isDHTEnabled) { + if (enabled != m_isDHTEnabled) + { m_isDHTEnabled = enabled; configureDeferred(); LogMsg(tr("DHT support [%1]").arg(enabled ? tr("ON") : tr("OFF")), Log::INFO); @@ -532,7 +548,8 @@ bool Session::isLSDEnabled() const void Session::setLSDEnabled(const bool enabled) { - if (enabled != m_isLSDEnabled) { + if (enabled != m_isLSDEnabled) + { m_isLSDEnabled = enabled; configureDeferred(); LogMsg(tr("Local Peer Discovery support [%1]").arg(enabled ? tr("ON") : tr("OFF")) @@ -559,7 +576,8 @@ bool Session::isTempPathEnabled() const void Session::setTempPathEnabled(const bool enabled) { - if (enabled != isTempPathEnabled()) { + if (enabled != isTempPathEnabled()) + { m_isTempPathEnabled = enabled; for (TorrentHandleImpl *const torrent : asConst(m_torrents)) torrent->handleTempPathChanged(); @@ -573,7 +591,8 @@ bool Session::isAppendExtensionEnabled() const void Session::setAppendExtensionEnabled(const bool enabled) { - if (isAppendExtensionEnabled() != enabled) { + if (isAppendExtensionEnabled() != enabled) + { // append or remove .!qB extension for incomplete files for (TorrentHandleImpl *const torrent : asConst(m_torrents)) torrent->handleAppendExtensionToggled(); @@ -589,7 +608,8 @@ int Session::refreshInterval() const void Session::setRefreshInterval(const int value) { - if (value != refreshInterval()) { + if (value != refreshInterval()) + { m_refreshInterval = value; } } @@ -651,7 +671,8 @@ QString Session::torrentTempPath(const TorrentInfo &torrentInfo) const bool Session::isValidCategoryName(const QString &name) { static const QRegularExpression re(R"(^([^\\\/]|[^\\\/]([^\\\/]|\/(?=[^\/]))*[^\\\/])$)"); - if (!name.isEmpty() && (name.indexOf(re) != 0)) { + if (!name.isEmpty() && (name.indexOf(re) != 0)) + { qDebug() << "Incorrect category name:" << name; return false; } @@ -666,7 +687,8 @@ QStringList Session::expandCategory(const QString &category) return result; int index = 0; - while ((index = category.indexOf('/', index)) >= 0) { + while ((index = category.indexOf('/', index)) >= 0) + { result << category.left(index); ++index; } @@ -701,9 +723,12 @@ bool Session::addCategory(const QString &name, const QString &savePath) if (!isValidCategoryName(name) || m_categories.contains(name)) return false; - if (isSubcategoriesEnabled()) { - for (const QString &parent : asConst(expandCategory(name))) { - if ((parent != name) && !m_categories.contains(parent)) { + if (isSubcategoriesEnabled()) + { + for (const QString &parent : asConst(expandCategory(name))) + { + if ((parent != name) && !m_categories.contains(parent)) + { m_categories[parent] = ""; emit categoryAdded(parent); } @@ -724,12 +749,14 @@ bool Session::editCategory(const QString &name, const QString &savePath) m_categories[name] = savePath; m_storedCategories = map_cast(m_categories); - if (isDisableAutoTMMWhenCategorySavePathChanged()) { + if (isDisableAutoTMMWhenCategorySavePathChanged()) + { for (TorrentHandleImpl *const torrent : asConst(m_torrents)) if (torrent->category() == name) torrent->setAutoTMMEnabled(false); } - else { + else + { for (TorrentHandleImpl *const torrent : asConst(m_torrents)) if (torrent->category() == name) torrent->handleCategorySavePathChanged(); @@ -746,12 +773,14 @@ bool Session::removeCategory(const QString &name) // remove stored category and its subcategories if exist bool result = false; - if (isSubcategoriesEnabled()) { + if (isSubcategoriesEnabled()) + { // remove subcategories const QString test = name + '/'; Algorithm::removeIf(m_categories, [this, &test, &result](const QString &category, const QString &) { - if (category.startsWith(test)) { + if (category.startsWith(test)) + { result = true; emit categoryRemoved(category); return true; @@ -762,7 +791,8 @@ bool Session::removeCategory(const QString &name) result = (m_categories.remove(name) > 0) || result; - if (result) { + if (result) + { // update stored categories m_storedCategories = map_cast(m_categories); emit categoryRemoved(name); @@ -780,13 +810,15 @@ void Session::setSubcategoriesEnabled(const bool value) { if (isSubcategoriesEnabled() == value) return; - if (value) { + if (value) + { // expand categories to include all parent categories m_categories = expandCategories(m_categories); // update stored categories m_storedCategories = map_cast(m_categories); } - else { + else + { // reload categories m_categories = map_cast(m_storedCategories); } @@ -815,7 +847,8 @@ bool Session::addTag(const QString &tag) if (!isValidTag(tag)) return false; - if (!hasTag(tag)) { + if (!hasTag(tag)) + { m_tags.insert(tag); m_storedTags = m_tags.values(); emit tagAdded(tag); @@ -826,7 +859,8 @@ bool Session::addTag(const QString &tag) bool Session::removeTag(const QString &tag) { - if (m_tags.remove(tag)) { + if (m_tags.remove(tag)) + { for (TorrentHandleImpl *const torrent : asConst(m_torrents)) torrent->removeTag(tag); m_storedTags = m_tags.values(); @@ -913,7 +947,8 @@ void Session::setGlobalMaxRatio(qreal ratio) if (ratio < 0) ratio = -1.; - if (ratio != globalMaxRatio()) { + if (ratio != globalMaxRatio()) + { m_globalMaxRatio = ratio; updateSeedingLimitTimer(); } @@ -929,7 +964,8 @@ void Session::setGlobalMaxSeedingMinutes(int minutes) if (minutes < 0) minutes = -1; - if (minutes != globalMaxSeedingMinutes()) { + if (minutes != globalMaxSeedingMinutes()) + { m_globalMaxSeedingMinutes = minutes; updateSeedingLimitTimer(); } @@ -978,7 +1014,8 @@ Session *Session::instance() void Session::adjustLimits() { - if (isQueueingSystemEnabled()) { + if (isQueueingSystemEnabled()) + { lt::settings_pack settingsPack = m_nativeSession->get_settings(); adjustLimits(settingsPack); m_nativeSession->apply_settings(settingsPack); @@ -1011,7 +1048,8 @@ void Session::configureComponents() configurePeerClasses(); - if (!m_IPFilteringConfigured) { + if (!m_IPFilteringConfigured) + { if (isIPFilteringEnabled()) enableIPFilter(); else @@ -1097,7 +1135,8 @@ void Session::initializeNativeSession() void Session::processBannedIPs(lt::ip_filter &filter) { // First, import current filter - for (const QString &ip : asConst(m_bannedIPs.value())) { + for (const QString &ip : asConst(m_bannedIPs.value())) + { lt::error_code ec; const lt::address addr = lt::make_address(ip.toLatin1().constData(), ec); Q_ASSERT(!ec); @@ -1215,7 +1254,8 @@ void Session::loadLTSettings(lt::settings_pack &settingsPack) // The most secure, rc4 only so that all streams are encrypted settingsPack.set_int(lt::settings_pack::allowed_enc_level, lt::settings_pack::pe_rc4); settingsPack.set_bool(lt::settings_pack::prefer_rc4, true); - switch (encryption()) { + switch (encryption()) + { case 0: // Enabled settingsPack.set_int(lt::settings_pack::out_enc_policy, lt::settings_pack::pe_enabled); settingsPack.set_int(lt::settings_pack::in_enc_policy, lt::settings_pack::pe_enabled); @@ -1233,7 +1273,8 @@ void Session::loadLTSettings(lt::settings_pack &settingsPack) const auto proxyManager = Net::ProxyConfigurationManager::instance(); const Net::ProxyConfiguration proxyConfig = proxyManager->proxyConfiguration(); - switch (proxyConfig.type) { + switch (proxyConfig.type) + { case Net::ProxyType::HTTP: settingsPack.set_int(lt::settings_pack::proxy_type, lt::settings_pack::http); break; @@ -1254,11 +1295,13 @@ void Session::loadLTSettings(lt::settings_pack &settingsPack) settingsPack.set_int(lt::settings_pack::proxy_type, lt::settings_pack::none); } - if (proxyConfig.type != Net::ProxyType::None) { + if (proxyConfig.type != Net::ProxyType::None) + { settingsPack.set_str(lt::settings_pack::proxy_hostname, proxyConfig.ip.toStdString()); settingsPack.set_int(lt::settings_pack::proxy_port, proxyConfig.port); - if (proxyManager->isAuthenticationRequired()) { + if (proxyManager->isAuthenticationRequired()) + { settingsPack.set_str(lt::settings_pack::proxy_username, proxyConfig.username.toStdString()); settingsPack.set_str(lt::settings_pack::proxy_password, proxyConfig.password.toStdString()); } @@ -1312,7 +1355,8 @@ void Session::loadLTSettings(lt::settings_pack &settingsPack) settingsPack.set_bool(lt::settings_pack::anonymous_mode, isAnonymousModeEnabled()); // Queueing System - if (isQueueingSystemEnabled()) { + if (isQueueingSystemEnabled()) + { adjustLimits(settingsPack); settingsPack.set_int(lt::settings_pack::active_seeds, maxActiveUploads()); @@ -1321,7 +1365,8 @@ void Session::loadLTSettings(lt::settings_pack &settingsPack) settingsPack.set_int(lt::settings_pack::inactive_up_rate, uploadRateForSlowTorrents() * 1024); // KiB to Bytes settingsPack.set_int(lt::settings_pack::auto_manage_startup, slowTorrentsInactivityTimer()); } - else { + else + { settingsPack.set_int(lt::settings_pack::active_downloads, -1); settingsPack.set_int(lt::settings_pack::active_seeds, -1); settingsPack.set_int(lt::settings_pack::active_limit, -1); @@ -1354,7 +1399,8 @@ void Session::loadLTSettings(lt::settings_pack &settingsPack) // * Global max upload slots settingsPack.set_int(lt::settings_pack::unchoke_slots_limit, maxUploads()); // uTP - switch (btProtocol()) { + switch (btProtocol()) + { case BTProtocol::Both: default: settingsPack.set_bool(lt::settings_pack::enable_incoming_tcp, true); @@ -1378,7 +1424,8 @@ void Session::loadLTSettings(lt::settings_pack &settingsPack) break; } - switch (utpMixedMode()) { + switch (utpMixedMode()) + { case MixedModeAlgorithm::TCP: default: settingsPack.set_int(lt::settings_pack::mixed_mode_algorithm, lt::settings_pack::prefer_tcp); @@ -1403,7 +1450,8 @@ void Session::loadLTSettings(lt::settings_pack &settingsPack) settingsPack.set_str(lt::settings_pack::dht_bootstrap_nodes, "dht.libtorrent.org:25401,router.bittorrent.com:6881,router.utorrent.com:6881,dht.transmissionbt.com:6881,dht.aelitis.com:6881"); settingsPack.set_bool(lt::settings_pack::enable_lsd, isLSDEnabled()); - switch (chokingAlgorithm()) { + switch (chokingAlgorithm()) + { case ChokingAlgorithm::FixedSlots: default: settingsPack.set_int(lt::settings_pack::choking_algorithm, lt::settings_pack::fixed_slots_choker); @@ -1413,7 +1461,8 @@ void Session::loadLTSettings(lt::settings_pack &settingsPack) break; } - switch (seedChokingAlgorithm()) { + switch (seedChokingAlgorithm()) + { case SeedChokingAlgorithm::RoundRobin: settingsPack.set_int(lt::settings_pack::seed_choking_algorithm, lt::settings_pack::round_robin); break; @@ -1440,9 +1489,11 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack) QStringList outgoingInterfaces; const QString portString = ':' + QString::number(port); - for (const QString &ip : asConst(getListeningIPs())) { + for (const QString &ip : asConst(getListeningIPs())) + { const QHostAddress addr {ip}; - if (!addr.isNull()) { + if (!addr.isNull()) + { const QString ip = ((addr.protocol() == QAbstractSocket::IPv6Protocol) ? ('[' + Utils::Net::canonicalIPv6Addr(addr).toString() + ']') : addr.toString()); @@ -1451,18 +1502,21 @@ void Session::configureNetworkInterfaces(lt::settings_pack &settingsPack) if ((ip != "0.0.0.0") && (ip != "[::]")) outgoingInterfaces << ip; } - else { + else + { // ip holds an interface name #ifdef Q_OS_WIN // On Vista+ versions and after Qt 5.5 QNetworkInterface::name() returns // the interface's LUID and not the GUID. // Libtorrent expects GUIDs for the 'listen_interfaces' setting. const QString guid = convertIfaceNameToGuid(ip); - if (!guid.isEmpty()) { + if (!guid.isEmpty()) + { endpoints << (guid + portString); outgoingInterfaces << guid; } - else { + else + { LogMsg(tr("Could not get GUID of network interface: %1").arg(ip) , Log::WARNING); // Since we can't get the GUID, we'll pass the interface name instead. // Otherwise an empty string will be passed to outgoing_interface which will cause IP leak. @@ -1498,14 +1552,16 @@ void Session::configurePeerClasses() // IPv6 may not be available on OS and the parsing // would result in an exception -> abnormal program termination // Affects Windows XP - try { + try + { f.add_rule(lt::address_v6::any() , lt::make_address("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") , 1 << static_cast>(lt::session::global_peer_class_id)); } catch (const std::exception &) {} - if (ignoreLimitsOnLAN()) { + if (ignoreLimitsOnLAN()) + { // local networks f.add_rule(lt::make_address("10.0.0.0") , lt::make_address("10.255.255.255") @@ -1528,7 +1584,8 @@ void Session::configurePeerClasses() // IPv6 may not be available on OS and the parsing // would result in an exception -> abnormal program termination // Affects Windows XP - try { + try + { // link local f.add_rule(lt::make_address("fe80::") , lt::make_address("febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff") @@ -1550,7 +1607,8 @@ void Session::configurePeerClasses() peerClassTypeFilter.add(lt::peer_class_type_filter::tcp_socket, lt::session::tcp_peer_class_id); peerClassTypeFilter.add(lt::peer_class_type_filter::ssl_tcp_socket, lt::session::tcp_peer_class_id); peerClassTypeFilter.add(lt::peer_class_type_filter::i2p_socket, lt::session::tcp_peer_class_id); - if (!isUTPRateLimited()) { + if (!isUTPRateLimited()) + { peerClassTypeFilter.disallow(lt::peer_class_type_filter::utp_socket , lt::session::global_peer_class_id); peerClassTypeFilter.disallow(lt::peer_class_type_filter::ssl_utp_socket @@ -1561,20 +1619,23 @@ void Session::configurePeerClasses() void Session::enableTracker(const bool enable) { - if (enable) { + if (enable) + { if (!m_tracker) m_tracker = new Tracker(this); m_tracker->start(); } - else { + else + { delete m_tracker; } } void Session::enableBandwidthScheduler() { - if (!m_bwScheduler) { + if (!m_bwScheduler) + { m_bwScheduler = new BandwidthScheduler(this); connect(m_bwScheduler.data(), &BandwidthScheduler::bandwidthLimitRequested , this, &Session::setAltGlobalSpeedLimitEnabled); @@ -1587,7 +1648,8 @@ void Session::populateAdditionalTrackers() m_additionalTrackerList.clear(); const QString trackers = additionalTrackers(); - for (QStringRef tracker : asConst(trackers.splitRef('\n'))) { + for (QStringRef tracker : asConst(trackers.splitRef('\n'))) + { tracker = tracker.trimmed(); if (!tracker.isEmpty()) m_additionalTrackerList << tracker.toString(); @@ -1601,32 +1663,41 @@ void Session::processShareLimits() // We shouldn't iterate over `m_torrents` in the loop below // since `deleteTorrent()` modifies it indirectly const QHash torrents {m_torrents}; - for (TorrentHandleImpl *const torrent : torrents) { - if (torrent->isSeed() && !torrent->isForced()) { - if (torrent->ratioLimit() != TorrentHandle::NO_RATIO_LIMIT) { + for (TorrentHandleImpl *const torrent : torrents) + { + if (torrent->isSeed() && !torrent->isForced()) + { + if (torrent->ratioLimit() != TorrentHandle::NO_RATIO_LIMIT) + { const qreal ratio = torrent->realRatio(); qreal ratioLimit = torrent->ratioLimit(); if (ratioLimit == TorrentHandle::USE_GLOBAL_RATIO) // If Global Max Ratio is really set... ratioLimit = globalMaxRatio(); - if (ratioLimit >= 0) { + if (ratioLimit >= 0) + { qDebug("Ratio: %f (limit: %f)", ratio, ratioLimit); - if ((ratio <= TorrentHandle::MAX_RATIO) && (ratio >= ratioLimit)) { - if (m_maxRatioAction == Remove) { + if ((ratio <= TorrentHandle::MAX_RATIO) && (ratio >= ratioLimit)) + { + if (m_maxRatioAction == Remove) + { LogMsg(tr("'%1' reached the maximum ratio you set. Removed.").arg(torrent->name())); deleteTorrent(torrent->hash()); } - else if (m_maxRatioAction == DeleteFiles) { + else if (m_maxRatioAction == DeleteFiles) + { LogMsg(tr("'%1' reached the maximum ratio you set. Removed torrent and its files.").arg(torrent->name())); deleteTorrent(torrent->hash(), TorrentAndFiles); } - else if ((m_maxRatioAction == Pause) && !torrent->isPaused()) { + else if ((m_maxRatioAction == Pause) && !torrent->isPaused()) + { torrent->pause(); LogMsg(tr("'%1' reached the maximum ratio you set. Paused.").arg(torrent->name())); } - else if ((m_maxRatioAction == EnableSuperSeeding) && !torrent->isPaused() && !torrent->superSeeding()) { + else if ((m_maxRatioAction == EnableSuperSeeding) && !torrent->isPaused() && !torrent->superSeeding()) + { torrent->setSuperSeeding(true); LogMsg(tr("'%1' reached the maximum ratio you set. Enabled super seeding for it.").arg(torrent->name())); } @@ -1635,29 +1706,37 @@ void Session::processShareLimits() } } - if (torrent->seedingTimeLimit() != TorrentHandle::NO_SEEDING_TIME_LIMIT) { + if (torrent->seedingTimeLimit() != TorrentHandle::NO_SEEDING_TIME_LIMIT) + { const qlonglong seedingTimeInMinutes = torrent->seedingTime() / 60; int seedingTimeLimit = torrent->seedingTimeLimit(); - if (seedingTimeLimit == TorrentHandle::USE_GLOBAL_SEEDING_TIME) { + if (seedingTimeLimit == TorrentHandle::USE_GLOBAL_SEEDING_TIME) + { // If Global Seeding Time Limit is really set... seedingTimeLimit = globalMaxSeedingMinutes(); } - if (seedingTimeLimit >= 0) { - if ((seedingTimeInMinutes <= TorrentHandle::MAX_SEEDING_TIME) && (seedingTimeInMinutes >= seedingTimeLimit)) { - if (m_maxRatioAction == Remove) { + if (seedingTimeLimit >= 0) + { + if ((seedingTimeInMinutes <= TorrentHandle::MAX_SEEDING_TIME) && (seedingTimeInMinutes >= seedingTimeLimit)) + { + if (m_maxRatioAction == Remove) + { LogMsg(tr("'%1' reached the maximum seeding time you set. Removed.").arg(torrent->name())); deleteTorrent(torrent->hash()); } - else if (m_maxRatioAction == DeleteFiles) { + else if (m_maxRatioAction == DeleteFiles) + { LogMsg(tr("'%1' reached the maximum seeding time you set. Removed torrent and its files.").arg(torrent->name())); deleteTorrent(torrent->hash(), TorrentAndFiles); } - else if ((m_maxRatioAction == Pause) && !torrent->isPaused()) { + else if ((m_maxRatioAction == Pause) && !torrent->isPaused()) + { torrent->pause(); LogMsg(tr("'%1' reached the maximum seeding time you set. Paused.").arg(torrent->name())); } - else if ((m_maxRatioAction == EnableSuperSeeding) && !torrent->isPaused() && !torrent->superSeeding()) { + else if ((m_maxRatioAction == EnableSuperSeeding) && !torrent->isPaused() && !torrent->superSeeding()) + { torrent->setSuperSeeding(true); LogMsg(tr("'%1' reached the maximum seeding time you set. Enabled super seeding for it.").arg(torrent->name())); } @@ -1671,7 +1750,8 @@ void Session::processShareLimits() // Add to BitTorrent session the downloaded torrent file void Session::handleDownloadFinished(const Net::DownloadResult &result) { - switch (result.status) { + switch (result.status) + { case Net::DownloadStatus::Success: emit downloadFromUrlFinished(result.url); addTorrent(TorrentInfo::load(result.data), m_downloadedTorrents.take(result.url)); @@ -1718,7 +1798,8 @@ bool Session::hasRunningSeed() const void Session::banIP(const QString &ip) { QStringList bannedIPs = m_bannedIPs; - if (!bannedIPs.contains(ip)) { + if (!bannedIPs.contains(ip)) + { lt::ip_filter filter = m_nativeSession->get_ip_filter(); lt::error_code ec; const lt::address addr = lt::make_address(ip.toLatin1().constData(), ec); @@ -1744,7 +1825,8 @@ bool Session::deleteTorrent(const InfoHash &hash, const DeleteOption deleteOptio emit torrentAboutToBeRemoved(torrent); // Remove it from session - if (deleteOption == Torrent) { + if (deleteOption == Torrent) + { m_removingTorrents[torrent->hash()] = {torrent->name(), "", deleteOption}; const lt::torrent_handle nativeHandle {torrent->nativeHandle()}; @@ -1753,26 +1835,31 @@ bool Session::deleteTorrent(const InfoHash &hash, const DeleteOption deleteOptio { return job.torrentHandle == nativeHandle; }); - if (iter != m_moveStorageQueue.end()) { + if (iter != m_moveStorageQueue.end()) + { // We shouldn't actually remove torrent until existing "move storage jobs" are done torrentQueuePositionBottom(nativeHandle); nativeHandle.unset_flags(lt::torrent_flags::auto_managed); nativeHandle.pause(); } - else { + else + { m_nativeSession->remove_torrent(nativeHandle, lt::session::delete_partfile); } } - else { + else + { QString rootPath = torrent->rootPath(true); - if (!rootPath.isEmpty() && torrent->useTempPath()) { + if (!rootPath.isEmpty() && torrent->useTempPath()) + { // torrent without root folder still has it in its temporary save path rootPath = torrent->actualStorageLocation(); } m_removingTorrents[torrent->hash()] = {torrent->name(), rootPath, deleteOption}; - if (m_moveStorageQueue.size() > 1) { + if (m_moveStorageQueue.size() > 1) + { // Delete "move storage job" for the deleted torrent // (note: we shouldn't delete active job) const auto iter = std::find_if(m_moveStorageQueue.begin() + 1, m_moveStorageQueue.end() @@ -1825,14 +1912,16 @@ void Session::increaseTorrentsQueuePos(const QVector &hashes) , std::greater> torrentQueue; // Sort torrents by queue position - for (const InfoHash &infoHash : hashes) { + for (const InfoHash &infoHash : hashes) + { TorrentHandleImpl *const torrent = m_torrents.value(infoHash); if (torrent && !torrent->isSeed()) torrentQueue.emplace(torrent->queuePosition(), torrent); } // Increase torrents queue position (starting with the one in the highest queue position) - while (!torrentQueue.empty()) { + while (!torrentQueue.empty()) + { const TorrentHandleImpl *torrent = torrentQueue.top().second; torrentQueuePositionUp(torrent->nativeHandle()); torrentQueue.pop(); @@ -1847,14 +1936,16 @@ void Session::decreaseTorrentsQueuePos(const QVector &hashes) std::priority_queue torrentQueue; // Sort torrents by queue position - for (const InfoHash &infoHash : hashes) { + for (const InfoHash &infoHash : hashes) + { TorrentHandleImpl *const torrent = m_torrents.value(infoHash); if (torrent && !torrent->isSeed()) torrentQueue.emplace(torrent->queuePosition(), torrent); } // Decrease torrents queue position (starting with the one in the lowest queue position) - while (!torrentQueue.empty()) { + while (!torrentQueue.empty()) + { const TorrentHandleImpl *torrent = torrentQueue.top().second; torrentQueuePositionDown(torrent->nativeHandle()); torrentQueue.pop(); @@ -1872,14 +1963,16 @@ void Session::topTorrentsQueuePos(const QVector &hashes) std::priority_queue torrentQueue; // Sort torrents by queue position - for (const InfoHash &infoHash : hashes) { + for (const InfoHash &infoHash : hashes) + { TorrentHandleImpl *const torrent = m_torrents.value(infoHash); if (torrent && !torrent->isSeed()) torrentQueue.emplace(torrent->queuePosition(), torrent); } // Top torrents queue position (starting with the one in the lowest queue position) - while (!torrentQueue.empty()) { + while (!torrentQueue.empty()) + { const TorrentHandleImpl *torrent = torrentQueue.top().second; torrentQueuePositionTop(torrent->nativeHandle()); torrentQueue.pop(); @@ -1896,14 +1989,16 @@ void Session::bottomTorrentsQueuePos(const QVector &hashes) , std::greater> torrentQueue; // Sort torrents by queue position - for (const InfoHash &infoHash : hashes) { + for (const InfoHash &infoHash : hashes) + { TorrentHandleImpl *const torrent = m_torrents.value(infoHash); if (torrent && !torrent->isSeed()) torrentQueue.emplace(torrent->queuePosition(), torrent); } // Bottom torrents queue position (starting with the one in the highest queue position) - while (!torrentQueue.empty()) { + while (!torrentQueue.empty()) + { const TorrentHandleImpl *torrent = torrentQueue.top().second; torrentQueuePositionBottom(torrent->nativeHandle()); torrentQueue.pop(); @@ -1935,7 +2030,8 @@ bool Session::addTorrent(const QString &source, const AddTorrentParams ¶ms) { // `source`: .torrent file path/url or magnet uri - if (Net::DownloadManager::hasSupportedScheme(source)) { + if (Net::DownloadManager::hasSupportedScheme(source)) + { LogMsg(tr("Downloading '%1', please wait...", "e.g: Downloading 'xxx.torrent', please wait...").arg(source)); // Launch downloader Net::DownloadManager::instance()->download(Net::DownloadRequest(source).limit(MAX_TORRENT_SIZE) @@ -1949,7 +2045,8 @@ bool Session::addTorrent(const QString &source, const AddTorrentParams ¶ms) return addTorrent(magnetUri, params); TorrentFileGuard guard {source}; - if (addTorrent(TorrentInfo::loadFromFile(source), params)) { + if (addTorrent(TorrentInfo::loadFromFile(source), params)) + { guard.markAsAddedToSession(); return true; } @@ -1964,7 +2061,8 @@ bool Session::addTorrent(const MagnetUri &magnetUri, const AddTorrentParams &par const InfoHash hash = magnetUri.hash(); const auto it = m_loadedMetadata.constFind(hash); - if (it != m_loadedMetadata.constEnd()) { + if (it != m_loadedMetadata.constEnd()) + { // It looks illogical that we don't just use an existing handle, // but as previous experience has shown, it actually creates unnecessary // problems and unwanted behavior due to the fact that it was originally @@ -2034,7 +2132,8 @@ bool Session::addTorrent_impl(const AddTorrentParams &addTorrentParams, const Ma return false; TorrentHandleImpl *const torrent = m_torrents.value(hash); - if (torrent) { // a duplicate torrent is added + if (torrent) + { // a duplicate torrent is added if (torrent->isPrivate() || (hasMetadata && metadata.isPrivate())) return false; @@ -2049,7 +2148,8 @@ bool Session::addTorrent_impl(const AddTorrentParams &addTorrentParams, const Ma // If empty then Automatic mode, otherwise Manual mode QString actualSavePath = loadTorrentParams.savePath.isEmpty() ? categorySavePath(loadTorrentParams.category) : loadTorrentParams.savePath; - if (hasMetadata) { + if (hasMetadata) + { if (!loadTorrentParams.hasRootFolder) metadata.stripRootFolder(); @@ -2058,7 +2158,8 @@ bool Session::addTorrent_impl(const AddTorrentParams &addTorrentParams, const Ma // if torrent name wasn't explicitly set we handle the case of // initial renaming of torrent content and rename torrent accordingly - if (loadTorrentParams.name.isEmpty()) { + if (loadTorrentParams.name.isEmpty()) + { QString contentName = metadata.rootFolder(); if (contentName.isEmpty() && (metadata.filesCount() == 1)) contentName = metadata.fileName(0); @@ -2077,7 +2178,8 @@ bool Session::addTorrent_impl(const AddTorrentParams &addTorrentParams, const Ma p.ti = metadata.nativeInfo(); } - else { + else + { p = magnetUri.addTorrentParams(); if (loadTorrentParams.name.isEmpty() && !p.name.empty()) @@ -2147,12 +2249,15 @@ bool Session::findIncompleteFiles(TorrentInfo &torrentInfo, QString &savePath) c { const QDir dir(dirPath); bool found = false; - for (int i = 0; i < torrentInfo.filesCount(); ++i) { + for (int i = 0; i < torrentInfo.filesCount(); ++i) + { const QString filePath = torrentInfo.filePath(i); - if (dir.exists(filePath)) { + if (dir.exists(filePath)) + { found = true; } - else if (dir.exists(filePath + QB_EXT)) { + else if (dir.exists(filePath + QB_EXT)) + { found = true; torrentInfo.renameFile(i, filePath + QB_EXT); } @@ -2162,7 +2267,8 @@ bool Session::findIncompleteFiles(TorrentInfo &torrentInfo, QString &savePath) c }; bool found = findInDir(savePath, torrentInfo); - if (!found && isTempPathEnabled()) { + if (!found && isTempPathEnabled()) + { savePath = torrentTempPath(torrentInfo); found = findInDir(savePath, torrentInfo); } @@ -2239,10 +2345,12 @@ void Session::exportTorrentFile(const TorrentHandle *torrent, TorrentExportFolde QString torrentExportFilename = QString::fromLatin1("%1.torrent").arg(validName); const QString torrentPath = QDir(m_resumeFolderPath).absoluteFilePath(torrentFilename); const QDir exportPath(folder == TorrentExportFolder::Regular ? torrentExportDirectory() : finishedTorrentExportDirectory()); - if (exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) { + if (exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) + { QString newTorrentPath = exportPath.absoluteFilePath(torrentExportFilename); int counter = 0; - while (QFile::exists(newTorrentPath) && !Utils::Fs::sameFiles(torrentPath, newTorrentPath)) { + while (QFile::exists(newTorrentPath) && !Utils::Fs::sameFiles(torrentPath, newTorrentPath)) + { // Append number to torrent name to make it unique torrentExportFilename = QString::fromLatin1("%1 %2.torrent").arg(validName).arg(++counter); newTorrentPath = exportPath.absoluteFilePath(torrentExportFilename); @@ -2255,7 +2363,8 @@ void Session::exportTorrentFile(const TorrentHandle *torrent, TorrentExportFolde void Session::generateResumeData() { - for (TorrentHandleImpl *const torrent : asConst(m_torrents)) { + for (TorrentHandleImpl *const torrent : asConst(m_torrents)) + { if (!torrent->isValid()) continue; if (torrent->needSaveResumeData()) @@ -2273,16 +2382,20 @@ void Session::saveResumeData() saveTorrentsQueue(); generateResumeData(); - while (m_numResumeData > 0) { + while (m_numResumeData > 0) + { const std::vector alerts = getPendingAlerts(lt::seconds {30}); - if (alerts.empty()) { + if (alerts.empty()) + { LogMsg(tr("Error: Aborted saving resume data for %1 outstanding torrents.").arg(QString::number(m_numResumeData)) , Log::CRITICAL); break; } - for (const lt::alert *a : alerts) { - switch (a->type()) { + for (const lt::alert *a : alerts) + { + switch (a->type()) + { case lt::save_resume_data_failed_alert::alert_type: case lt::save_resume_data_alert::alert_type: dispatchTorrentAlert(a); @@ -2296,7 +2409,8 @@ void Session::saveTorrentsQueue() { // store hash in textual representation QMap queue; // Use QMap since it should be ordered by key - for (const TorrentHandleImpl *torrent : asConst(m_torrents)) { + for (const TorrentHandleImpl *torrent : asConst(m_torrents)) + { // We require actual (non-cached) queue position here! const int queuePos = static_cast>(torrent->nativeHandle().queue_position()); if (queuePos >= 0) @@ -2369,7 +2483,8 @@ void Session::networkConfigurationChange(const QNetworkConfiguration &cfg) const QString changedInterface = cfg.name(); - if (configuredInterfaceName == changedInterface) { + if (configuredInterfaceName == changedInterface) + { LogMsg(tr("Network configuration of %1 has changed, refreshing session binding", "e.g: Network configuration of tun0 has changed, refreshing session binding").arg(changedInterface), Log::INFO); configureListeningInterface(); } @@ -2385,7 +2500,8 @@ QStringList Session::getListeningIPs() const const bool allIPv4 = (ifaceAddr == QLatin1String("0.0.0.0")); // Means All IPv4 addresses const bool allIPv6 = (ifaceAddr == QLatin1String("::")); // Means All IPv6 addresses - if (!ifaceAddr.isEmpty() && !allIPv4 && !allIPv6 && configuredAddr.isNull()) { + if (!ifaceAddr.isEmpty() && !allIPv4 && !allIPv6 && configuredAddr.isNull()) + { LogMsg(tr("Configured network interface address %1 isn't valid.", "Configured network interface address 124.5.158.1 isn't valid.").arg(ifaceAddr), Log::CRITICAL); // Pass the invalid user configured interface name/address to libtorrent // in hopes that it will come online later. @@ -2395,7 +2511,8 @@ QStringList Session::getListeningIPs() const return IPs; } - if (ifaceName.isEmpty()) { + if (ifaceName.isEmpty()) + { if (ifaceAddr.isEmpty()) return {QLatin1String("0.0.0.0"), QLatin1String("::")}; // Indicates all interfaces + all addresses (aka default) @@ -2416,14 +2533,16 @@ QStringList Session::getListeningIPs() const IPs.append(addr.toString()); }; - if (ifaceName.isEmpty()) { + if (ifaceName.isEmpty()) + { const QList addresses = QNetworkInterface::allAddresses(); for (const auto &addr : addresses) checkAndAddIP(addr, configuredAddr); // At this point ifaceAddr was non-empty // If IPs.isEmpty() it means the configured Address was not found - if (IPs.isEmpty()) { + if (IPs.isEmpty()) + { LogMsg(tr("Can't find the configured address '%1' to listen on" , "Can't find the configured address '192.168.1.3' to listen on") .arg(ifaceAddr), Log::CRITICAL); @@ -2435,14 +2554,16 @@ QStringList Session::getListeningIPs() const // Attempt to listen on provided interface const QNetworkInterface networkIFace = QNetworkInterface::interfaceFromName(ifaceName); - if (!networkIFace.isValid()) { + if (!networkIFace.isValid()) + { qDebug("Invalid network interface: %s", qUtf8Printable(ifaceName)); LogMsg(tr("The network interface defined is invalid: %1").arg(ifaceName), Log::CRITICAL); IPs.append(ifaceName); return IPs; } - if (ifaceAddr.isEmpty()) { + if (ifaceAddr.isEmpty()) + { IPs.append(ifaceName); return IPs; // On Windows calling code converts it to GUID } @@ -2455,7 +2576,8 @@ QStringList Session::getListeningIPs() const // Make sure there is at least one IP // At this point there was an explicit interface and an explicit address set // and the address should have been found - if (IPs.isEmpty()) { + if (IPs.isEmpty()) + { LogMsg(tr("Can't find the configured address '%1' to listen on" , "Can't find the configured address '192.168.1.3' to listen on") .arg(ifaceAddr), Log::CRITICAL); @@ -2626,7 +2748,8 @@ bool Session::isBandwidthSchedulerEnabled() const void Session::setBandwidthSchedulerEnabled(const bool enabled) { - if (enabled != isBandwidthSchedulerEnabled()) { + if (enabled != isBandwidthSchedulerEnabled()) + { m_isBandwidthSchedulerEnabled = enabled; if (enabled) enableBandwidthScheduler(); @@ -2647,11 +2770,13 @@ void Session::setSaveResumeDataInterval(const int value) m_saveResumeDataInterval = value; - if (value > 0) { + if (value > 0) + { m_resumeDataTimer->setInterval(value * 60 * 1000); m_resumeDataTimer->start(); } - else { + else + { m_resumeDataTimer->stop(); } } @@ -2663,7 +2788,8 @@ int Session::port() const void Session::setPort(const int port) { - if (port != m_port) { + if (port != m_port) + { m_port = port; configureListeningInterface(); } @@ -2686,7 +2812,8 @@ QString Session::networkInterface() const void Session::setNetworkInterface(const QString &iface) { - if (iface != networkInterface()) { + if (iface != networkInterface()) + { m_networkInterface = iface; configureListeningInterface(); } @@ -2709,7 +2836,8 @@ QString Session::networkInterfaceAddress() const void Session::setNetworkInterfaceAddress(const QString &address) { - if (address != networkInterfaceAddress()) { + if (address != networkInterfaceAddress()) + { m_networkInterfaceAddress = address; configureListeningInterface(); } @@ -2722,7 +2850,8 @@ int Session::encryption() const void Session::setEncryption(const int state) { - if (state != encryption()) { + if (state != encryption()) + { m_encryption = state; configureDeferred(); LogMsg(tr("Encryption support [%1]").arg( @@ -2738,7 +2867,8 @@ bool Session::isProxyPeerConnectionsEnabled() const void Session::setProxyPeerConnectionsEnabled(const bool enabled) { - if (enabled != isProxyPeerConnectionsEnabled()) { + if (enabled != isProxyPeerConnectionsEnabled()) + { m_isProxyPeerConnectionsEnabled = enabled; configureDeferred(); } @@ -2787,7 +2917,8 @@ QString Session::additionalTrackers() const void Session::setAdditionalTrackers(const QString &trackers) { - if (trackers != additionalTrackers()) { + if (trackers != additionalTrackers()) + { m_additionalTrackers = trackers; populateAdditionalTrackers(); } @@ -2800,7 +2931,8 @@ bool Session::isIPFilteringEnabled() const void Session::setIPFilteringEnabled(const bool enabled) { - if (enabled != m_isIPFilteringEnabled) { + if (enabled != m_isIPFilteringEnabled) + { m_isIPFilteringEnabled = enabled; m_IPFilteringConfigured = false; configureDeferred(); @@ -2815,7 +2947,8 @@ QString Session::IPFilterFile() const void Session::setIPFilterFile(QString path) { path = Utils::Fs::toUniformPath(path); - if (path != IPFilterFile()) { + if (path != IPFilterFile()) + { m_IPFilterFile = path; m_IPFilteringConfigured = false; configureDeferred(); @@ -2828,14 +2961,17 @@ void Session::setBannedIPs(const QStringList &newList) return; // do nothing // here filter out incorrect IP QStringList filteredList; - for (const QString &ip : newList) { - if (Utils::Net::isValidIP(ip)) { + for (const QString &ip : newList) + { + if (Utils::Net::isValidIP(ip)) + { // the same IPv6 addresses could be written in different forms; // QHostAddress::toString() result format follows RFC5952; // thus we avoid duplicate entries pointing to the same address filteredList << QHostAddress(ip).toString(); } - else { + else + { LogMsg(tr("%1 is not a valid IP address and was rejected while applying the list of banned addresses.") .arg(ip) , Log::WARNING); @@ -2898,7 +3034,8 @@ void Session::applyOSMemoryPriority() const #endif MEMORY_PRIORITY_INFORMATION prioInfo {}; - switch (getOSMemoryPriority()) { + switch (getOSMemoryPriority()) + { case OSMemoryPriority::Normal: default: prioInfo.MemoryPriority = MEMORY_PRIORITY_NORMAL; @@ -2928,13 +3065,16 @@ int Session::maxConnectionsPerTorrent() const void Session::setMaxConnectionsPerTorrent(int max) { max = (max > 0) ? max : -1; - if (max != maxConnectionsPerTorrent()) { + if (max != maxConnectionsPerTorrent()) + { m_maxConnectionsPerTorrent = max; // Apply this to all session torrents - for (const lt::torrent_handle &handle : m_nativeSession->get_torrents()) { + for (const lt::torrent_handle &handle : m_nativeSession->get_torrents()) + { if (!handle.is_valid()) continue; - try { + try + { handle.set_max_connections(max); } catch (const std::exception &) {} @@ -2950,13 +3090,16 @@ int Session::maxUploadsPerTorrent() const void Session::setMaxUploadsPerTorrent(int max) { max = (max > 0) ? max : -1; - if (max != maxUploadsPerTorrent()) { + if (max != maxUploadsPerTorrent()) + { m_maxUploadsPerTorrent = max; // Apply this to all session torrents - for (const lt::torrent_handle &handle : m_nativeSession->get_torrents()) { + for (const lt::torrent_handle &handle : m_nativeSession->get_torrents()) + { if (!handle.is_valid()) continue; - try { + try + { handle.set_max_uploads(max); } catch (const std::exception &) {} @@ -2971,7 +3114,8 @@ bool Session::announceToAllTrackers() const void Session::setAnnounceToAllTrackers(const bool val) { - if (val != m_announceToAllTrackers) { + if (val != m_announceToAllTrackers) + { m_announceToAllTrackers = val; configureDeferred(); } @@ -2984,7 +3128,8 @@ bool Session::announceToAllTiers() const void Session::setAnnounceToAllTiers(const bool val) { - if (val != m_announceToAllTiers) { + if (val != m_announceToAllTiers) + { m_announceToAllTiers = val; configureDeferred(); } @@ -3109,7 +3254,8 @@ void Session::setDiskCacheSize(int size) // allocate 1536MiB and leave 512MiB to the rest of program data in RAM size = qMin(size, 1536); #endif - if (size != m_diskCacheSize) { + if (size != m_diskCacheSize) + { m_diskCacheSize = size; configureDeferred(); } @@ -3122,7 +3268,8 @@ int Session::diskCacheTTL() const void Session::setDiskCacheTTL(const int ttl) { - if (ttl != m_diskCacheTTL) { + if (ttl != m_diskCacheTTL) + { m_diskCacheTTL = ttl; configureDeferred(); } @@ -3135,7 +3282,8 @@ bool Session::useOSCache() const void Session::setUseOSCache(const bool use) { - if (use != m_useOSCache) { + if (use != m_useOSCache) + { m_useOSCache = use; configureDeferred(); } @@ -3239,7 +3387,8 @@ bool Session::isAnonymousModeEnabled() const void Session::setAnonymousModeEnabled(const bool enabled) { - if (enabled != m_isAnonymousModeEnabled) { + if (enabled != m_isAnonymousModeEnabled) + { m_isAnonymousModeEnabled = enabled; configureDeferred(); LogMsg(tr("Anonymous mode [%1]").arg(isAnonymousModeEnabled() ? tr("ON") : tr("OFF")) @@ -3254,7 +3403,8 @@ bool Session::isQueueingSystemEnabled() const void Session::setQueueingSystemEnabled(const bool enabled) { - if (enabled != m_isQueueingEnabled) { + if (enabled != m_isQueueingEnabled) + { m_isQueueingEnabled = enabled; configureDeferred(); @@ -3273,7 +3423,8 @@ int Session::maxActiveDownloads() const void Session::setMaxActiveDownloads(int max) { max = std::max(max, -1); - if (max != m_maxActiveDownloads) { + if (max != m_maxActiveDownloads) + { m_maxActiveDownloads = max; configureDeferred(); } @@ -3287,7 +3438,8 @@ int Session::maxActiveUploads() const void Session::setMaxActiveUploads(int max) { max = std::max(max, -1); - if (max != m_maxActiveUploads) { + if (max != m_maxActiveUploads) + { m_maxActiveUploads = max; configureDeferred(); } @@ -3301,7 +3453,8 @@ int Session::maxActiveTorrents() const void Session::setMaxActiveTorrents(int max) { max = std::max(max, -1); - if (max != m_maxActiveTorrents) { + if (max != m_maxActiveTorrents) + { m_maxActiveTorrents = max; configureDeferred(); } @@ -3314,7 +3467,8 @@ bool Session::ignoreSlowTorrentsForQueueing() const void Session::setIgnoreSlowTorrentsForQueueing(const bool ignore) { - if (ignore != m_ignoreSlowTorrentsForQueueing) { + if (ignore != m_ignoreSlowTorrentsForQueueing) + { m_ignoreSlowTorrentsForQueueing = ignore; configureDeferred(); } @@ -3369,7 +3523,8 @@ int Session::outgoingPortsMin() const void Session::setOutgoingPortsMin(const int min) { - if (min != m_outgoingPortsMin) { + if (min != m_outgoingPortsMin) + { m_outgoingPortsMin = min; configureDeferred(); } @@ -3382,7 +3537,8 @@ int Session::outgoingPortsMax() const void Session::setOutgoingPortsMax(const int max) { - if (max != m_outgoingPortsMax) { + if (max != m_outgoingPortsMax) + { m_outgoingPortsMax = max; configureDeferred(); } @@ -3395,7 +3551,8 @@ int Session::UPnPLeaseDuration() const void Session::setUPnPLeaseDuration(const int duration) { - if (duration != m_UPnPLeaseDuration) { + if (duration != m_UPnPLeaseDuration) + { m_UPnPLeaseDuration = duration; configureDeferred(); } @@ -3408,7 +3565,8 @@ bool Session::ignoreLimitsOnLAN() const void Session::setIgnoreLimitsOnLAN(const bool ignore) { - if (ignore != m_ignoreLimitsOnLAN) { + if (ignore != m_ignoreLimitsOnLAN) + { m_ignoreLimitsOnLAN = ignore; configureDeferred(); } @@ -3421,7 +3579,8 @@ bool Session::includeOverheadInLimits() const void Session::setIncludeOverheadInLimits(const bool include) { - if (include != m_includeOverheadInLimits) { + if (include != m_includeOverheadInLimits) + { m_includeOverheadInLimits = include; configureDeferred(); } @@ -3434,7 +3593,8 @@ QString Session::announceIP() const void Session::setAnnounceIP(const QString &ip) { - if (ip != m_announceIP) { + if (ip != m_announceIP) + { m_announceIP = ip; configureDeferred(); } @@ -3476,7 +3636,8 @@ int Session::maxConnections() const void Session::setMaxConnections(int max) { max = (max > 0) ? max : -1; - if (max != m_maxConnections) { + if (max != m_maxConnections) + { m_maxConnections = max; configureDeferred(); } @@ -3490,7 +3651,8 @@ int Session::maxUploads() const void Session::setMaxUploads(int max) { max = (max > 0) ? max : -1; - if (max != m_maxUploads) { + if (max != m_maxUploads) + { m_maxUploads = max; configureDeferred(); } @@ -3519,7 +3681,8 @@ bool Session::isUTPRateLimited() const void Session::setUTPRateLimited(const bool limited) { - if (limited != m_isUTPRateLimited) { + if (limited != m_isUTPRateLimited) + { m_isUTPRateLimited = limited; configureDeferred(); } @@ -3584,7 +3747,8 @@ bool Session::isTrackerFilteringEnabled() const void Session::setTrackerFilteringEnabled(const bool enabled) { - if (enabled != m_isTrackerFilteringEnabled) { + if (enabled != m_isTrackerFilteringEnabled) + { m_isTrackerFilteringEnabled = enabled; configureDeferred(); } @@ -3617,11 +3781,13 @@ bool Session::isKnownTorrent(const InfoHash &hash) const void Session::updateSeedingLimitTimer() { if ((globalMaxRatio() == TorrentHandle::NO_RATIO_LIMIT) && !hasPerTorrentRatioLimit() - && (globalMaxSeedingMinutes() == TorrentHandle::NO_SEEDING_TIME_LIMIT) && !hasPerTorrentSeedingTimeLimit()) { + && (globalMaxSeedingMinutes() == TorrentHandle::NO_SEEDING_TIME_LIMIT) && !hasPerTorrentSeedingTimeLimit()) + { if (m_seedingLimitTimer->isActive()) m_seedingLimitTimer->stop(); } - else if (!m_seedingLimitTimer->isActive()) { + else if (!m_seedingLimitTimer->isActive()) + { m_seedingLimitTimer->start(); } } @@ -3718,13 +3884,15 @@ void Session::handleTorrentMetadataReceived(TorrentHandleImpl *const torrent) // Save metadata const QDir resumeDataDir {m_resumeFolderPath}; const QString torrentFileName {QString {"%1.torrent"}.arg(torrent->hash())}; - try { + try + { torrent->info().saveToFile(resumeDataDir.absoluteFilePath(torrentFileName)); // Copy the torrent file to the export folder if (!torrentExportDirectory().isEmpty()) exportTorrentFile(torrent); } - catch (const RuntimeError &err) { + catch (const RuntimeError &err) + { LogMsg(tr("Couldn't save torrent metadata file '%1'. Reason: %2") .arg(torrentFileName, err.message()), Log::CRITICAL); } @@ -3757,19 +3925,23 @@ void Session::handleTorrentFinished(TorrentHandleImpl *const torrent) qDebug("Checking if the torrent contains torrent files to download"); // Check if there are torrent files inside - for (int i = 0; i < torrent->filesCount(); ++i) { + for (int i = 0; i < torrent->filesCount(); ++i) + { const QString torrentRelpath = torrent->filePath(i); - if (torrentRelpath.endsWith(".torrent", Qt::CaseInsensitive)) { + if (torrentRelpath.endsWith(".torrent", Qt::CaseInsensitive)) + { qDebug("Found possible recursive torrent download."); const QString torrentFullpath = torrent->savePath(true) + '/' + torrentRelpath; qDebug("Full subtorrent path is %s", qUtf8Printable(torrentFullpath)); TorrentInfo torrentInfo = TorrentInfo::loadFromFile(torrentFullpath); - if (torrentInfo.isValid()) { + if (torrentInfo.isValid()) + { qDebug("emitting recursiveTorrentDownloadPossible()"); emit recursiveTorrentDownloadPossible(torrent); break; } - else { + else + { qDebug("Caught error loading torrent"); LogMsg(tr("Unable to decode '%1' torrent file.").arg(Utils::Fs::toNativePath(torrentFullpath)), Log::CRITICAL); } @@ -3818,31 +3990,37 @@ bool Session::addMoveTorrentStorageJob(TorrentHandleImpl *torrent, const QString const lt::torrent_handle torrentHandle = torrent->nativeHandle(); const QString currentLocation = torrent->actualStorageLocation(); - if (m_moveStorageQueue.size() > 1) { + if (m_moveStorageQueue.size() > 1) + { const auto iter = std::find_if(m_moveStorageQueue.begin() + 1, m_moveStorageQueue.end() , [&torrentHandle](const MoveStorageJob &job) { return job.torrentHandle == torrentHandle; }); - if (iter != m_moveStorageQueue.end()) { + if (iter != m_moveStorageQueue.end()) + { // remove existing inactive job m_moveStorageQueue.erase(iter); LogMsg(tr("Cancelled moving \"%1\" from \"%2\" to \"%3\".").arg(torrent->name(), currentLocation, iter->path)); } } - if (!m_moveStorageQueue.isEmpty() && (m_moveStorageQueue.first().torrentHandle == torrentHandle)) { + if (!m_moveStorageQueue.isEmpty() && (m_moveStorageQueue.first().torrentHandle == torrentHandle)) + { // if there is active job for this torrent prevent creating meaningless // job that will move torrent to the same location as current one - if (QDir {m_moveStorageQueue.first().path} == QDir {newPath}) { + if (QDir {m_moveStorageQueue.first().path} == QDir {newPath}) + { LogMsg(tr("Couldn't enqueue move of \"%1\" to \"%2\". Torrent is currently moving to the same destination location.") .arg(torrent->name(), newPath)); return false; } } - else { - if (QDir {currentLocation} == QDir {newPath}) { + else + { + if (QDir {currentLocation} == QDir {newPath}) + { LogMsg(tr("Couldn't enqueue move of \"%1\" from \"%2\" to \"%3\". Both paths point to the same location.") .arg(torrent->name(), currentLocation, newPath)); return false; @@ -3887,8 +4065,10 @@ void Session::handleMoveTorrentStorageJobFinished() if (torrent) torrent->handleMoveStorageJobFinished(torrentHasOutstandingJob); - if (!torrentHasOutstandingJob) { - if (!torrent) { + if (!torrentHasOutstandingJob) + { + if (!torrent) + { // Last job is completed for torrent that being removing, so actually remove it const lt::torrent_handle nativeHandle {finishedJob.torrentHandle}; const RemovingTorrentData &removingTorrentData = m_removingTorrents[nativeHandle.info_hash()]; @@ -3926,15 +4106,20 @@ void Session::initResumeFolder() { m_resumeFolderPath = Utils::Fs::expandPathAbs(specialFolderLocation(SpecialFolder::Data) + RESUME_FOLDER); const QDir resumeFolderDir(m_resumeFolderPath); - if (resumeFolderDir.exists() || resumeFolderDir.mkpath(resumeFolderDir.absolutePath())) { + if (resumeFolderDir.exists() || resumeFolderDir.mkpath(resumeFolderDir.absolutePath())) + { m_resumeFolderLock->setFileName(resumeFolderDir.absoluteFilePath("session.lock")); - if (!m_resumeFolderLock->open(QFile::WriteOnly)) { - throw RuntimeError {tr("Cannot write to torrent resume folder: \"%1\"") + if (!m_resumeFolderLock->open(QFile::WriteOnly)) + { + throw RuntimeError + {tr("Cannot write to torrent resume folder: \"%1\"") .arg(Utils::Fs::toNativePath(m_resumeFolderPath))}; } } - else { - throw RuntimeError {tr("Cannot create torrent resume folder: \"%1\"") + else + { + throw RuntimeError + {tr("Cannot create torrent resume folder: \"%1\"") .arg(Utils::Fs::toNativePath(m_resumeFolderPath))}; } } @@ -3963,7 +4148,8 @@ void Session::enableIPFilter() // 2. In the slot add the manually banned IPs to the provided lt::ip_filter // 3. Set the ip_filter in one go so there isn't a time window where there isn't an ip_filter // set between clearing the old one and setting the new one. - if (!m_filterParser) { + if (!m_filterParser) + { m_filterParser = new FilterParserThread(this); connect(m_filterParser.data(), &FilterParserThread::IPFilterParsed, this, &Session::handleIPFilterParsed); connect(m_filterParser.data(), &FilterParserThread::IPFilterError, this, &Session::handleIPFilterError); @@ -3975,7 +4161,8 @@ void Session::enableIPFilter() void Session::disableIPFilter() { qDebug("Disabling IPFilter"); - if (m_filterParser) { + if (m_filterParser) + { disconnect(m_filterParser.data(), nullptr, this, nullptr); delete m_filterParser; } @@ -3993,9 +4180,11 @@ void Session::recursiveTorrentDownload(const InfoHash &hash) TorrentHandleImpl *const torrent = m_torrents.value(hash); if (!torrent) return; - for (int i = 0; i < torrent->filesCount(); ++i) { + for (int i = 0; i < torrent->filesCount(); ++i) + { const QString torrentRelpath = torrent->filePath(i); - if (torrentRelpath.endsWith(".torrent")) { + if (torrentRelpath.endsWith(".torrent")) + { LogMsg(tr("Recursive download of file '%1' embedded in torrent '%2'" , "Recursive download of 'test.torrent' embedded in torrent 'test2'") .arg(Utils::Fs::toNativePath(torrentRelpath), torrent->name())); @@ -4044,8 +4233,10 @@ bool Session::loadTorrentResumeData(const QByteArray &data, const TorrentInfo &m torrentParams.ratioLimit = fromLTString(ratioLimitString).toDouble(); const lt::bdecode_node tagsNode = root.dict_find("qBt-tags"); - if (tagsNode.type() == lt::bdecode_node::list_t) { - for (int i = 0; i < tagsNode.list_size(); ++i) { + if (tagsNode.type() == lt::bdecode_node::list_t) + { + for (int i = 0; i < tagsNode.list_size(); ++i) + { const QString tag = fromLTString(tagsNode.list_string_value_at(i)); if (Session::isValidTag(tag)) torrentParams.tags << tag; @@ -4054,7 +4245,8 @@ bool Session::loadTorrentResumeData(const QByteArray &data, const TorrentInfo &m // NOTE: Do we really need the following block in case of existing (restored) torrent? torrentParams.savePath = normalizePath(torrentParams.savePath); - if (!torrentParams.category.isEmpty()) { + if (!torrentParams.category.isEmpty()) + { if (!m_categories.contains(torrentParams.category) && !addCategory(torrentParams.category)) torrentParams.category = ""; } @@ -4067,12 +4259,14 @@ bool Session::loadTorrentResumeData(const QByteArray &data, const TorrentInfo &m p.ti = metadata.nativeInfo(); torrentParams.paused = (p.flags & lt::torrent_flags::paused) && !(p.flags & lt::torrent_flags::auto_managed); - if (!torrentParams.paused) { + if (!torrentParams.paused) + { // If torrent has "stop_when_ready" flag set then it is actually "stopped" // but temporarily "resumed" to perform some service jobs (e.g. checking) torrentParams.paused = !!(p.flags & lt::torrent_flags::stop_when_ready); } - else { + else + { // Fix inconsistent state when "paused" torrent has "stop_when_ready" flag set p.flags &= ~lt::torrent_flags::stop_when_ready; } @@ -4080,18 +4274,22 @@ bool Session::loadTorrentResumeData(const QByteArray &data, const TorrentInfo &m torrentParams.forced = !(p.flags & lt::torrent_flags::paused) && !(p.flags & lt::torrent_flags::auto_managed); const bool hasMetadata = (p.ti && p.ti->is_valid()); - if (!hasMetadata && !root.dict_find("info-hash")) { + if (!hasMetadata && !root.dict_find("info-hash")) + { // TODO: The following code is deprecated. Remove after several releases in 4.3.x. // === BEGIN DEPRECATED CODE === // // Try to load from legacy data used in older versions for torrents w/o metadata const lt::bdecode_node magnetURINode = root.dict_find("qBt-magnetUri"); - if (magnetURINode.type() == lt::bdecode_node::string_t) { + if (magnetURINode.type() == lt::bdecode_node::string_t) + { lt::parse_magnet_uri(magnetURINode.string_value(), p, ec); - if (isTempPathEnabled()) { + if (isTempPathEnabled()) + { p.save_path = Utils::Fs::toNativePath(tempPath()).toStdString(); } - else { + else + { // If empty then Automatic mode, otherwise Manual mode const QString savePath = torrentParams.savePath.isEmpty() ? categorySavePath(torrentParams.category) : torrentParams.savePath; p.save_path = Utils::Fs::toNativePath(savePath).toStdString(); @@ -4105,7 +4303,8 @@ bool Session::loadTorrentResumeData(const QByteArray &data, const TorrentInfo &m p.added_time = addedTimeNode.int_value(); const lt::bdecode_node sequentialNode = root.dict_find("qBt-sequential"); - if (sequentialNode.type() == lt::bdecode_node::int_t) { + if (sequentialNode.type() == lt::bdecode_node::int_t) + { if (static_cast(sequentialNode.int_value())) p.flags |= lt::torrent_flags::sequential_download; else @@ -4116,7 +4315,8 @@ bool Session::loadTorrentResumeData(const QByteArray &data, const TorrentInfo &m torrentParams.name = QString::fromStdString(p.name); } // === END DEPRECATED CODE === // - else { + else + { return false; } } @@ -4134,7 +4334,8 @@ void Session::startUpTorrents() const auto readFile = [](const QString &path, QByteArray &buf) -> bool { QFile file(path); - if (!file.open(QIODevice::ReadOnly)) { + if (!file.open(QIODevice::ReadOnly)) + { LogMsg(tr("Cannot read file %1: %2").arg(path, file.errorString()), Log::WARNING); return false; } @@ -4148,15 +4349,18 @@ void Session::startUpTorrents() const QRegularExpression rx(QLatin1String("^([A-Fa-f0-9]{40})\\.fastresume$")); - if (isQueueingSystemEnabled()) { + if (isQueueingSystemEnabled()) + { QFile queueFile {resumeDataDir.absoluteFilePath(QLatin1String {"queue"})}; QStringList queue; - if (queueFile.open(QFile::ReadOnly)) { + if (queueFile.open(QFile::ReadOnly)) + { QByteArray line; while (!(line = queueFile.readLine()).isEmpty()) queue.append(QString::fromLatin1(line.trimmed()) + QLatin1String {".fastresume"}); } - else { + else + { LogMsg(tr("Couldn't load torrents queue from '%1'. Error: %2") .arg(queueFile.fileName(), queueFile.errorString()), Log::WARNING); } @@ -4166,7 +4370,8 @@ void Session::startUpTorrents() } int resumedTorrentsCount = 0; - for (const QString &fastresumeName : asConst(fastresumes)) { + for (const QString &fastresumeName : asConst(fastresumes)) + { const QRegularExpressionMatch rxMatch = rx.match(fastresumeName); if (!rxMatch.hasMatch()) continue; @@ -4176,7 +4381,8 @@ void Session::startUpTorrents() LoadTorrentParams torrentParams; const QString torrentFilePath = resumeDataDir.filePath(QString::fromLatin1("%1.torrent").arg(hash)); TorrentInfo metadata = TorrentInfo::loadFromFile(torrentFilePath); - if (readFile(fastresumePath, data) && loadTorrentResumeData(data, metadata, torrentParams)) { + if (readFile(fastresumePath, data) && loadTorrentResumeData(data, metadata, torrentParams)) + { qDebug() << "Starting up torrent" << hash << "..."; if (!loadTorrent(torrentParams)) LogMsg(tr("Unable to resume torrent '%1'.", "e.g: Unable to resume torrent 'hash'.") @@ -4187,7 +4393,8 @@ void Session::startUpTorrents() ++resumedTorrentsCount; } - else { + else + { LogMsg(tr("Unable to resume torrent '%1'.", "e.g: Unable to resume torrent 'hash'.") .arg(hash), Log::CRITICAL); } @@ -4219,7 +4426,8 @@ void Session::enqueueRefresh() void Session::handleIPFilterParsed(const int ruleCount) { - if (m_filterParser) { + if (m_filterParser) + { lt::ip_filter filter = m_filterParser->IPfilter(); processBannedIPs(filter); m_nativeSession->set_ip_filter(filter); @@ -4268,8 +4476,10 @@ void Session::readAlerts() void Session::handleAlert(const lt::alert *a) { - try { - switch (a->type()) { + try + { + switch (a->type()) + { case lt::file_renamed_alert::alert_type: case lt::file_completed_alert::alert_type: case lt::torrent_finished_alert::alert_type: @@ -4351,7 +4561,8 @@ void Session::handleAlert(const lt::alert *a) #endif } } - catch (const std::exception &exc) { + catch (const std::exception &exc) + { qWarning() << "Caught exception in " << Q_FUNC_INFO << ": " << QString::fromStdString(exc.what()); } } @@ -4359,12 +4570,14 @@ void Session::handleAlert(const lt::alert *a) void Session::dispatchTorrentAlert(const lt::alert *a) { TorrentHandleImpl *const torrent = m_torrents.value(static_cast(a)->handle.info_hash()); - if (torrent) { + if (torrent) + { torrent->handleAlert(a); return; } - switch (a->type()) { + switch (a->type()) + { case lt::metadata_received_alert::alert_type: handleMetadataReceivedAlert(static_cast(a)); break; @@ -4382,22 +4595,27 @@ void Session::createTorrentHandle(const lt::torrent_handle &nativeHandle) const bool hasMetadata = torrent->hasMetadata(); - if (params.restored) { + if (params.restored) + { LogMsg(tr("'%1' restored.", "'torrent name' restored.").arg(torrent->name())); } - else { + else + { // The following is useless for newly added magnet - if (hasMetadata) { + if (hasMetadata) + { // Backup torrent file const QDir resumeDataDir {m_resumeFolderPath}; const QString torrentFileName {QString {"%1.torrent"}.arg(torrent->hash())}; - try { + try + { torrent->info().saveToFile(resumeDataDir.absoluteFilePath(torrentFileName)); // Copy the torrent file to the export folder if (!torrentExportDirectory().isEmpty()) exportTorrentFile(torrent); } - catch (const RuntimeError &err) { + catch (const RuntimeError &err) + { LogMsg(tr("Couldn't save torrent metadata file '%1'. Reason: %2") .arg(torrentFileName, err.message()), Log::CRITICAL); } @@ -4437,13 +4655,15 @@ void Session::createTorrentHandle(const lt::torrent_handle &nativeHandle) void Session::handleAddTorrentAlert(const lt::add_torrent_alert *p) { - if (p->error) { + if (p->error) + { qDebug("/!\\ Error: Failed to add torrent!"); QString msg = QString::fromStdString(p->message()); LogMsg(tr("Couldn't load torrent. Reason: %1").arg(msg), Log::WARNING); emit loadTorrentFailed(msg); } - else if (m_loadingTorrents.contains(p->handle.info_hash())) { + else if (m_loadingTorrents.contains(p->handle.info_hash())) + { createTorrentHandle(p->handle); } } @@ -4453,8 +4673,10 @@ void Session::handleTorrentRemovedAlert(const lt::torrent_removed_alert *p) const InfoHash infoHash {p->info_hash}; const auto removingTorrentDataIter = m_removingTorrents.find(infoHash); - if (removingTorrentDataIter != m_removingTorrents.end()) { - if (removingTorrentDataIter->deleteOption == Torrent) { + if (removingTorrentDataIter != m_removingTorrents.end()) + { + if (removingTorrentDataIter->deleteOption == Torrent) + { LogMsg(tr("'%1' was removed from the transfer list.", "'xxx.avi' was removed...").arg(removingTorrentDataIter->name)); m_removingTorrents.erase(removingTorrentDataIter); } @@ -4486,12 +4708,14 @@ void Session::handleTorrentDeleteFailedAlert(const lt::torrent_delete_failed_ale // so we remove the directory ourselves Utils::Fs::smartRemoveEmptyFolderTree(removingTorrentDataIter->pathToRemove); - if (p->error) { + if (p->error) + { LogMsg(tr("'%1' was removed from the transfer list but the files couldn't be deleted. Error: %2", "'xxx.avi' was removed...") .arg(removingTorrentDataIter->name, QString::fromLocal8Bit(p->error.message().c_str())) , Log::WARNING); } - else { + else + { LogMsg(tr("'%1' was removed from the transfer list.", "'xxx.avi' was removed...").arg(removingTorrentDataIter->name)); } m_removingTorrents.erase(removingTorrentDataIter); @@ -4502,7 +4726,8 @@ void Session::handleMetadataReceivedAlert(const lt::metadata_received_alert *p) const InfoHash hash {p->handle.info_hash()}; const auto loadedMetadataIter = m_loadedMetadata.find(hash); - if (loadedMetadataIter != m_loadedMetadata.end()) { + if (loadedMetadataIter != m_loadedMetadata.end()) + { TorrentInfo metadata {p->handle.torrent_file()}; m_loadedMetadata.erase(loadedMetadataIter); @@ -4522,7 +4747,8 @@ void Session::handleFileErrorAlert(const lt::file_error_alert *p) const InfoHash hash = torrent->hash(); - if (!m_recentErroredTorrents.contains(hash)) { + if (!m_recentErroredTorrents.contains(hash)) + { m_recentErroredTorrents.insert(hash); const QString msg = QString::fromStdString(p->message()); @@ -4538,7 +4764,8 @@ void Session::handleFileErrorAlert(const lt::file_error_alert *p) #if (LIBTORRENT_VERSION_NUM < 10208) void Session::handleReadPieceAlert(const lt::read_piece_alert *p) const { - if (p->error) { + if (p->error) + { p->handle.unset_flags(lt::torrent_flags::auto_managed); p->handle.force_recheck(); } @@ -4559,7 +4786,8 @@ void Session::handlePortmapAlert(const lt::portmap_alert *p) void Session::handlePeerBlockedAlert(const lt::peer_blocked_alert *p) { QString reason; - switch (p->reason) { + switch (p->reason) + { case lt::peer_blocked_alert::ip_filter: reason = tr("IP filter", "this peer was blocked. Reason: IP filter."); break; @@ -4598,12 +4826,14 @@ void Session::handleUrlSeedAlert(const lt::url_seed_alert *p) if (!torrent) return; - if (p->error) { + if (p->error) + { LogMsg(tr("URL seed name lookup failed. Torrent: \"%1\". URL: \"%2\". Error: \"%3\"") .arg(torrent->name(), p->server_url(), QString::fromStdString(p->message())) , Log::WARNING); } - else { + else + { LogMsg(tr("Received error message from a URL seed. Torrent: \"%1\". URL: \"%2\". Message: \"%3\"") .arg(torrent->name(), p->server_url(), p->error_message()) , Log::WARNING); @@ -4763,7 +4993,8 @@ void Session::handleStateUpdateAlert(const lt::state_update_alert *p) QVector updatedTorrents; updatedTorrents.reserve(p->status.size()); - for (const lt::torrent_status &status : p->status) { + for (const lt::torrent_status &status : p->status) + { TorrentHandleImpl *const torrent = m_torrents.value(status.info_hash); if (!torrent) @@ -4785,7 +5016,8 @@ void Session::handleStateUpdateAlert(const lt::state_update_alert *p) #if (LIBTORRENT_VERSION_NUM >= 10204) void Session::handleSocks5Alert(const lt::socks5_alert *p) const { - if (p->error) { + if (p->error) + { LogMsg(tr("SOCKS5 proxy error. Message: %1").arg(QString::fromStdString(p->message())) , Log::WARNING); } diff --git a/src/base/bittorrent/speedmonitor.cpp b/src/base/bittorrent/speedmonitor.cpp index 2145aca26..592788642 100644 --- a/src/base/bittorrent/speedmonitor.cpp +++ b/src/base/bittorrent/speedmonitor.cpp @@ -36,7 +36,8 @@ SpeedMonitor::SpeedMonitor() void SpeedMonitor::addSample(const SpeedSample &sample) { - if (m_speedSamples.size() >= MAX_SAMPLES) { + if (m_speedSamples.size() >= MAX_SAMPLES) + { m_sum -= m_speedSamples.front(); } diff --git a/src/base/bittorrent/statistics.cpp b/src/base/bittorrent/statistics.cpp index c16f998f9..c692b609d 100644 --- a/src/base/bittorrent/statistics.cpp +++ b/src/base/bittorrent/statistics.cpp @@ -71,11 +71,13 @@ quint64 Statistics::getAlltimeUL() const void Statistics::gather() { const SessionStatus &ss = m_session->status(); - if (ss.totalDownload > m_sessionDL) { + if (ss.totalDownload > m_sessionDL) + { m_sessionDL = ss.totalDownload; m_dirty = true; } - if (ss.totalUpload > m_sessionUL) { + if (ss.totalUpload > m_sessionUL) + { m_sessionUL = ss.totalUpload; m_dirty = true; } diff --git a/src/base/bittorrent/torrentcreatorthread.cpp b/src/base/bittorrent/torrentcreatorthread.cpp index 87b7fd086..98d44f8be 100644 --- a/src/base/bittorrent/torrentcreatorthread.cpp +++ b/src/base/bittorrent/torrentcreatorthread.cpp @@ -59,7 +59,8 @@ namespace #if (LIBTORRENT_VERSION_NUM >= 20000) lt::create_flags_t toNativeTorrentFormatFlag(const BitTorrent::TorrentFormat torrentFormat) { - switch (torrentFormat) { + switch (torrentFormat) + { case BitTorrent::TorrentFormat::V1: return lt::create_torrent::v1_only; case BitTorrent::TorrentFormat::Hybrid: @@ -102,20 +103,24 @@ void TorrentCreatorThread::run() emit updateProgress(0); - try { + try + { const QString parentPath = Utils::Fs::branchPath(m_params.inputPath) + '/'; // Adding files to the torrent lt::file_storage fs; - if (QFileInfo(m_params.inputPath).isFile()) { + if (QFileInfo(m_params.inputPath).isFile()) + { lt::add_files(fs, Utils::Fs::toNativePath(m_params.inputPath).toStdString(), fileFilter); } - else { + else + { // need to sort the file names by natural sort order QStringList dirs = {m_params.inputPath}; QDirIterator dirIter(m_params.inputPath, (QDir::AllDirs | QDir::NoDotAndDotDot), QDirIterator::Subdirectories); - while (dirIter.hasNext()) { + while (dirIter.hasNext()) + { dirIter.next(); dirs += dirIter.filePath(); } @@ -124,11 +129,13 @@ void TorrentCreatorThread::run() QStringList fileNames; QHash fileSizeMap; - for (const auto &dir : asConst(dirs)) { + for (const auto &dir : asConst(dirs)) + { QStringList tmpNames; // natural sort files within each dir QDirIterator fileIter(dir, QDir::Files); - while (fileIter.hasNext()) { + while (fileIter.hasNext()) + { fileIter.next(); const QString relFilePath = fileIter.filePath().mid(parentPath.length()); @@ -154,14 +161,16 @@ void TorrentCreatorThread::run() #endif // Add url seeds - for (QString seed : asConst(m_params.urlSeeds)) { + for (QString seed : asConst(m_params.urlSeeds)) + { seed = seed.trimmed(); if (!seed.isEmpty()) newTorrent.add_url_seed(seed.toStdString()); } int tier = 0; - for (const QString &tracker : asConst(m_params.trackers)) { + for (const QString &tracker : asConst(m_params.trackers)) + { if (tracker.isEmpty()) ++tier; else @@ -195,16 +204,20 @@ void TorrentCreatorThread::run() // create the torrent QFile outfile {m_params.savePath}; - if (!outfile.open(QIODevice::WriteOnly)) { - throw RuntimeError {tr("Create new torrent file failed. Reason: %1") + if (!outfile.open(QIODevice::WriteOnly)) + { + throw RuntimeError + {tr("Create new torrent file failed. Reason: %1") .arg(outfile.errorString())}; } if (isInterruptionRequested()) return; lt::bencode(Utils::IO::FileDeviceOutputIterator {outfile}, entry); - if (outfile.error() != QFileDevice::NoError) { - throw RuntimeError {tr("Create new torrent file failed. Reason: %1") + if (outfile.error() != QFileDevice::NoError) + { + throw RuntimeError + {tr("Create new torrent file failed. Reason: %1") .arg(outfile.errorString())}; } outfile.close(); @@ -212,7 +225,8 @@ void TorrentCreatorThread::run() emit updateProgress(100); emit creationSuccess(m_params.savePath, parentPath); } - catch (const std::exception &e) { + catch (const std::exception &e) + { emit creationFailure(e.what()); } } diff --git a/src/base/bittorrent/torrenthandleimpl.cpp b/src/base/bittorrent/torrenthandleimpl.cpp index 14aa75aba..3aa72e760 100644 --- a/src/base/bittorrent/torrenthandleimpl.cpp +++ b/src/base/bittorrent/torrenthandleimpl.cpp @@ -126,10 +126,12 @@ TorrentHandleImpl::TorrentHandleImpl(Session *session, const lt::torrent_handle updateStatus(); m_hash = InfoHash(m_nativeStatus.info_hash); - if (hasMetadata()) { + if (hasMetadata()) + { applyFirstLastPiecePriority(m_hasFirstLastPiecePriority); - if (!params.restored) { + if (!params.restored) + { if (filesCount() == 1) m_hasRootFolder = false; } @@ -138,11 +140,13 @@ TorrentHandleImpl::TorrentHandleImpl(Session *session, const lt::torrent_handle // TODO: Remove the following upgrade code in v.4.4 // == BEGIN UPGRADE CODE == const QString spath = actualStorageLocation(); - for (int i = 0; i < filesCount(); ++i) { + for (int i = 0; i < filesCount(); ++i) + { const QString filepath = filePath(i); // Move "unwanted" files back to their original folder const QString parentRelPath = Utils::Fs::branchPath(filepath); - if (QDir(parentRelPath).dirName() == ".unwanted") { + if (QDir(parentRelPath).dirName() == ".unwanted") + { const QString oldName = Utils::Fs::fileName(filepath); const QString newRelPath = Utils::Fs::branchPath(parentRelPath); if (newRelPath.isEmpty()) @@ -178,7 +182,8 @@ QString TorrentHandleImpl::name() const name = QString::fromStdString(m_nativeStatus.name); if (!name.isEmpty()) return name; - if (hasMetadata()) { + if (hasMetadata()) + { name = QString::fromStdString(m_torrentInfo.nativeInfo()->orig_files().name()); if (!name.isEmpty()) return name; } @@ -330,8 +335,10 @@ void TorrentHandleImpl::addTrackers(const QVector &trackers) QVector newTrackers; newTrackers.reserve(trackers.size()); - for (const TrackerEntry &tracker : trackers) { - if (!currentTrackers.contains(tracker)) { + for (const TrackerEntry &tracker : trackers) + { + if (!currentTrackers.contains(tracker)) + { m_nativeHandle.add_tracker(tracker.nativeEntry()); newTrackers << tracker; } @@ -351,7 +358,8 @@ void TorrentHandleImpl::replaceTrackers(const QVector &trackers) std::vector nativeTrackers; nativeTrackers.reserve(trackers.size()); - for (const TrackerEntry &tracker : trackers) { + for (const TrackerEntry &tracker : trackers) + { nativeTrackers.emplace_back(tracker.nativeEntry()); if (!currentTrackers.removeOne(tracker)) @@ -360,11 +368,13 @@ void TorrentHandleImpl::replaceTrackers(const QVector &trackers) m_nativeHandle.replace_trackers(nativeTrackers); - if (newTrackers.isEmpty() && currentTrackers.isEmpty()) { + if (newTrackers.isEmpty() && currentTrackers.isEmpty()) + { // when existing tracker reorders m_session->handleTorrentTrackersChanged(this); } - else { + else + { if (!currentTrackers.isEmpty()) m_session->handleTorrentTrackersRemoved(this, currentTrackers); @@ -398,9 +408,11 @@ void TorrentHandleImpl::addUrlSeeds(const QVector &urlSeeds) QVector addedUrlSeeds; addedUrlSeeds.reserve(urlSeeds.size()); - for (const QUrl &url : urlSeeds) { + for (const QUrl &url : urlSeeds) + { const std::string nativeUrl = url.toString().toStdString(); - if (currentSeeds.find(nativeUrl) == currentSeeds.end()) { + if (currentSeeds.find(nativeUrl) == currentSeeds.end()) + { m_nativeHandle.add_url_seed(nativeUrl); addedUrlSeeds << url; } @@ -417,9 +429,11 @@ void TorrentHandleImpl::removeUrlSeeds(const QVector &urlSeeds) QVector removedUrlSeeds; removedUrlSeeds.reserve(urlSeeds.size()); - for (const QUrl &url : urlSeeds) { + for (const QUrl &url : urlSeeds) + { const std::string nativeUrl = url.toString().toStdString(); - if (currentSeeds.find(nativeUrl) != currentSeeds.end()) { + if (currentSeeds.find(nativeUrl) != currentSeeds.end()) + { m_nativeHandle.remove_url_seed(nativeUrl); removedUrlSeeds << url; } @@ -443,10 +457,12 @@ bool TorrentHandleImpl::connectPeer(const PeerAddress &peerAddress) if (ec) return false; const lt::tcp::endpoint endpoint(addr, peerAddress.port); - try { + try + { m_nativeHandle.connect_peer(endpoint); } - catch (const lt::system_error &err) { + catch (const lt::system_error &err) + { LogMsg(tr("Failed to add peer \"%1\" to torrent \"%2\". Reason: %3") .arg(peerAddress.toString(), name(), QString::fromLocal8Bit(err.what())), Log::WARNING); return false; @@ -533,7 +549,8 @@ bool TorrentHandleImpl::addTag(const QString &tag) if (!Session::isValidTag(tag)) return false; - if (!hasTag(tag)) { + if (!hasTag(tag)) + { if (!m_session->hasTag(tag)) if (!m_session->addTag(tag)) return false; @@ -546,7 +563,8 @@ bool TorrentHandleImpl::addTag(const QString &tag) bool TorrentHandleImpl::removeTag(const QString &tag) { - if (m_tags.remove(tag)) { + if (m_tags.remove(tag)) + { m_session->handleTorrentTagRemoved(this, tag); return true; } @@ -719,25 +737,31 @@ TorrentState TorrentHandleImpl::state() const void TorrentHandleImpl::updateState() { - if (m_nativeStatus.state == lt::torrent_status::checking_resume_data) { + if (m_nativeStatus.state == lt::torrent_status::checking_resume_data) + { m_state = TorrentState::CheckingResumeData; } - else if (isMoveInProgress()) { + else if (isMoveInProgress()) + { m_state = TorrentState::Moving; } - else if (hasMissingFiles()) { + else if (hasMissingFiles()) + { m_state = TorrentState::MissingFiles; } - else if (hasError()) { + else if (hasError()) + { m_state = TorrentState::Error; } else if ((m_nativeStatus.state == lt::torrent_status::checking_files) && (!isPaused() || (m_nativeStatus.flags & lt::torrent_flags::auto_managed) - || !(m_nativeStatus.flags & lt::torrent_flags::paused))) { + || !(m_nativeStatus.flags & lt::torrent_flags::paused))) + { // If the torrent is not just in the "checking" state, but is being actually checked m_state = m_hasSeedStatus ? TorrentState::CheckingUploading : TorrentState::CheckingDownloading; } - else if (isSeed()) { + else if (isSeed()) + { if (isPaused()) m_state = TorrentState::PausedUploading; else if (m_session->isQueueingSystemEnabled() && isQueued()) @@ -749,7 +773,8 @@ void TorrentHandleImpl::updateState() else m_state = TorrentState::StalledUploading; } - else { + else + { if (isPaused()) m_state = TorrentState::PausedDownloading; else if (m_nativeStatus.state == lt::torrent_status::downloading_metadata) @@ -832,14 +857,16 @@ qlonglong TorrentHandleImpl::eta() const const SpeedSampleAvg speedAverage = m_speedMonitor.average(); - if (isSeed()) { + if (isSeed()) + { const qreal maxRatioValue = maxRatio(); const int maxSeedingTimeValue = maxSeedingTime(); if ((maxRatioValue < 0) && (maxSeedingTimeValue < 0)) return MAX_ETA; qlonglong ratioEta = MAX_ETA; - if ((speedAverage.upload > 0) && (maxRatioValue >= 0)) { + if ((speedAverage.upload > 0) && (maxRatioValue >= 0)) + { qlonglong realDL = totalDownload(); if (realDL <= 0) @@ -850,7 +877,8 @@ qlonglong TorrentHandleImpl::eta() const qlonglong seedingTimeEta = MAX_ETA; - if (maxSeedingTimeValue >= 0) { + if (maxSeedingTimeValue >= 0) + { seedingTimeEta = (maxSeedingTimeValue * 60) - seedingTime(); if (seedingTimeEta < 0) seedingTimeEta = 0; @@ -872,7 +900,8 @@ QVector TorrentHandleImpl::filesProgress() const const int count = static_cast(fp.size()); QVector result; result.reserve(count); - for (int i = 0; i < count; ++i) { + for (int i = 0; i < count; ++i) + { const qlonglong size = fileSize(i); if ((size <= 0) || (fp[i] == size)) result << 1; @@ -995,7 +1024,8 @@ QVector TorrentHandleImpl::peers() const QBitArray TorrentHandleImpl::pieces() const { QBitArray result(m_nativeStatus.pieces.size()); - for (int i = 0; i < result.size(); ++i) { + for (int i = 0; i < result.size(); ++i) + { if (m_nativeStatus.pieces[lt::piece_index_t {i}]) result.setBit(i, true); } @@ -1097,7 +1127,8 @@ qlonglong TorrentHandleImpl::nextAnnounce() const void TorrentHandleImpl::setName(const QString &name) { - if (m_name != name) { + if (m_name != name) + { m_name = name; m_session->handleTorrentNameChanged(this); } @@ -1105,7 +1136,8 @@ void TorrentHandleImpl::setName(const QString &name) bool TorrentHandleImpl::setCategory(const QString &category) { - if (m_category != category) { + if (m_category != category) + { if (!category.isEmpty() && !m_session->categories().contains(category)) return false; @@ -1113,7 +1145,8 @@ bool TorrentHandleImpl::setCategory(const QString &category) m_category = category; m_session->handleTorrentCategoryChanged(this, oldCategory); - if (m_useAutoTMM) { + if (m_useAutoTMM) + { if (!m_session->isDisableAutoTMMWhenCategoryChanged()) move_impl(m_session->categorySavePath(m_category), MoveStorageMode::Overwrite); else @@ -1126,7 +1159,8 @@ bool TorrentHandleImpl::setCategory(const QString &category) void TorrentHandleImpl::move(QString path) { - if (m_useAutoTMM) { + if (m_useAutoTMM) + { m_useAutoTMM = false; m_session->handleTorrentSavingModeChanged(this); } @@ -1145,10 +1179,12 @@ void TorrentHandleImpl::move_impl(QString path, const MoveStorageMode mode) if (path == savePath()) return; path = Utils::Fs::toNativePath(path); - if (!useTempPath()) { + if (!useTempPath()) + { moveStorage(path, mode); } - else { + else + { m_savePath = path; m_session->handleTorrentSavePathChanged(this); } @@ -1172,7 +1208,8 @@ void TorrentHandleImpl::forceRecheck() m_hasMissingFiles = false; m_unchecked = false; - if (isPaused()) { + if (isPaused()) + { // When "force recheck" is applied on paused torrent, we temporarily resume it // (really we just allow libtorrent to resume it by enabling auto management for it). m_nativeHandle.set_flags(lt::torrent_flags::stop_when_ready | lt::torrent_flags::auto_managed); @@ -1181,11 +1218,13 @@ void TorrentHandleImpl::forceRecheck() void TorrentHandleImpl::setSequentialDownload(const bool enable) { - if (enable) { + if (enable) + { m_nativeHandle.set_flags(lt::torrent_flags::sequential_download); m_nativeStatus.flags |= lt::torrent_flags::sequential_download; // prevent return cached value } - else { + else + { m_nativeHandle.unset_flags(lt::torrent_flags::sequential_download); m_nativeStatus.flags &= ~lt::torrent_flags::sequential_download; // prevent return cached value } @@ -1220,7 +1259,8 @@ void TorrentHandleImpl::applyFirstLastPiecePriority(const bool enabled, const QV // Updating file priorities is an async operation in libtorrent, when we just updated it and immediately query it // we might get the old/wrong values, so we rely on `updatedFilePrio` in this case. - for (int index = 0; index < static_cast(filePriorities.size()); ++index) { + for (int index = 0; index < static_cast(filePriorities.size()); ++index) + { const lt::download_priority_t filePrio = filePriorities[index]; if (filePrio <= lt::download_priority_t {0}) continue; @@ -1231,7 +1271,8 @@ void TorrentHandleImpl::applyFirstLastPiecePriority(const bool enabled, const QV // worst case: AVI index = 1% of total file size (at the end of the file) const int nNumPieces = std::ceil(fileSize(index) * 0.01 / pieceLength()); - for (int i = 0; i < nNumPieces; ++i) { + for (int i = 0; i < nNumPieces; ++i) + { piecePriorities[extremities.first() + i] = newPrio; piecePriorities[extremities.last() - i] = newPrio; } @@ -1247,7 +1288,8 @@ void TorrentHandleImpl::pause() m_speedMonitor.reset(); - if (!m_isStopped) { + if (!m_isStopped) + { m_isStopped = true; m_session->handleTorrentPaused(this); } @@ -1258,12 +1300,14 @@ void TorrentHandleImpl::resume(const TorrentOperatingMode mode) if (hasError()) m_nativeHandle.clear_error(); - if (m_hasMissingFiles) { + if (m_hasMissingFiles) + { m_hasMissingFiles = false; m_nativeHandle.force_recheck(); } - if (m_isStopped) { + if (m_isStopped) + { // Torrent may have been temporarily resumed to perform checking files // so we have to ensure it will not pause after checking is done. m_nativeHandle.unset_flags(lt::torrent_flags::stop_when_ready); @@ -1275,7 +1319,8 @@ void TorrentHandleImpl::resume(const TorrentOperatingMode mode) m_operatingMode = mode; - if (m_isStopped) { + if (m_isStopped) + { m_isStopped = false; m_session->handleTorrentResumed(this); } @@ -1283,7 +1328,8 @@ void TorrentHandleImpl::resume(const TorrentOperatingMode mode) void TorrentHandleImpl::moveStorage(const QString &newPath, const MoveStorageMode mode) { - if (m_session->addMoveTorrentStorageJob(this, newPath, mode)) { + if (m_session->addMoveTorrentStorageJob(this, newPath, mode)) + { m_storageIsMoving = true; updateStatus(); } @@ -1307,7 +1353,8 @@ void TorrentHandleImpl::handleMoveStorageJobFinished(const bool hasOutstandingJo updateStatus(); const QString newPath = QString::fromStdString(m_nativeStatus.save_path); - if (!useTempPath() && (newPath != m_savePath)) { + if (!useTempPath() && (newPath != m_savePath)) + { m_savePath = newPath; m_session->handleTorrentSavePathChanged(this); } @@ -1363,14 +1410,16 @@ void TorrentHandleImpl::handleTorrentCheckedAlert(const lt::torrent_checked_aler Q_UNUSED(p); qDebug("\"%s\" have just finished checking", qUtf8Printable(name())); - if (m_fastresumeDataRejected && !m_hasMissingFiles) { + if (m_fastresumeDataRejected && !m_hasMissingFiles) + { saveResumeData(); m_fastresumeDataRejected = false; } updateStatus(); - if (!m_hasMissingFiles) { + if (!m_hasMissingFiles) + { if ((progress() < 1.0) && (wantedSize() > 0)) m_hasSeedStatus = false; else if (progress() == 1.0) @@ -1398,12 +1447,14 @@ void TorrentHandleImpl::handleTorrentFinishedAlert(const lt::torrent_finished_al manageIncompleteFiles(); const bool recheckTorrentsOnCompletion = Preferences::instance()->recheckTorrentsOnCompletion(); - if (isMoveInProgress() || (m_renameCount > 0)) { + if (isMoveInProgress() || (m_renameCount > 0)) + { if (recheckTorrentsOnCompletion) m_moveFinishedTriggers.append([this]() { forceRecheck(); }); m_moveFinishedTriggers.append([this]() { m_session->handleTorrentFinished(this); }); } - else { + else + { if (recheckTorrentsOnCompletion && m_unchecked) forceRecheck(); m_session->handleTorrentFinished(this); @@ -1422,18 +1473,22 @@ void TorrentHandleImpl::handleTorrentResumedAlert(const lt::torrent_resumed_aler void TorrentHandleImpl::handleSaveResumeDataAlert(const lt::save_resume_data_alert *p) { - if (p && !m_hasMissingFiles) { + if (p && !m_hasMissingFiles) + { // Update recent resume data m_ltAddTorrentParams = p->params; } - if (!m_isStopped) { + if (!m_isStopped) + { // Torrent can be actually "running" but temporarily "paused" to perform some // service jobs behind the scenes so we need to restore it as "running" - if (m_operatingMode == TorrentOperatingMode::AutoManaged) { + if (m_operatingMode == TorrentOperatingMode::AutoManaged) + { m_ltAddTorrentParams.flags |= lt::torrent_flags::auto_managed; } - else { + else + { m_ltAddTorrentParams.flags &= ~lt::torrent_flags::paused; m_ltAddTorrentParams.flags &= ~lt::torrent_flags::auto_managed; } @@ -1449,7 +1504,8 @@ void TorrentHandleImpl::handleSaveResumeDataAlert(const lt::save_resume_data_ale // TODO: The following code is deprecated. Remove after several releases in 4.3.x. // === BEGIN DEPRECATED CODE === // const bool useDummyResumeData = !p; - if (useDummyResumeData) { + if (useDummyResumeData) + { updateStatus(); resumeData["qBt-magnetUri"] = createMagnetURI().toStdString(); @@ -1489,12 +1545,14 @@ void TorrentHandleImpl::handleFastResumeRejectedAlert(const lt::fastresume_rejec { m_fastresumeDataRejected = true; - if (p->error.value() == lt::errors::mismatching_file_size) { + if (p->error.value() == lt::errors::mismatching_file_size) + { // Mismatching file size (files were probably moved) m_hasMissingFiles = true; LogMsg(tr("File sizes mismatch for torrent '%1'. Cannot proceed further.").arg(name()), Log::CRITICAL); } - else { + else + { LogMsg(tr("Fast resume data was rejected for torrent '%1'. Reason: %2. Checking again...") .arg(name(), QString::fromStdString(p->message())), Log::WARNING); } @@ -1527,13 +1585,15 @@ void TorrentHandleImpl::handleFileRenamedAlert(const lt::file_renamed_alert *p) #endif int pathIdx = 0; - while ((pathIdx < oldPathParts.size()) && (pathIdx < newPathParts.size())) { + while ((pathIdx < oldPathParts.size()) && (pathIdx < newPathParts.size())) + { if (oldPathParts[pathIdx].compare(newPathParts[pathIdx], caseSensitivity) != 0) break; ++pathIdx; } - for (int i = (oldPathParts.size() - 1); i >= pathIdx; --i) { + for (int i = (oldPathParts.size() - 1); i >= pathIdx; --i) + { QDir().rmdir(savePath() + Utils::String::join(oldPathParts, QLatin1String("/"))); oldPathParts.removeLast(); } @@ -1571,9 +1631,11 @@ void TorrentHandleImpl::handleFileCompletedAlert(const lt::file_completed_alert m_torrentInfo = TorrentInfo {m_nativeHandle.torrent_file()}; qDebug("A file completed download in torrent \"%s\"", qUtf8Printable(name())); - if (m_session->isAppendExtensionEnabled()) { + if (m_session->isAppendExtensionEnabled()) + { QString name = filePath(static_cast>(p->index)); - if (name.endsWith(QB_EXT)) { + if (name.endsWith(QB_EXT)) + { const QString oldName = name; name.chop(QB_EXT.size()); qDebug("Renaming %s to %s", qUtf8Printable(oldName), qUtf8Printable(name)); @@ -1627,7 +1689,8 @@ void TorrentHandleImpl::handleAppendExtensionToggled() void TorrentHandleImpl::handleAlert(const lt::alert *a) { - switch (a->type()) { + switch (a->type()) + { case lt::file_renamed_alert::alert_type: handleFileRenamedAlert(static_cast(a)); break; @@ -1680,22 +1743,28 @@ void TorrentHandleImpl::manageIncompleteFiles() { const bool isAppendExtensionEnabled = m_session->isAppendExtensionEnabled(); const QVector fp = filesProgress(); - if (fp.size() != filesCount()) { + if (fp.size() != filesCount()) + { qDebug() << "skip manageIncompleteFiles because of invalid torrent meta-data or empty file-progress"; return; } - for (int i = 0; i < filesCount(); ++i) { + for (int i = 0; i < filesCount(); ++i) + { QString name = filePath(i); - if (isAppendExtensionEnabled && (fileSize(i) > 0) && (fp[i] < 1)) { - if (!name.endsWith(QB_EXT)) { + if (isAppendExtensionEnabled && (fileSize(i) > 0) && (fp[i] < 1)) + { + if (!name.endsWith(QB_EXT)) + { const QString newName = name + QB_EXT; qDebug() << "Renaming" << name << "to" << newName; renameFile(i, newName); } } - else { - if (name.endsWith(QB_EXT)) { + else + { + if (name.endsWith(QB_EXT)) + { const QString oldName = name; name.chop(QB_EXT.size()); qDebug() << "Renaming" << oldName << "to" << name; @@ -1722,8 +1791,10 @@ void TorrentHandleImpl::adjustActualSavePath_impl() if (targetDir == currentDir) return; - if (!needUseTempDir) { - if ((currentDir == tempDir) && (currentDir != QDir {m_session->tempPath()})) { + if (!needUseTempDir) + { + if ((currentDir == tempDir) && (currentDir != QDir {m_session->tempPath()})) + { // torrent without root folder still has it in its temporary save path // so its temp path isn't equal to temp path root const QString currentDirPath = currentDir.absolutePath(); @@ -1790,7 +1861,8 @@ void TorrentHandleImpl::setRatioLimit(qreal limit) else if (limit > MAX_RATIO) limit = MAX_RATIO; - if (m_ratioLimit != limit) { + if (m_ratioLimit != limit) + { m_ratioLimit = limit; m_session->handleTorrentShareLimitChanged(this); } @@ -1803,7 +1875,8 @@ void TorrentHandleImpl::setSeedingTimeLimit(int limit) else if (limit > MAX_SEEDING_TIME) limit = MAX_SEEDING_TIME; - if (m_seedingTimeLimit != limit) { + if (m_seedingTimeLimit != limit) + { m_seedingTimeLimit = limit; m_session->handleTorrentShareLimitChanged(this); } @@ -1846,10 +1919,12 @@ void TorrentHandleImpl::prioritizeFiles(const QVector &priorit // 'torrent_finished_alert' and eg show tray notifications const QVector progress = filesProgress(); const QVector oldPriorities = filePriorities(); - for (int i = 0; i < oldPriorities.size(); ++i) { + for (int i = 0; i < oldPriorities.size(); ++i) + { if ((oldPriorities[i] == DownloadPriority::Ignored) && (priorities[i] > DownloadPriority::Ignored) - && (progress[i] < 1.0)) { + && (progress[i] < 1.0)) + { m_hasSeedStatus = false; break; } @@ -1875,7 +1950,8 @@ QVector TorrentHandleImpl::availableFileFractions() const QVector res; res.reserve(filesCount); const TorrentInfo info = this->info(); - for (int i = 0; i < filesCount; ++i) { + for (int i = 0; i < filesCount; ++i) + { const TorrentInfo::PieceRange filePieces = info.filePieces(i); int availablePieces = 0; diff --git a/src/base/bittorrent/torrentinfo.cpp b/src/base/bittorrent/torrentinfo.cpp index a6f44c873..d49061be8 100644 --- a/src/base/bittorrent/torrentinfo.cpp +++ b/src/base/bittorrent/torrentinfo.cpp @@ -77,14 +77,16 @@ TorrentInfo TorrentInfo::load(const QByteArray &data, QString *error) noexcept lt::error_code ec; const lt::bdecode_node node = lt::bdecode(data, ec , nullptr, depthLimit, tokenLimit); - if (ec) { + if (ec) + { if (error) *error = QString::fromStdString(ec.message()); return TorrentInfo(); } TorrentInfo info {std::shared_ptr(new lt::torrent_info(node, ec))}; - if (ec) { + if (ec) + { if (error) *error = QString::fromStdString(ec.message()); return TorrentInfo(); @@ -99,28 +101,33 @@ TorrentInfo TorrentInfo::loadFromFile(const QString &path, QString *error) noexc error->clear(); QFile file {path}; - if (!file.open(QIODevice::ReadOnly)) { + if (!file.open(QIODevice::ReadOnly)) + { if (error) *error = file.errorString(); return TorrentInfo(); } - if (file.size() > MAX_TORRENT_SIZE) { + if (file.size() > MAX_TORRENT_SIZE) + { if (error) *error = tr("File size exceeds max limit %1").arg(Utils::Misc::friendlyUnit(MAX_TORRENT_SIZE)); return TorrentInfo(); } QByteArray data; - try { + try + { data = file.readAll(); } - catch (const std::bad_alloc &e) { + catch (const std::bad_alloc &e) + { if (error) *error = tr("Torrent file read error: %1").arg(e.what()); return TorrentInfo(); } - if (data.size() != file.size()) { + if (data.size() != file.size()) + { if (error) *error = tr("Torrent file read error: size mismatch"); return TorrentInfo(); @@ -284,7 +291,8 @@ QVector TorrentInfo::urlSeeds() const QVector urlSeeds; urlSeeds.reserve(nativeWebSeeds.size()); - for (const lt::web_seed_entry &webSeed : nativeWebSeeds) { + for (const lt::web_seed_entry &webSeed : nativeWebSeeds) + { if (webSeed.type == lt::web_seed_entry::url_seed) urlSeeds.append(QUrl(webSeed.url.c_str())); } @@ -353,7 +361,8 @@ TorrentInfo::PieceRange TorrentInfo::filePieces(const QString &file) const return {}; const int index = fileIndex(file); - if (index == -1) { + if (index == -1) + { qDebug() << "Filename" << file << "was not found in torrent" << name(); return {}; } @@ -365,7 +374,8 @@ TorrentInfo::PieceRange TorrentInfo::filePieces(const int fileIndex) const if (!isValid()) return {}; - if ((fileIndex < 0) || (fileIndex >= filesCount())) { + if ((fileIndex < 0) || (fileIndex >= filesCount())) + { qDebug() << "File index (" << fileIndex << ") is out of range for torrent" << name(); return {}; } @@ -402,7 +412,8 @@ int TorrentInfo::fileIndex(const QString &fileName) const QString TorrentInfo::rootFolder() const { QString rootFolder; - for (int i = 0; i < filesCount(); ++i) { + for (int i = 0; i < filesCount(); ++i) + { const QString filePath = this->filePath(i); if (QDir::isAbsolutePath(filePath)) continue; @@ -433,7 +444,8 @@ void TorrentInfo::stripRootFolder() // Solution for case of renamed root folder const QString path = filePath(0); const std::string newName = path.left(path.indexOf('/')).toStdString(); - if (files.name() != newName) { + if (files.name() != newName) + { files.set_name(newName); for (int i = 0; i < files.num_files(); ++i) files.rename_file(lt::file_index_t {i}, files.file_path(lt::file_index_t {i})); diff --git a/src/base/bittorrent/tracker.cpp b/src/base/bittorrent/tracker.cpp index bbf059e0c..212d50616 100644 --- a/src/base/bittorrent/tracker.cpp +++ b/src/base/bittorrent/tracker.cpp @@ -92,9 +92,11 @@ namespace QByteArray toBigEndianByteArray(const QHostAddress &addr) { // translate IP address to a sequence of bytes in big-endian order - switch (addr.protocol()) { + switch (addr.protocol()) + { case QAbstractSocket::IPv4Protocol: - case QAbstractSocket::AnyIPProtocol: { + case QAbstractSocket::AnyIPProtocol: + { const quint32 ipv4 = addr.toIPv4Address(); QByteArray ret; ret.append(static_cast((ipv4 >> 24) & 0xFF)) @@ -104,7 +106,8 @@ namespace return ret; } - case QAbstractSocket::IPv6Protocol: { + case QAbstractSocket::IPv6Protocol: + { const Q_IPV6ADDR ipv6 = addr.toIPv6Address(); QByteArray ret; for (const quint8 i : ipv6.c) @@ -162,7 +165,8 @@ struct Tracker::TrackerAnnounceRequest void Tracker::TorrentStats::setPeer(const Peer &peer) { // always replace existing peer - if (!removePeer(peer)) { + if (!removePeer(peer)) + { // Too many peers, remove a random one if (peers.size() >= MAX_PEERS_PER_TORRENT) removePeer(*peers.begin()); @@ -198,8 +202,10 @@ bool Tracker::start() const QHostAddress ip = QHostAddress::Any; const int port = Preferences::instance()->getTrackerPort(); - if (m_server->isListening()) { - if (m_server->serverPort() == port) { + if (m_server->isListening()) + { + if (m_server->serverPort() == port) + { // Already listening on the right port, just return return true; } @@ -211,11 +217,13 @@ bool Tracker::start() // Listen on the predefined port const bool listenSuccess = m_server->listen(ip, port); - if (listenSuccess) { + if (listenSuccess) + { LogMsg(tr("Embedded Tracker: Now listening on IP: %1, port: %2") .arg(ip.toString(), QString::number(port)), Log::INFO); } - else { + else + { LogMsg(tr("Embedded Tracker: Unable to bind to IP: %1, port: %2. Reason: %3") .arg(ip.toString(), QString::number(port), m_server->errorString()) , Log::WARNING); @@ -233,7 +241,8 @@ Http::Response Tracker::processRequest(const Http::Request &request, const Http: status(200); - try { + try + { // Is it a GET request? if (request.method != Http::HEADER_REQUEST_METHOD_GET) throw MethodNotAllowedHTTPError(); @@ -243,16 +252,19 @@ Http::Response Tracker::processRequest(const Http::Request &request, const Http: else throw NotFoundHTTPError(); } - catch (const HTTPError &error) { + catch (const HTTPError &error) + { status(error.statusCode(), error.statusText()); if (!error.message().isEmpty()) print(error.message(), Http::CONTENT_TYPE_TXT); } - catch (const TrackerError &error) { + catch (const TrackerError &error) + { clear(); // clear response status(200); - const lt::entry::dictionary_type bencodedEntry = { + const lt::entry::dictionary_type bencodedEntry = + { {ANNOUNCE_RESPONSE_FAILURE_REASON, {error.what()}} }; QByteArray reply; @@ -312,7 +324,8 @@ void Tracker::processAnnounceRequest() // 4. numwant const auto numWantIter = queryParams.find(ANNOUNCE_REQUEST_NUM_WANT); - if (numWantIter != queryParams.end()) { + if (numWantIter != queryParams.end()) + { const int num = numWantIter->toInt(); if (num < 0) throw TrackerError("Invalid \"numwant\" parameter"); @@ -348,15 +361,18 @@ void Tracker::processAnnounceRequest() || (announceReq.event == ANNOUNCE_REQUEST_EVENT_EMPTY) || (announceReq.event == ANNOUNCE_REQUEST_EVENT_COMPLETED) || (announceReq.event == ANNOUNCE_REQUEST_EVENT_STARTED) - || (announceReq.event == ANNOUNCE_REQUEST_EVENT_PAUSED)) { + || (announceReq.event == ANNOUNCE_REQUEST_EVENT_PAUSED)) + { // [BEP-21] Extension for partial seeds // (partial support - we don't support BEP-48 so the part that concerns that is not supported) registerPeer(announceReq); } - else if (announceReq.event == ANNOUNCE_REQUEST_EVENT_STOPPED) { + else if (announceReq.event == ANNOUNCE_REQUEST_EVENT_STOPPED) + { unregisterPeer(announceReq); } - else { + else + { throw TrackerError("Invalid \"event\" parameter"); } @@ -365,7 +381,8 @@ void Tracker::processAnnounceRequest() void Tracker::registerPeer(const TrackerAnnounceRequest &announceReq) { - if (!m_torrents.contains(announceReq.infoHash)) { + if (!m_torrents.contains(announceReq.infoHash)) + { // Reached max size, remove a random torrent if (m_torrents.size() >= MAX_TORRENTS) m_torrents.erase(m_torrents.begin()); @@ -390,7 +407,8 @@ void Tracker::prepareAnnounceResponse(const TrackerAnnounceRequest &announceReq) { const TorrentStats &torrentStats = m_torrents[announceReq.infoHash]; - lt::entry::dictionary_type replyDict { + lt::entry::dictionary_type replyDict + { {ANNOUNCE_RESPONSE_INTERVAL, ANNOUNCE_INTERVAL}, {ANNOUNCE_RESPONSE_COMPLETE, torrentStats.seeders}, {ANNOUNCE_RESPONSE_INCOMPLETE, (torrentStats.peers.size() - torrentStats.seeders)}, @@ -402,13 +420,16 @@ void Tracker::prepareAnnounceResponse(const TrackerAnnounceRequest &announceReq) // peer list // [BEP-7] IPv6 Tracker Extension (partial support - only the part that concerns BEP-23) // [BEP-23] Tracker Returns Compact Peer Lists - if (announceReq.compact) { + if (announceReq.compact) + { lt::entry::string_type peers; lt::entry::string_type peers6; - if (announceReq.event != ANNOUNCE_REQUEST_EVENT_STOPPED) { + if (announceReq.event != ANNOUNCE_REQUEST_EVENT_STOPPED) + { int counter = 0; - for (const Peer &peer : asConst(torrentStats.peers)) { + for (const Peer &peer : asConst(torrentStats.peers)) + { if (counter++ >= announceReq.numwant) break; @@ -423,16 +444,20 @@ void Tracker::prepareAnnounceResponse(const TrackerAnnounceRequest &announceReq) if (!peers6.empty()) replyDict[ANNOUNCE_RESPONSE_PEERS6] = peers6; } - else { + else + { lt::entry::list_type peerList; - if (announceReq.event != ANNOUNCE_REQUEST_EVENT_STOPPED) { + if (announceReq.event != ANNOUNCE_REQUEST_EVENT_STOPPED) + { int counter = 0; - for (const Peer &peer : torrentStats.peers) { + for (const Peer &peer : torrentStats.peers) + { if (counter++ >= announceReq.numwant) break; - lt::entry::dictionary_type peerDict = { + lt::entry::dictionary_type peerDict = + { {ANNOUNCE_RESPONSE_PEERS_IP, peer.address}, {ANNOUNCE_RESPONSE_PEERS_PORT, peer.port} }; diff --git a/src/base/bittorrent/trackerentry.cpp b/src/base/bittorrent/trackerentry.cpp index 61b359012..59b9d0a5a 100644 --- a/src/base/bittorrent/trackerentry.cpp +++ b/src/base/bittorrent/trackerentry.cpp @@ -107,7 +107,8 @@ void TrackerEntry::setTier(const int value) int TrackerEntry::numSeeds() const { int value = -1; - for (const lt::announce_endpoint &endpoint : nativeEntry().endpoints) { + for (const lt::announce_endpoint &endpoint : nativeEntry().endpoints) + { #if (LIBTORRENT_VERSION_NUM >= 20000) for (const lt::announce_infohash &infoHash : endpoint.info_hashes) value = std::max(value, infoHash.scrape_complete); @@ -121,7 +122,8 @@ int TrackerEntry::numSeeds() const int TrackerEntry::numLeeches() const { int value = -1; - for (const lt::announce_endpoint &endpoint : nativeEntry().endpoints) { + for (const lt::announce_endpoint &endpoint : nativeEntry().endpoints) + { #if (LIBTORRENT_VERSION_NUM >= 20000) for (const lt::announce_infohash &infoHash : endpoint.info_hashes) value = std::max(value, infoHash.scrape_incomplete); @@ -135,7 +137,8 @@ int TrackerEntry::numLeeches() const int TrackerEntry::numDownloaded() const { int value = -1; - for (const lt::announce_endpoint &endpoint : nativeEntry().endpoints) { + for (const lt::announce_endpoint &endpoint : nativeEntry().endpoints) + { #if (LIBTORRENT_VERSION_NUM >= 20000) for (const lt::announce_infohash &infoHash : endpoint.info_hashes) value = std::max(value, infoHash.scrape_downloaded); diff --git a/src/base/filesystemwatcher.cpp b/src/base/filesystemwatcher.cpp index 90dd49204..fd1b19fff 100644 --- a/src/base/filesystemwatcher.cpp +++ b/src/base/filesystemwatcher.cpp @@ -76,7 +76,8 @@ void FileSystemWatcher::addPath(const QString &path) if (!dir.exists()) return; // Check if the path points to a network file system or not - if (Utils::Fs::isNetworkFileSystem(path)) { + if (Utils::Fs::isNetworkFileSystem(path)) + { // Network mode LogMsg(tr("Watching remote folder: \"%1\"").arg(Utils::Fs::toNativePath(path))); m_watchedFolders << dir; @@ -94,7 +95,8 @@ void FileSystemWatcher::addPath(const QString &path) void FileSystemWatcher::removePath(const QString &path) { - if (m_watchedFolders.removeOne(path)) { + if (m_watchedFolders.removeOne(path)) + { if (m_watchedFolders.isEmpty()) m_watchTimer.stop(); return; @@ -125,12 +127,14 @@ void FileSystemWatcher::processPartialTorrents() if (!QFile::exists(torrentPath)) return true; - if (BitTorrent::TorrentInfo::loadFromFile(torrentPath).isValid()) { + if (BitTorrent::TorrentInfo::loadFromFile(torrentPath).isValid()) + { noLongerPartial << torrentPath; return true; } - if (value >= MAX_PARTIAL_RETRIES) { + if (value >= MAX_PARTIAL_RETRIES) + { QFile::rename(torrentPath, torrentPath + ".qbt_rejected"); return true; } @@ -140,11 +144,13 @@ void FileSystemWatcher::processPartialTorrents() }); // Stop the partial timer if necessary - if (m_partialTorrents.empty()) { + if (m_partialTorrents.empty()) + { m_partialTorrentTimer.stop(); qDebug("No longer any partial torrent."); } - else { + else + { qDebug("Still %d partial torrents after delayed processing.", m_partialTorrents.count()); m_partialTorrentTimer.start(WATCH_INTERVAL); } @@ -158,7 +164,8 @@ void FileSystemWatcher::processTorrentsInDir(const QDir &dir) { QStringList torrents; const QStringList files = dir.entryList({"*.torrent", "*.magnet"}, QDir::Files); - for (const QString &file : files) { + for (const QString &file : files) + { const QString fileAbsPath = dir.absoluteFilePath(file); if (file.endsWith(".magnet", Qt::CaseInsensitive)) torrents << fileAbsPath; diff --git a/src/base/http/connection.cpp b/src/base/http/connection.cpp index fe3685be1..64a3f6a3e 100644 --- a/src/base/http/connection.cpp +++ b/src/base/http/connection.cpp @@ -59,13 +59,17 @@ void Connection::read() m_idleTimer.restart(); m_receivedData.append(m_socket->readAll()); - while (!m_receivedData.isEmpty()) { + while (!m_receivedData.isEmpty()) + { const RequestParser::ParseResult result = RequestParser::parse(m_receivedData); - switch (result.status) { - case RequestParser::ParseStatus::Incomplete: { + switch (result.status) + { + case RequestParser::ParseStatus::Incomplete: + { const long bufferLimit = RequestParser::MAX_CONTENT_SIZE * 1.1; // some margin for headers - if (m_receivedData.size() > bufferLimit) { + if (m_receivedData.size() > bufferLimit) + { Logger::instance()->addMessage(tr("Http request size exceeds limitation, closing socket. Limit: %1, IP: %2") .arg(bufferLimit).arg(m_socket->peerAddress().toString()), Log::WARNING); @@ -78,7 +82,8 @@ void Connection::read() } return; - case RequestParser::ParseStatus::BadRequest: { + case RequestParser::ParseStatus::BadRequest: + { Logger::instance()->addMessage(tr("Bad Http request, closing socket. IP: %1") .arg(m_socket->peerAddress().toString()), Log::WARNING); @@ -90,7 +95,8 @@ void Connection::read() } return; - case RequestParser::ParseStatus::OK: { + case RequestParser::ParseStatus::OK: + { const Environment env {m_socket->localAddress(), m_socket->localPort(), m_socket->peerAddress(), m_socket->peerPort()}; Response resp = m_requestHandler->processRequest(result.request, env); @@ -133,7 +139,8 @@ bool Connection::acceptsGzipEncoding(QString codings) const auto isCodingAvailable = [](const QVector &list, const QString &encoding) -> bool { - for (const QStringRef &str : list) { + for (const QStringRef &str : list) + { if (!str.startsWith(encoding)) continue; diff --git a/src/base/http/requestparser.cpp b/src/base/http/requestparser.cpp index 3f74b7a76..549cb1c91 100644 --- a/src/base/http/requestparser.cpp +++ b/src/base/http/requestparser.cpp @@ -61,7 +61,8 @@ namespace { // [rfc7230] 3.2. Header Fields const int i = line.indexOf(':'); - if (i <= 0) { + if (i <= 0) + { qWarning() << Q_FUNC_INFO << "invalid http header:" << line; return false; } @@ -88,13 +89,15 @@ RequestParser::ParseResult RequestParser::doParse(const QByteArray &data) { // we don't handle malformed requests which use double `LF` as delimiter const int headerEnd = data.indexOf(EOH); - if (headerEnd < 0) { + if (headerEnd < 0) + { qDebug() << Q_FUNC_INFO << "incomplete request"; return {ParseStatus::Incomplete, Request(), 0}; } const QString httpHeaders = QString::fromLatin1(data.constData(), headerEnd); - if (!parseStartLines(httpHeaders)) { + if (!parseStartLines(httpHeaders)) + { qWarning() << Q_FUNC_INFO << "header parsing error"; return {ParseStatus::BadRequest, Request(), 0}; } @@ -104,26 +107,32 @@ RequestParser::ParseResult RequestParser::doParse(const QByteArray &data) // handle supported methods if ((m_request.method == HEADER_REQUEST_METHOD_GET) || (m_request.method == HEADER_REQUEST_METHOD_HEAD)) return {ParseStatus::OK, m_request, headerLength}; - if (m_request.method == HEADER_REQUEST_METHOD_POST) { + if (m_request.method == HEADER_REQUEST_METHOD_POST) + { bool ok = false; const int contentLength = m_request.headers[HEADER_CONTENT_LENGTH].toInt(&ok); - if (!ok || (contentLength < 0)) { + if (!ok || (contentLength < 0)) + { qWarning() << Q_FUNC_INFO << "bad request: content-length invalid"; return {ParseStatus::BadRequest, Request(), 0}; } - if (contentLength > MAX_CONTENT_SIZE) { + if (contentLength > MAX_CONTENT_SIZE) + { qWarning() << Q_FUNC_INFO << "bad request: message too long"; return {ParseStatus::BadRequest, Request(), 0}; } - if (contentLength > 0) { + if (contentLength > 0) + { const QByteArray httpBodyView = midView(data, headerLength, contentLength); - if (httpBodyView.length() < contentLength) { + if (httpBodyView.length() < contentLength) + { qDebug() << Q_FUNC_INFO << "incomplete request"; return {ParseStatus::Incomplete, Request(), 0}; } - if (!parsePostMessage(httpBodyView)) { + if (!parsePostMessage(httpBodyView)) + { qWarning() << Q_FUNC_INFO << "message body parsing error"; return {ParseStatus::BadRequest, Request(), 0}; } @@ -143,12 +152,15 @@ bool RequestParser::parseStartLines(const QString &data) // [rfc7230] 3.2.2. Field Order QStringList requestLines; - for (const auto &line : lines) { - if (line.at(0).isSpace() && !requestLines.isEmpty()) { + for (const auto &line : lines) + { + if (line.at(0).isSpace() && !requestLines.isEmpty()) + { // continuation of previous line requestLines.last() += line.toString(); } - else { + else + { requestLines += line.toString(); } } @@ -159,7 +171,8 @@ bool RequestParser::parseStartLines(const QString &data) if (!parseRequestLine(requestLines[0])) return false; - for (auto i = ++(requestLines.begin()); i != requestLines.end(); ++i) { + for (auto i = ++(requestLines.begin()); i != requestLines.end(); ++i) + { if (!parseHeaderLine(*i, m_request.headers)) return false; } @@ -174,7 +187,8 @@ bool RequestParser::parseRequestLine(const QString &line) const QRegularExpression re(QLatin1String("^([A-Z]+)\\s+(\\S+)\\s+HTTP\\/(\\d\\.\\d)$")); const QRegularExpressionMatch match = re.match(line); - if (!match.hasMatch()) { + if (!match.hasMatch()) + { qWarning() << Q_FUNC_INFO << "invalid http header:" << line; return false; } @@ -189,12 +203,14 @@ bool RequestParser::parseRequestLine(const QString &line) m_request.path = QString::fromUtf8(QByteArray::fromPercentEncoding(pathComponent)); - if (sepPos >= 0) { + if (sepPos >= 0) + { const QByteArray query = midView(url, (sepPos + 1)); // [rfc3986] 2.4 When to Encode or Decode // URL components should be separated before percent-decoding - for (const QByteArray ¶m : asConst(splitToViews(query, "&"))) { + for (const QByteArray ¶m : asConst(splitToViews(query, "&"))) + { const int eqCharPos = param.indexOf('='); if (eqCharPos <= 0) continue; // ignores params without name @@ -222,12 +238,14 @@ bool RequestParser::parsePostMessage(const QByteArray &data) const QString contentTypeLower = contentType.toLower(); // application/x-www-form-urlencoded - if (contentTypeLower.startsWith(CONTENT_TYPE_FORM_ENCODED)) { + if (contentTypeLower.startsWith(CONTENT_TYPE_FORM_ENCODED)) + { // [URL Standard] 5.1 application/x-www-form-urlencoded parsing const QByteArray processedData = QByteArray(data).replace('+', ' '); QListIterator i(QUrlQuery(processedData).queryItems(QUrl::FullyDecoded)); - while (i.hasNext()) { + while (i.hasNext()) + { const QStringPair pair = i.next(); m_request.posts[pair.first] = pair.second; } @@ -236,19 +254,22 @@ bool RequestParser::parsePostMessage(const QByteArray &data) } // multipart/form-data - if (contentTypeLower.startsWith(CONTENT_TYPE_FORM_DATA)) { + if (contentTypeLower.startsWith(CONTENT_TYPE_FORM_DATA)) + { // [rfc2046] 5.1.1. Common Syntax // find boundary delimiter const QLatin1String boundaryFieldName("boundary="); const int idx = contentType.indexOf(boundaryFieldName); - if (idx < 0) { + if (idx < 0) + { qWarning() << Q_FUNC_INFO << "Could not find boundary in multipart/form-data header!"; return false; } const QByteArray delimiter = Utils::String::unquote(contentType.midRef(idx + boundaryFieldName.size())).toLatin1(); - if (delimiter.isEmpty()) { + if (delimiter.isEmpty()) + { qWarning() << Q_FUNC_INFO << "boundary delimiter field empty!"; return false; } @@ -256,7 +277,8 @@ bool RequestParser::parsePostMessage(const QByteArray &data) // split data by "dash-boundary" const QByteArray dashDelimiter = QByteArray("--") + delimiter + CRLF; QVector multipart = splitToViews(data, dashDelimiter, QString::SkipEmptyParts); - if (multipart.isEmpty()) { + if (multipart.isEmpty()) + { qWarning() << Q_FUNC_INFO << "multipart empty"; return false; } @@ -279,7 +301,8 @@ bool RequestParser::parseFormData(const QByteArray &data) { const QVector list = splitToViews(data, EOH, QString::KeepEmptyParts); - if (list.size() != 2) { + if (list.size() != 2) + { qWarning() << Q_FUNC_INFO << "multipart/form-data format error"; return false; } @@ -289,12 +312,15 @@ bool RequestParser::parseFormData(const QByteArray &data) HeaderMap headersMap; const QVector headerLines = headers.splitRef(CRLF, QString::SkipEmptyParts); - for (const auto &line : headerLines) { - if (line.trimmed().startsWith(HEADER_CONTENT_DISPOSITION, Qt::CaseInsensitive)) { + for (const auto &line : headerLines) + { + if (line.trimmed().startsWith(HEADER_CONTENT_DISPOSITION, Qt::CaseInsensitive)) + { // extract out filename & name const QVector directives = line.split(';', QString::SkipEmptyParts); - for (const auto &directive : directives) { + for (const auto &directive : directives) + { const int idx = directive.indexOf('='); if (idx < 0) continue; @@ -304,7 +330,8 @@ bool RequestParser::parseFormData(const QByteArray &data) headersMap[name] = value; } } - else { + else + { if (!parseHeaderLine(line.toString(), headersMap)) return false; } @@ -314,13 +341,16 @@ bool RequestParser::parseFormData(const QByteArray &data) const QLatin1String filename("filename"); const QLatin1String name("name"); - if (headersMap.contains(filename)) { + if (headersMap.contains(filename)) + { m_request.files.append({headersMap[filename], headersMap[HEADER_CONTENT_TYPE], payload}); } - else if (headersMap.contains(name)) { + else if (headersMap.contains(name)) + { m_request.posts[headersMap[name]] = payload; } - else { + else + { // malformed qWarning() << Q_FUNC_INFO << "multipart/form-data header error"; return false; diff --git a/src/base/http/server.cpp b/src/base/http/server.cpp index 1d16bf590..48ca74356 100644 --- a/src/base/http/server.cpp +++ b/src/base/http/server.cpp @@ -93,12 +93,14 @@ void Server::incomingConnection(const qintptr socketDescriptor) else serverSocket = new QTcpSocket(this); - if (!serverSocket->setSocketDescriptor(socketDescriptor)) { + if (!serverSocket->setSocketDescriptor(socketDescriptor)) + { delete serverSocket; return; } - if (m_https) { + if (m_https) + { static_cast(serverSocket)->setProtocol(QSsl::SecureProtocols); static_cast(serverSocket)->setPrivateKey(m_key); static_cast(serverSocket)->setLocalCertificateChain(m_certificates); @@ -134,7 +136,8 @@ bool Server::setupHttps(const QByteArray &certificates, const QByteArray &privat const QList certs {Utils::Net::loadSSLCertificate(certificates)}; const QSslKey key {Utils::Net::loadSSLKey(privateKey)}; - if (certs.isEmpty() || key.isNull()) { + if (certs.isEmpty() || key.isNull()) + { disableHttps(); return false; } diff --git a/src/base/net/dnsupdater.cpp b/src/base/net/dnsupdater.cpp index 86a96afc5..ad688ab2b 100644 --- a/src/base/net/dnsupdater.cpp +++ b/src/base/net/dnsupdater.cpp @@ -56,7 +56,8 @@ DNSUpdater::DNSUpdater(QObject *parent) // Check lastUpdate to avoid flooding if (!m_lastIPCheckTime.isValid() - || (m_lastIPCheckTime.secsTo(QDateTime::currentDateTime()) * 1000 > IP_CHECK_INTERVAL_MS)) { + || (m_lastIPCheckTime.secsTo(QDateTime::currentDateTime()) * 1000 > IP_CHECK_INTERVAL_MS)) + { checkPublicIP(); } } @@ -82,30 +83,36 @@ void DNSUpdater::checkPublicIP() void DNSUpdater::ipRequestFinished(const DownloadResult &result) { - if (result.status != DownloadStatus::Success) { + if (result.status != DownloadStatus::Success) + { qWarning() << "IP request failed:" << result.errorString; return; } // Parse response const QRegularExpressionMatch ipRegexMatch = QRegularExpression("Current IP Address:\\s+([^<]+)").match(result.data); - if (ipRegexMatch.hasMatch()) { + if (ipRegexMatch.hasMatch()) + { QString ipStr = ipRegexMatch.captured(1); qDebug() << Q_FUNC_INFO << "Regular expression captured the following IP:" << ipStr; QHostAddress newIp(ipStr); - if (!newIp.isNull()) { - if (m_lastIP != newIp) { + if (!newIp.isNull()) + { + if (m_lastIP != newIp) + { qDebug() << Q_FUNC_INFO << "The IP address changed, report the change to DynDNS..."; qDebug() << m_lastIP.toString() << "->" << newIp.toString(); m_lastIP = newIp; updateDNSService(); } } - else { + else + { qWarning() << Q_FUNC_INFO << "Failed to construct a QHostAddress from the IP string"; } } - else { + else + { qWarning() << Q_FUNC_INFO << "Regular expression failed to capture the IP address"; } } @@ -133,7 +140,8 @@ QString DNSUpdater::getUpdateUrl() const Q_ASSERT(!m_lastIP.isNull()); // Service specific - switch (m_service) { + switch (m_service) + { case DNS::DYNDNS: url.setHost("members.dyndns.org"); break; @@ -171,12 +179,14 @@ void DNSUpdater::processIPUpdateReply(const QString &reply) const QString code = reply.split(' ').first(); qDebug() << Q_FUNC_INFO << "Code:" << code; - if ((code == "good") || (code == "nochg")) { + if ((code == "good") || (code == "nochg")) + { logger->addMessage(tr("Your dynamic DNS was successfully updated."), Log::INFO); return; } - if ((code == "911") || (code == "dnserr")) { + if ((code == "911") || (code == "dnserr")) + { logger->addMessage(tr("Dynamic DNS error: The service is temporarily unavailable, it will be retried in 30 minutes."), Log::CRITICAL); m_lastIP.clear(); // It will retry in 30 minutes because the timer was not stopped @@ -186,33 +196,38 @@ 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 == "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 == "badauth") + { logger->addMessage(tr("Dynamic DNS error: Invalid username/password."), Log::CRITICAL); m_state = INVALID_CREDS; return; } - if (code == "badagent") { + if (code == "badagent") + { logger->addMessage(tr("Dynamic DNS error: qBittorrent was blacklisted by the service, please report a bug at http://bugs.qbittorrent.org."), Log::CRITICAL); m_state = FATAL; return; } - if (code == "!donator") { + if (code == "!donator") + { logger->addMessage(tr("Dynamic DNS error: %1 was returned by the service, please report a bug at http://bugs.qbittorrent.org.").arg("!donator"), Log::CRITICAL); m_state = FATAL; return; } - if (code == "abuse") { + if (code == "abuse") + { logger->addMessage(tr("Dynamic DNS error: Your username was blocked due to abuse."), Log::CRITICAL); m_state = FATAL; } @@ -225,14 +240,17 @@ void DNSUpdater::updateCredentials() Logger *const logger = Logger::instance(); bool change = false; // Get DNS service information - if (m_service != pref->getDynDNSService()) { + if (m_service != pref->getDynDNSService()) + { m_service = pref->getDynDNSService(); change = true; } - if (m_domain != pref->getDynDomainName()) { + 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); - if (!domainRegexMatch.hasMatch()) { + if (!domainRegexMatch.hasMatch()) + { logger->addMessage(tr("Dynamic DNS error: supplied domain name is invalid."), Log::CRITICAL); m_lastIP.clear(); m_ipCheckTimer.stop(); @@ -241,9 +259,11 @@ void DNSUpdater::updateCredentials() } change = true; } - if (m_username != pref->getDynDNSUsername()) { + if (m_username != pref->getDynDNSUsername()) + { m_username = pref->getDynDNSUsername(); - if (m_username.length() < 4) { + if (m_username.length() < 4) + { logger->addMessage(tr("Dynamic DNS error: supplied username is too short."), Log::CRITICAL); m_lastIP.clear(); m_ipCheckTimer.stop(); @@ -252,9 +272,11 @@ void DNSUpdater::updateCredentials() } change = true; } - if (m_password != pref->getDynDNSPassword()) { + if (m_password != pref->getDynDNSPassword()) + { m_password = pref->getDynDNSPassword(); - if (m_password.length() < 4) { + if (m_password.length() < 4) + { logger->addMessage(tr("Dynamic DNS error: supplied password is too short."), Log::CRITICAL); m_lastIP.clear(); m_ipCheckTimer.stop(); @@ -264,7 +286,8 @@ void DNSUpdater::updateCredentials() change = true; } - if ((m_state == INVALID_CREDS) && change) { + if ((m_state == INVALID_CREDS) && change) + { m_state = OK; // Try again m_ipCheckTimer.start(); checkPublicIP(); @@ -273,7 +296,8 @@ void DNSUpdater::updateCredentials() QUrl DNSUpdater::getRegistrationUrl(const int service) { - switch (service) { + switch (service) + { case DNS::DYNDNS: return {"https://www.dyndns.com/account/services/hosts/add.html"}; case DNS::NOIP: diff --git a/src/base/net/downloadhandlerimpl.cpp b/src/base/net/downloadhandlerimpl.cpp index 699392381..b5b9a2ed0 100644 --- a/src/base/net/downloadhandlerimpl.cpp +++ b/src/base/net/downloadhandlerimpl.cpp @@ -66,10 +66,12 @@ DownloadHandlerImpl::DownloadHandlerImpl(Net::DownloadManager *manager, const Ne void DownloadHandlerImpl::cancel() { - if (m_reply) { + if (m_reply) + { m_reply->abort(); } - else { + else + { setError(errorCodeToString(QNetworkReply::OperationCanceledError)); finish(); } @@ -103,7 +105,8 @@ void DownloadHandlerImpl::processFinishedDownload() qDebug("Download finished: %s", qUtf8Printable(url())); // Check if the request was successful - if (m_reply->error() != QNetworkReply::NoError) { + if (m_reply->error() != QNetworkReply::NoError) + { // Failure qDebug("Download failure (%s), reason: %s", qUtf8Printable(url()), qUtf8Printable(errorCodeToString(m_reply->error()))); setError(errorCodeToString(m_reply->error())); @@ -113,7 +116,8 @@ void DownloadHandlerImpl::processFinishedDownload() // Check if the server ask us to redirect somewhere else const QVariant redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute); - if (redirection.isValid()) { + if (redirection.isValid()) + { handleRedirection(redirection.toUrl()); return; } @@ -123,7 +127,8 @@ void DownloadHandlerImpl::processFinishedDownload() ? Utils::Gzip::decompress(m_reply->readAll()) : m_reply->readAll(); - if (m_downloadRequest.saveToFile()) { + if (m_downloadRequest.saveToFile()) + { QString filePath; if (saveToFile(m_result.data, filePath)) m_result.filePath = filePath; @@ -136,13 +141,15 @@ void DownloadHandlerImpl::processFinishedDownload() void DownloadHandlerImpl::checkDownloadSize(const qint64 bytesReceived, const qint64 bytesTotal) { - if ((bytesTotal > 0) && (bytesTotal <= m_downloadRequest.limit())) { + if ((bytesTotal > 0) && (bytesTotal <= m_downloadRequest.limit())) + { // Total number of bytes is available disconnect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadHandlerImpl::checkDownloadSize); return; } - if ((bytesTotal > m_downloadRequest.limit()) || (bytesReceived > m_downloadRequest.limit())) { + if ((bytesTotal > m_downloadRequest.limit()) || (bytesReceived > m_downloadRequest.limit())) + { m_reply->abort(); setError(tr("The file size (%1) exceeds the download limit (%2)") .arg(Utils::Misc::friendlyUnit(bytesTotal) @@ -153,7 +160,8 @@ void DownloadHandlerImpl::checkDownloadSize(const qint64 bytesReceived, const qi void DownloadHandlerImpl::handleRedirection(const QUrl &newUrl) { - if (m_redirectionCount >= MAX_REDIRECTIONS) { + if (m_redirectionCount >= MAX_REDIRECTIONS) + { setError(tr("Exceeded max redirections (%1)").arg(MAX_REDIRECTIONS)); finish(); return; @@ -165,7 +173,8 @@ 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("magnet:", Qt::CaseInsensitive)) + { qDebug("Magnet redirect detected."); m_result.status = Net::DownloadStatus::RedirectedToMagnet; m_result.magnet = newUrlString; @@ -199,7 +208,8 @@ void DownloadHandlerImpl::finish() QString DownloadHandlerImpl::errorCodeToString(const QNetworkReply::NetworkError status) { - switch (status) { + switch (status) + { case QNetworkReply::HostNotFoundError: return tr("The remote host name was not found (invalid hostname)"); case QNetworkReply::OperationCanceledError: diff --git a/src/base/net/downloadmanager.cpp b/src/base/net/downloadmanager.cpp index a14540530..71fbf9f12 100644 --- a/src/base/net/downloadmanager.cpp +++ b/src/base/net/downloadmanager.cpp @@ -60,7 +60,8 @@ namespace { const QDateTime now = QDateTime::currentDateTime(); QList cookies = Preferences::instance()->getNetworkCookies(); - for (const QNetworkCookie &cookie : asConst(Preferences::instance()->getNetworkCookies())) { + for (const QNetworkCookie &cookie : asConst(Preferences::instance()->getNetworkCookies())) + { if (cookie.isSessionCookie() || (cookie.expirationDate() <= now)) cookies.removeAll(cookie); } @@ -72,7 +73,8 @@ namespace { const QDateTime now = QDateTime::currentDateTime(); QList cookies = allCookies(); - for (const QNetworkCookie &cookie : asConst(allCookies())) { + for (const QNetworkCookie &cookie : asConst(allCookies())) + { if (cookie.isSessionCookie() || (cookie.expirationDate() <= now)) cookies.removeAll(cookie); } @@ -87,7 +89,8 @@ namespace { const QDateTime now = QDateTime::currentDateTime(); QList cookies = QNetworkCookieJar::cookiesForUrl(url); - for (const QNetworkCookie &cookie : asConst(QNetworkCookieJar::cookiesForUrl(url))) { + for (const QNetworkCookie &cookie : asConst(QNetworkCookieJar::cookiesForUrl(url))) + { if (!cookie.isSessionCookie() && (cookie.expirationDate() <= now)) cookies.removeAll(cookie); } @@ -99,7 +102,8 @@ namespace { const QDateTime now = QDateTime::currentDateTime(); QList cookies = cookieList; - for (const QNetworkCookie &cookie : cookieList) { + for (const QNetworkCookie &cookie : cookieList) + { if (!cookie.isSessionCookie() && (cookie.expirationDate() <= now)) cookies.removeAll(cookie); } @@ -172,10 +176,12 @@ Net::DownloadHandler *Net::DownloadManager::download(const DownloadRequest &down m_waitingJobs[id].removeOne(downloadHandler); }); - if (isSequentialService && m_busyServices.contains(id)) { + if (isSequentialService && m_busyServices.contains(id)) + { m_waitingJobs[id].enqueue(downloadHandler); } - else { + else + { qDebug("Downloading %s...", qUtf8Printable(downloadRequest.url())); if (isSequentialService) m_busyServices.insert(id); @@ -230,27 +236,32 @@ void Net::DownloadManager::applyProxySettings() const ProxyConfiguration proxyConfig = proxyManager->proxyConfiguration(); QNetworkProxy proxy; - if (!proxyManager->isProxyOnlyForTorrents() && (proxyConfig.type != ProxyType::None)) { + if (!proxyManager->isProxyOnlyForTorrents() && (proxyConfig.type != ProxyType::None)) + { // Proxy enabled proxy.setHostName(proxyConfig.ip); proxy.setPort(proxyConfig.port); // Default proxy type is HTTP, we must change if it is SOCKS5 - if ((proxyConfig.type == ProxyType::SOCKS5) || (proxyConfig.type == ProxyType::SOCKS5_PW)) { + if ((proxyConfig.type == ProxyType::SOCKS5) || (proxyConfig.type == ProxyType::SOCKS5_PW)) + { qDebug() << Q_FUNC_INFO << "using SOCKS proxy"; proxy.setType(QNetworkProxy::Socks5Proxy); } - else { + else + { qDebug() << Q_FUNC_INFO << "using HTTP proxy"; proxy.setType(QNetworkProxy::HttpProxy); } // Authentication? - if (proxyManager->isAuthenticationRequired()) { + if (proxyManager->isAuthenticationRequired()) + { qDebug("Proxy requires authentication, authenticating..."); proxy.setUser(proxyConfig.username); proxy.setPassword(proxyConfig.password); } } - else { + else + { proxy.setType(QNetworkProxy::NoProxy); } @@ -264,7 +275,8 @@ void Net::DownloadManager::handleReplyFinished(const QNetworkReply *reply) // in the case when the redirection occurred. const ServiceID id = ServiceID::fromURL(reply->request().url()); const auto waitingJobsIter = m_waitingJobs.find(id); - if ((waitingJobsIter == m_waitingJobs.end()) || waitingJobsIter.value().isEmpty()) { + if ((waitingJobsIter == m_waitingJobs.end()) || waitingJobsIter.value().isEmpty()) + { // No more waiting jobs for given ServiceID m_busyServices.remove(id); return; diff --git a/src/base/net/geoipdatabase.cpp b/src/base/net/geoipdatabase.cpp index 8c565321c..b55e3d8f8 100644 --- a/src/base/net/geoipdatabase.cpp +++ b/src/base/net/geoipdatabase.cpp @@ -88,26 +88,30 @@ GeoIPDatabase *GeoIPDatabase::load(const QString &filename, QString &error) { GeoIPDatabase *db = nullptr; QFile file(filename); - if (file.size() > MAX_FILE_SIZE) { + if (file.size() > MAX_FILE_SIZE) + { error = tr("Unsupported database file size."); return nullptr; } - if (!file.open(QFile::ReadOnly)) { + if (!file.open(QFile::ReadOnly)) + { error = file.errorString(); return nullptr; } db = new GeoIPDatabase(file.size()); - if (file.read(reinterpret_cast(db->m_data), db->m_size) != db->m_size) { + if (file.read(reinterpret_cast(db->m_data), db->m_size) != db->m_size) + { error = file.errorString(); delete db; return nullptr; } - if (!db->parseMetadata(db->readMetadata(), error) || !db->loadDB(error)) { + if (!db->parseMetadata(db->readMetadata(), error) || !db->loadDB(error)) + { delete db; return nullptr; } @@ -118,7 +122,8 @@ GeoIPDatabase *GeoIPDatabase::load(const QString &filename, QString &error) GeoIPDatabase *GeoIPDatabase::load(const QByteArray &data, QString &error) { GeoIPDatabase *db = nullptr; - if (data.size() > MAX_FILE_SIZE) { + if (data.size() > MAX_FILE_SIZE) + { error = tr("Unsupported database file size."); return nullptr; } @@ -127,7 +132,8 @@ GeoIPDatabase *GeoIPDatabase::load(const QByteArray &data, QString &error) memcpy(reinterpret_cast(db->m_data), data.constData(), db->m_size); - if (!db->parseMetadata(db->readMetadata(), error) || !db->loadDB(error)) { + if (!db->parseMetadata(db->readMetadata(), error) || !db->loadDB(error)) + { delete db; return nullptr; } @@ -161,8 +167,10 @@ QString GeoIPDatabase::lookup(const QHostAddress &hostAddr) const const uchar *ptr = m_data; - for (int i = 0; i < 16; ++i) { - for (int j = 0; j < 8; ++j) { + for (int i = 0; i < 16; ++i) + { + for (int j = 0; j < 8; ++j) + { const bool right = static_cast((addr[i] >> (7 - j)) & 1); // Interpret the left/right record as number if (right) @@ -173,16 +181,20 @@ QString GeoIPDatabase::lookup(const QHostAddress &hostAddr) const memcpy(&idPtr[4 - m_recordBytes], ptr, m_recordBytes); fromBigEndian(idPtr, 4); - if (id == m_nodeCount) { + if (id == m_nodeCount) + { return {}; } - if (id > m_nodeCount) { + if (id > m_nodeCount) + { QString country = m_countries.value(id); - if (country.isEmpty()) { + if (country.isEmpty()) + { const quint32 offset = id - m_nodeCount - sizeof(DATA_SECTION_SEPARATOR); quint32 tmp = offset + m_indexSize + sizeof(DATA_SECTION_SEPARATOR); const QVariant val = readDataField(tmp); - if (val.userType() == QMetaType::QVariantHash) { + if (val.userType() == QMetaType::QVariantHash) + { country = val.toHash()["country"].toHash()["iso_code"].toString(); m_countries[id] = country; } @@ -198,18 +210,22 @@ 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); \ return false; \ } \ -if (metadata.value(#key).userType() != QMetaType::type) { \ +if (metadata.value(#key).userType() != QMetaType::type) \ +{ \ error = errMsgInvalid.arg(#key); \ return false; \ } #define CHECK_METADATA_OPT(key, type) \ -if (metadata.contains(#key)) { \ - if (metadata.value(#key).userType() != QMetaType::type) { \ +if (metadata.contains(#key)) \ +{ \ + if (metadata.value(#key).userType() != QMetaType::type) \ + { \ error = errMsgInvalid.arg(#key); \ return false; \ } \ @@ -226,21 +242,24 @@ bool GeoIPDatabase::parseMetadata(const QVariantHash &metadata, QString &error) 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(); - if (versionMajor != 2) { + 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(); - if (m_ipVersion != 6) { + 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(); - if (m_recordSize != 24) { + if (m_recordSize != 24) + { error = tr("Unsupported record size: %1").arg(m_recordSize); return false; } @@ -270,7 +289,8 @@ bool GeoIPDatabase::loadDB(QString &error) const const int nodeSize = m_recordSize / 4; // in bytes const int indexSize = m_nodeCount * nodeSize; if ((m_size < (indexSize + sizeof(DATA_SECTION_SEPARATOR))) - || (memcmp(m_data + indexSize, DATA_SECTION_SEPARATOR, sizeof(DATA_SECTION_SEPARATOR)) != 0)) { + || (memcmp(m_data + indexSize, DATA_SECTION_SEPARATOR, sizeof(DATA_SECTION_SEPARATOR)) != 0)) + { error = tr("Database corrupted: no data section found."); return false; } @@ -282,14 +302,16 @@ QVariantHash GeoIPDatabase::readMetadata() const { const char *ptr = reinterpret_cast(m_data); quint32 size = m_size; - if (m_size > MAX_METADATA_SIZE) { + if (m_size > MAX_METADATA_SIZE) + { ptr += m_size - MAX_METADATA_SIZE; size = MAX_METADATA_SIZE; } const QByteArray data = QByteArray::fromRawData(ptr, size); int index = data.lastIndexOf(METADATA_BEGIN_MARK); - if (index >= 0) { + if (index >= 0) + { if (m_size > MAX_METADATA_SIZE) index += (m_size - MAX_METADATA_SIZE); // from begin of all data auto offset = static_cast(index + strlen(METADATA_BEGIN_MARK)); @@ -309,7 +331,8 @@ QVariant GeoIPDatabase::readDataField(quint32 &offset) const quint32 locOffset = offset; bool usePointer = false; - if (descr.fieldType == DataType::Pointer) { + if (descr.fieldType == DataType::Pointer) + { usePointer = true; // convert offset from data section to global locOffset = descr.offset + (m_nodeCount * m_recordSize / 4) + sizeof(DATA_SECTION_SEPARATOR); @@ -318,7 +341,8 @@ QVariant GeoIPDatabase::readDataField(quint32 &offset) const } QVariant fieldValue; - switch (descr.fieldType) { + switch (descr.fieldType) + { case DataType::Pointer: qDebug() << "* Illegal Pointer using"; break; @@ -388,7 +412,8 @@ bool GeoIPDatabase::readDataFieldDescriptor(quint32 &offset, DataFieldDescriptor if (availSize < 1) return false; out.fieldType = static_cast((dataPtr[0] & 0xE0) >> 5); - if (out.fieldType == DataType::Pointer) { + if (out.fieldType == DataType::Pointer) + { const int size = ((dataPtr[0] & 0x18) >> 3); if (availSize < (size + 2)) return false; @@ -406,28 +431,34 @@ bool GeoIPDatabase::readDataFieldDescriptor(quint32 &offset, DataFieldDescriptor } out.fieldSize = dataPtr[0] & 0x1F; - if (out.fieldSize <= 28) { - if (out.fieldType == DataType::Unknown) { + if (out.fieldSize <= 28) + { + if (out.fieldType == DataType::Unknown) + { out.fieldType = static_cast(dataPtr[1] + 7); if ((out.fieldType <= DataType::Map) || (out.fieldType > DataType::Float) || (availSize < 3)) return false; offset += 2; } - else { + else + { offset += 1; } } - else if (out.fieldSize == 29) { + else if (out.fieldSize == 29) + { if (availSize < 2) return false; out.fieldSize = dataPtr[1] + 29; offset += 2; } - else if (out.fieldSize == 30) { + else if (out.fieldSize == 30) + { if (availSize < 3) return false; out.fieldSize = (dataPtr[1] << 8) + dataPtr[2] + 285; offset += 3; } - else if (out.fieldSize == 31) { + else if (out.fieldSize == 31) + { if (availSize < 4) return false; out.fieldSize = (dataPtr[1] << 16) + (dataPtr[2] << 8) + dataPtr[3] + 65821; offset += 4; @@ -450,7 +481,8 @@ QVariant GeoIPDatabase::readMapValue(quint32 &offset, const quint32 count) const { QVariantHash map; - for (quint32 i = 0; i < count; ++i) { + for (quint32 i = 0; i < count; ++i) + { QVariant field = readDataField(offset); if (field.userType() != QMetaType::QString) return {}; @@ -470,7 +502,8 @@ QVariant GeoIPDatabase::readArrayValue(quint32 &offset, const quint32 count) con { QVariantList array; - for (quint32 i = 0; i < count; ++i) { + for (quint32 i = 0; i < count; ++i) + { const QVariant field = readDataField(offset); if (field.userType() == QVariant::Invalid) return {}; diff --git a/src/base/net/geoipdatabase.h b/src/base/net/geoipdatabase.h index 313ee0346..44d095cb0 100644 --- a/src/base/net/geoipdatabase.h +++ b/src/base/net/geoipdatabase.h @@ -74,7 +74,8 @@ private: const uchar *const data = m_data + offset; const quint32 availSize = m_size - offset; - if ((len > 0) && (len <= sizeof(T) && (availSize >= len))) { + if ((len > 0) && (len <= sizeof(T) && (availSize >= len))) + { // copy input data to last 'len' bytes of 'value' uchar *dst = reinterpret_cast(&value) + (sizeof(T) - len); memcpy(dst, data, len); diff --git a/src/base/net/geoipmanager.cpp b/src/base/net/geoipmanager.cpp index 1243f21a8..a7c9e1473 100644 --- a/src/base/net/geoipmanager.cpp +++ b/src/base/net/geoipmanager.cpp @@ -140,7 +140,8 @@ QString GeoIPManager::lookup(const QHostAddress &hostAddr) const QString GeoIPManager::CountryName(const QString &countryISOCode) { - static const QHash countries = { + static const QHash countries = + { // ISO 3166-1 alpha-2 codes // http://www.iso.org/iso/home/standards/country_codes/country_names_and_code_elements_txt-temp.htm @@ -404,12 +405,15 @@ QString GeoIPManager::CountryName(const QString &countryISOCode) void GeoIPManager::configure() { const bool enabled = Preferences::instance()->resolvePeerCountries(); - if (m_enabled != enabled) { + if (m_enabled != enabled) + { m_enabled = enabled; - if (m_enabled && !m_geoIPDatabase) { + if (m_enabled && !m_geoIPDatabase) + { loadDatabase(); } - else if (!m_enabled) { + else if (!m_enabled) + { delete m_geoIPDatabase; m_geoIPDatabase = nullptr; } @@ -418,22 +422,26 @@ void GeoIPManager::configure() void GeoIPManager::downloadFinished(const DownloadResult &result) { - if (result.status != DownloadStatus::Success) { + if (result.status != DownloadStatus::Success) + { LogMsg(tr("Couldn't download IP geolocation database file. Reason: %1").arg(result.errorString), Log::WARNING); return; } bool ok = false; const QByteArray data = Utils::Gzip::decompress(result.data, &ok); - if (!ok) { + if (!ok) + { LogMsg(tr("Could not decompress IP geolocation database file."), Log::WARNING); return; } QString error; GeoIPDatabase *geoIPDatabase = GeoIPDatabase::load(data, error); - if (geoIPDatabase) { - if (!m_geoIPDatabase || (geoIPDatabase->buildEpoch() > m_geoIPDatabase->buildEpoch())) { + if (geoIPDatabase) + { + if (!m_geoIPDatabase || (geoIPDatabase->buildEpoch() > m_geoIPDatabase->buildEpoch())) + { delete m_geoIPDatabase; m_geoIPDatabase = geoIPDatabase; LogMsg(tr("IP geolocation database loaded. Type: %1. Build time: %2.") @@ -449,11 +457,13 @@ void GeoIPManager::downloadFinished(const DownloadResult &result) else LogMsg(tr("Successfully updated IP geolocation database."), Log::INFO); } - else { + else + { delete geoIPDatabase; } } - else { + else + { LogMsg(tr("Couldn't load IP geolocation database. Reason: %1").arg(error), Log::WARNING); } } diff --git a/src/base/net/proxyconfigurationmanager.cpp b/src/base/net/proxyconfigurationmanager.cpp index 155e52461..0a4961594 100644 --- a/src/base/net/proxyconfigurationmanager.cpp +++ b/src/base/net/proxyconfigurationmanager.cpp @@ -100,7 +100,8 @@ ProxyConfiguration ProxyConfigurationManager::proxyConfiguration() const void ProxyConfigurationManager::setProxyConfiguration(const ProxyConfiguration &config) { - if (config != m_config) { + if (config != m_config) + { m_config = config; settings()->storeValue(KEY_TYPE, static_cast(config.type)); settings()->storeValue(KEY_IP, config.ip); @@ -120,7 +121,8 @@ bool ProxyConfigurationManager::isProxyOnlyForTorrents() const void ProxyConfigurationManager::setProxyOnlyForTorrents(bool onlyForTorrents) { - if (m_isProxyOnlyForTorrents != onlyForTorrents) { + if (m_isProxyOnlyForTorrents != onlyForTorrents) + { settings()->storeValue(KEY_ONLY_FOR_TORRENTS, onlyForTorrents); m_isProxyOnlyForTorrents = onlyForTorrents; } @@ -136,8 +138,10 @@ void ProxyConfigurationManager::configureProxy() { // Define environment variables for urllib in search engine plugins QString proxyStrHTTP, proxyStrSOCK; - if (!m_isProxyOnlyForTorrents) { - switch (m_config.type) { + if (!m_isProxyOnlyForTorrents) + { + switch (m_config.type) + { case ProxyType::HTTP_PW: proxyStrHTTP = QString::fromLatin1("http://%1:%2@%3:%4").arg(m_config.username , m_config.password, m_config.ip, QString::number(m_config.port)); diff --git a/src/base/net/reverseresolution.cpp b/src/base/net/reverseresolution.cpp index 4d63923b0..b53ea1989 100644 --- a/src/base/net/reverseresolution.cpp +++ b/src/base/net/reverseresolution.cpp @@ -60,7 +60,8 @@ ReverseResolution::~ReverseResolution() void ReverseResolution::resolve(const QHostAddress &ip) { const QString *hostname = m_cache.object(ip); - if (hostname) { + if (hostname) + { emit ipResolved(ip, *hostname); return; } @@ -74,7 +75,8 @@ void ReverseResolution::hostResolved(const QHostInfo &host) { const QHostAddress ip = m_lookups.take(host.lookupId()); - if (host.error() != QHostInfo::NoError) { + if (host.error() != QHostInfo::NoError) + { emit ipResolved(ip, {}); return; } diff --git a/src/base/net/smtp.cpp b/src/base/net/smtp.cpp index 5c8258a65..65ff739a4 100644 --- a/src/base/net/smtp.cpp +++ b/src/base/net/smtp.cpp @@ -67,7 +67,8 @@ namespace // ascii characters 0x36 ("6") and 0x5c ("\") are selected because they have large // Hamming distance (http://en.wikipedia.org/wiki/Hamming_distance) - for (int i = 0; i < key.length(); ++i) { + for (int i = 0; i < key.length(); ++i) + { innerPadding[i] = innerPadding[i] ^ key.at(i); // XOR operation between every byte in key and innerpadding, of key length outerPadding[i] = outerPadding[i] ^ key.at(i); // XOR operation between every byte in key and outerpadding, of key length } @@ -100,7 +101,8 @@ Smtp::Smtp(QObject *parent) { static bool needToRegisterMetaType = true; - if (needToRegisterMetaType) { + if (needToRegisterMetaType) + { qRegisterMetaType(); needToRegisterMetaType = false; } @@ -153,18 +155,21 @@ void Smtp::sendMail(const QString &from, const QString &to, const QString &subje m_from = from; m_rcpt = to; // Authentication - if (pref->getMailNotificationSMTPAuth()) { + if (pref->getMailNotificationSMTPAuth()) + { m_username = pref->getMailNotificationSMTPUsername(); m_password = pref->getMailNotificationSMTPPassword(); } // Connect to SMTP server #ifndef QT_NO_OPENSSL - if (pref->getMailNotificationSMTPSSL()) { + if (pref->getMailNotificationSMTPSSL()) + { m_socket->connectToHostEncrypted(pref->getMailNotificationSMTP(), DEFAULT_PORT_SSL); m_useSsl = true; } - else { + else + { #endif m_socket->connectToHost(pref->getMailNotificationSMTP(), DEFAULT_PORT); m_useSsl = false; @@ -178,7 +183,8 @@ void Smtp::readyRead() qDebug() << Q_FUNC_INFO; // SMTP is line-oriented m_buffer += m_socket->readAll(); - while (true) { + while (true) + { const int pos = m_buffer.indexOf("\r\n"); if (pos < 0) return; // Loop exit condition const QByteArray line = m_buffer.left(pos); @@ -187,9 +193,11 @@ void Smtp::readyRead() // Extract response code const QByteArray code = line.left(3); - switch (m_state) { + switch (m_state) + { case Init: - if (code[0] == '2') { + if (code[0] == '2') + { // The server may send a multiline greeting/INIT/220 response. // We wait until it finishes. if (line[3] != ' ') @@ -197,7 +205,8 @@ void Smtp::readyRead() // Connection was successful ehlo(); } - else { + else + { logError(QLatin1String("Connection failed, unrecognized reply: ") + line); m_state = Close; } @@ -209,11 +218,13 @@ void Smtp::readyRead() break; #ifndef QT_NO_OPENSSL case StartTLSSent: - if (code == "220") { + if (code == "220") + { m_socket->startClientEncryption(); ehlo(); } - else { + else + { authenticate(); } break; @@ -226,59 +237,69 @@ void Smtp::readyRead() break; case AuthSent: case Authenticated: - if (code[0] == '2') { + if (code[0] == '2') + { qDebug() << "Sending ..."; m_socket->write("mail from:<" + m_from.toLatin1() + ">\r\n"); m_socket->flush(); m_state = Rcpt; } - else { + else + { // Authentication failed! logError(QLatin1String("Authentication failed, msg: ") + line); m_state = Close; } break; case Rcpt: - if (code[0] == '2') { + if (code[0] == '2') + { m_socket->write("rcpt to:<" + m_rcpt.toLatin1() + ">\r\n"); m_socket->flush(); m_state = Data; } - else { + else + { logError(QLatin1String(" was rejected by server, msg: ") + line); m_state = Close; } break; case Data: - if (code[0] == '2') { + if (code[0] == '2') + { m_socket->write("data\r\n"); m_socket->flush(); m_state = Body; } - else { + else + { logError(QLatin1String(" was rejected by server, msg: ") + line); m_state = Close; } break; case Body: - if (code[0] == '3') { + if (code[0] == '3') + { m_socket->write(m_message + "\r\n.\r\n"); m_socket->flush(); m_state = Quit; } - else { + else + { logError(QLatin1String(" was rejected by server, msg: ") + line); m_state = Close; } break; case Quit: - if (code[0] == '2') { + if (code[0] == '2') + { m_socket->write("QUIT\r\n"); m_socket->flush(); // here, we just close. m_state = Close; } - else { + else + { logError(QLatin1String("Message was rejected by the server, error: ") + line); m_state = Close; } @@ -296,10 +317,13 @@ QByteArray Smtp::encodeMimeHeader(const QString &key, const QString &value, cons QByteArray rv = ""; QByteArray line = key.toLatin1() + ": "; if (!prefix.isEmpty()) line += prefix; - if (!value.contains("=?") && latin1->canEncode(value)) { + if (!value.contains("=?") && latin1->canEncode(value)) + { bool firstWord = true; - for (const QByteArray &word : asConst(value.toLatin1().split(' '))) { - if (line.size() > 78) { + for (const QByteArray &word : asConst(value.toLatin1().split(' '))) + { + if (line.size() > 78) + { rv = rv + line + "\r\n"; line.clear(); } @@ -310,7 +334,8 @@ QByteArray Smtp::encodeMimeHeader(const QString &key, const QString &value, cons firstWord = false; } } - else { + else + { // The text cannot be losslessly encoded as Latin-1. Therefore, we // must use base64 encoding. const QByteArray utf8 = value.toUtf8(); @@ -318,8 +343,10 @@ QByteArray Smtp::encodeMimeHeader(const QString &key, const QString &value, cons const QByteArray base64 = utf8.toBase64(); const int ct = base64.length(); line += "=?utf-8?b?"; - for (int i = 0; i < ct; i += 4) { - /*if (line.length() > 72) { + for (int i = 0; i < ct; i += 4) + { + /*if (line.length() > 72) + { rv += line + "?\n\r"; line = " =?utf-8?b?"; }*/ @@ -348,14 +375,17 @@ void Smtp::helo() void Smtp::parseEhloResponse(const QByteArray &code, const bool continued, const QString &line) { - if (code != "250") { + if (code != "250") + { // Error - if (m_state == EhloSent) { + if (m_state == EhloSent) + { // try to send HELO instead of EHLO qDebug() << "EHLO failed, trying HELO instead..."; helo(); } - else { + else + { // Both EHLO and HELO failed, chances are this is NOT // a SMTP server logError("Both EHLO and HELO failed, msg: " + line); @@ -364,20 +394,24 @@ void Smtp::parseEhloResponse(const QByteArray &code, const bool continued, const return; } - if (m_state != EhloGreetReceived) { - if (!continued) { + if (m_state != EhloGreetReceived) + { + if (!continued) + { // greeting only, no extensions qDebug() << "No extension"; m_state = EhloDone; } - else { + else + { // greeting followed by extensions m_state = EhloGreetReceived; qDebug() << "EHLO greet received"; return; } } - else { + 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); @@ -387,11 +421,13 @@ void Smtp::parseEhloResponse(const QByteArray &code, const bool continued, const if (m_state != EhloDone) return; - if (m_extensions.contains("STARTTLS") && m_useSsl) { + if (m_extensions.contains("STARTTLS") && m_useSsl) + { qDebug() << "STARTTLS"; startTLS(); } - else { + else + { authenticate(); } } @@ -400,7 +436,8 @@ void Smtp::authenticate() { qDebug() << Q_FUNC_INFO; if (!m_extensions.contains("AUTH") || - m_username.isEmpty() || m_password.isEmpty()) { + m_username.isEmpty() || m_password.isEmpty()) + { // Skip authentication qDebug() << "Skipping authentication..."; m_state = Authenticated; @@ -414,19 +451,23 @@ void Smtp::authenticate() // authentication modes are supported by // the server const QStringList auth = m_extensions["AUTH"].toUpper().split(' ', QString::SkipEmptyParts); - if (auth.contains("CRAM-MD5")) { + if (auth.contains("CRAM-MD5")) + { qDebug() << "Using CRAM-MD5 authentication..."; authCramMD5(); } - else if (auth.contains("PLAIN")) { + else if (auth.contains("PLAIN")) + { qDebug() << "Using PLAIN authentication..."; authPlain(); } - else if (auth.contains("LOGIN")) { + else if (auth.contains("LOGIN")) + { qDebug() << "Using LOGIN authentication..."; authLogin(); } - else { + 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, " @@ -453,13 +494,15 @@ void Smtp::startTLS() void Smtp::authCramMD5(const QByteArray &challenge) { - if (m_state != AuthRequestSent) { + if (m_state != AuthRequestSent) + { m_socket->write("auth cram-md5\r\n"); m_socket->flush(); m_authType = AuthCramMD5; m_state = AuthRequestSent; } - else { + else + { const QByteArray response = m_username.toLatin1() + ' ' + hmacMD5(m_password.toLatin1(), QByteArray::fromBase64(challenge)).toHex(); m_socket->write(response.toBase64() + "\r\n"); @@ -470,7 +513,8 @@ void Smtp::authCramMD5(const QByteArray &challenge) void Smtp::authPlain() { - if (m_state != AuthRequestSent) { + if (m_state != AuthRequestSent) + { m_authType = AuthPlain; // Prepare Auth string QByteArray auth; @@ -489,18 +533,21 @@ void Smtp::authPlain() void Smtp::authLogin() { - if ((m_state != AuthRequestSent) && (m_state != AuthUsernameSent)) { + if ((m_state != AuthRequestSent) && (m_state != AuthUsernameSent)) + { m_socket->write("auth login\r\n"); m_socket->flush(); m_authType = AuthLogin; m_state = AuthRequestSent; } - else if (m_state == AuthRequestSent) { + else if (m_state == AuthRequestSent) + { m_socket->write(m_username.toLatin1().toBase64() + "\r\n"); m_socket->flush(); m_state = AuthUsernameSent; } - else { + else + { m_socket->write(m_password.toLatin1().toBase64() + "\r\n"); m_socket->flush(); m_state = AuthSent; diff --git a/src/base/preferences.cpp b/src/base/preferences.cpp index f58557d9d..13e7f40df 100644 --- a/src/base/preferences.cpp +++ b/src/base/preferences.cpp @@ -306,11 +306,13 @@ bool Preferences::WinStartup() const void Preferences::setWinStartup(const bool b) { QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat); - if (b) { + if (b) + { const QString binPath = '"' + Utils::Fs::toNativePath(qApp->applicationFilePath()) + '"'; settings.setValue("qBittorrent", binPath); } - else { + else + { settings.remove("qBittorrent"); } } @@ -530,7 +532,8 @@ QVector Preferences::getWebUiAuthSubnetWhitelist() const QVector ret; ret.reserve(subnets.size()); - for (const QString &rawSubnet : subnets) { + for (const QString &rawSubnet : subnets) + { bool ok = false; const Utils::Net::Subnet subnet = Utils::Net::parseSubnet(rawSubnet.trimmed(), &ok); if (ok) @@ -977,7 +980,8 @@ void Preferences::setNeverCheckFileAssoc(const bool check) bool Preferences::isTorrentFileAssocSet() { const QSettings settings("HKEY_CURRENT_USER\\Software\\Classes", QSettings::NativeFormat); - if (settings.value(".torrent/Default").toString() != "qBittorrent") { + if (settings.value(".torrent/Default").toString() != "qBittorrent") + { qDebug(".torrent != qBittorrent"); return false; } @@ -1008,13 +1012,15 @@ void Preferences::setTorrentFileAssoc(const bool set) QSettings settings("HKEY_CURRENT_USER\\Software\\Classes", QSettings::NativeFormat); // .Torrent association - if (set) { + if (set) + { const QString oldProgId = settings.value(".torrent/Default").toString(); if (!oldProgId.isEmpty() && (oldProgId != "qBittorrent")) settings.setValue(".torrent/OpenWithProgids/" + oldProgId, ""); settings.setValue(".torrent/Default", "qBittorrent"); } - else if (isTorrentFileAssocSet()) { + else if (isTorrentFileAssocSet()) + { settings.setValue(".torrent/Default", ""); } @@ -1026,7 +1032,8 @@ void Preferences::setMagnetLinkAssoc(const bool set) QSettings settings("HKEY_CURRENT_USER\\Software\\Classes", QSettings::NativeFormat); // Magnet association - if (set) { + if (set) + { const QString commandStr = '"' + qApp->applicationFilePath() + "\" \"%1\""; const QString iconStr = '"' + qApp->applicationFilePath() + "\",1"; @@ -1037,7 +1044,8 @@ void Preferences::setMagnetLinkAssoc(const bool set) settings.setValue("magnet/shell/Default", "open"); settings.setValue("magnet/shell/open/command/Default", Utils::Fs::toNativePath(commandStr)); } - else if (isMagnetLinkAssocSet()) { + else if (isMagnetLinkAssocSet()) + { settings.remove("magnet"); } @@ -1056,9 +1064,11 @@ bool Preferences::isTorrentFileAssocSet() { bool isSet = false; const CFStringRef torrentId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, torrentExtension, NULL); - if (torrentId != NULL) { + if (torrentId != NULL) + { const CFStringRef defaultHandlerId = LSCopyDefaultRoleHandlerForContentType(torrentId, kLSRolesViewer); - if (defaultHandlerId != NULL) { + if (defaultHandlerId != NULL) + { const CFStringRef myBundleId = CFBundleGetIdentifier(CFBundleGetMainBundle()); isSet = CFStringCompare(myBundleId, defaultHandlerId, 0) == kCFCompareEqualTo; CFRelease(defaultHandlerId); @@ -1072,7 +1082,8 @@ bool Preferences::isMagnetLinkAssocSet() { bool isSet = false; const CFStringRef defaultHandlerId = LSCopyDefaultHandlerForURLScheme(magnetUrlScheme); - if (defaultHandlerId != NULL) { + if (defaultHandlerId != NULL) + { const CFStringRef myBundleId = CFBundleGetIdentifier(CFBundleGetMainBundle()); isSet = CFStringCompare(myBundleId, defaultHandlerId, 0) == kCFCompareEqualTo; CFRelease(defaultHandlerId); @@ -1085,7 +1096,8 @@ void Preferences::setTorrentFileAssoc() if (isTorrentFileAssocSet()) return; const CFStringRef torrentId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, torrentExtension, NULL); - if (torrentId != NULL) { + if (torrentId != NULL) + { const CFStringRef myBundleId = CFBundleGetIdentifier(CFBundleGetMainBundle()); LSSetDefaultRoleHandlerForContentType(torrentId, kLSRolesViewer, myBundleId); CFRelease(torrentId); diff --git a/src/base/profile.cpp b/src/base/profile.cpp index 5ffb80022..5d9d2e242 100644 --- a/src/base/profile.cpp +++ b/src/base/profile.cpp @@ -72,7 +72,8 @@ const Profile *Profile::instance() QString Profile::location(const SpecialFolder folder) const { QString result; - switch (folder) { + switch (folder) + { case SpecialFolder::Cache: result = m_profileImpl->cacheLocation(); break; diff --git a/src/base/profile_p.cpp b/src/base/profile_p.cpp index 4ba1b5261..46ebbaf50 100644 --- a/src/base/profile_p.cpp +++ b/src/base/profile_p.cpp @@ -83,7 +83,8 @@ QString Private::DefaultProfile::dataLocation() const const QString dataDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + profileName() + QLatin1Char('/'); - if (QDir(legacyDir).exists()) { + if (QDir(legacyDir).exists()) + { qWarning("The legacy data directory '%s' is used. It is recommended to move its content to '%s'", qUtf8Printable(legacyDir), qUtf8Printable(dataDir)); @@ -178,7 +179,8 @@ QString Private::Converter::toPortablePath(const QString &path) const return path; #ifdef Q_OS_WIN - if (QDir::isAbsolutePath(path)) { + if (QDir::isAbsolutePath(path)) + { const QChar driveLeter = path[0].toUpper(); const QChar baseDriveLetter = m_baseDir.path()[0].toUpper(); const bool onSameDrive = (driveLeter.category() == QChar::Letter_Uppercase) && (driveLeter == baseDriveLetter); diff --git a/src/base/rss/rss_article.cpp b/src/base/rss/rss_article.cpp index 9e88adc3b..6a709ea4a 100644 --- a/src/base/rss/rss_article.cpp +++ b/src/base/rss/rss_article.cpp @@ -126,7 +126,8 @@ QVariantHash Article::data() const void Article::markAsRead() { - if (!m_isRead) { + if (!m_isRead) + { m_isRead = true; m_data[KeyIsRead] = m_isRead; emit read(this); diff --git a/src/base/rss/rss_autodownloader.cpp b/src/base/rss/rss_autodownloader.cpp index 8cc43e940..c93651093 100644 --- a/src/base/rss/rss_autodownloader.cpp +++ b/src/base/rss/rss_autodownloader.cpp @@ -82,7 +82,8 @@ namespace const QJsonObject jsonObj {jsonDoc.object()}; QVector rules; - for (auto it = jsonObj.begin(); it != jsonObj.end(); ++it) { + for (auto it = jsonObj.begin(); it != jsonObj.end(); ++it) + { const QJsonValue jsonVal {it.value()}; if (!jsonVal.isObject()) throw RSS::ParsingError(RSS::AutoDownloader::tr("Invalid data format.")); @@ -177,7 +178,8 @@ QList AutoDownloader::rules() const void AutoDownloader::insertRule(const AutoDownloadRule &rule) { - if (!hasRule(rule.name())) { + if (!hasRule(rule.name())) + { // Insert new rule setRule_impl(rule); m_dirty = true; @@ -185,7 +187,8 @@ void AutoDownloader::insertRule(const AutoDownloadRule &rule) emit ruleAdded(rule.name()); resetProcessingQueue(); } - else if (ruleByName(rule.name()) != rule) { + else if (ruleByName(rule.name()) != rule) + { // Update existing rule setRule_impl(rule); m_dirty = true; @@ -211,7 +214,8 @@ bool AutoDownloader::renameRule(const QString &ruleName, const QString &newRuleN void AutoDownloader::removeRule(const QString &ruleName) { - if (m_rules.contains(ruleName)) { + if (m_rules.contains(ruleName)) + { emit ruleAboutToBeRemoved(ruleName); m_rules.remove(ruleName); m_dirty = true; @@ -221,7 +225,8 @@ void AutoDownloader::removeRule(const QString &ruleName) QByteArray AutoDownloader::exportRules(AutoDownloader::RulesFileFormat format) const { - switch (format) { + switch (format) + { case RulesFileFormat::Legacy: return exportRulesToLegacyFormat(); default: @@ -231,7 +236,8 @@ QByteArray AutoDownloader::exportRules(AutoDownloader::RulesFileFormat format) c void AutoDownloader::importRules(const QByteArray &data, const AutoDownloader::RulesFileFormat format) { - switch (format) { + switch (format) + { case RulesFileFormat::Legacy: importRulesFromLegacyFormat(data); break; @@ -286,8 +292,10 @@ QStringList AutoDownloader::smartEpisodeFilters() const { const QVariant filtersSetting = SettingsStorage::instance()->loadValue(SettingsKey_SmartEpisodeFilter); - if (filtersSetting.isNull()) { - QStringList filters = { + if (filtersSetting.isNull()) + { + QStringList filters = + { "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 @@ -375,7 +383,8 @@ void AutoDownloader::addJobForArticle(const Article *article) void AutoDownloader::processJob(const QSharedPointer &job) { - for (AutoDownloadRule &rule : m_rules) { + for (AutoDownloadRule &rule : m_rules) + { if (!rule.isEnabled()) continue; if (!rule.feedURLs().contains(job->feedURL)) continue; if (!rule.accepts(job->articleData)) continue; @@ -393,13 +402,16 @@ void AutoDownloader::processJob(const QSharedPointer &job) const auto torrentURL = job->articleData.value(Article::KeyTorrentURL).toString(); BitTorrent::Session::instance()->addTorrent(torrentURL, params); - if (BitTorrent::MagnetUri(torrentURL).isValid()) { - if (Feed *feed = Session::instance()->feedByURL(job->feedURL)) { + if (BitTorrent::MagnetUri(torrentURL).isValid()) + { + if (Feed *feed = Session::instance()->feedByURL(job->feedURL)) + { if (Article *article = feed->articleByGUID(job->articleData.value(Article::KeyId).toString())) article->markAsRead(); } } - else { + else + { // waiting for torrent file downloading m_waitingJobs.insert(torrentURL, job); } @@ -423,12 +435,14 @@ void AutoDownloader::load() void AutoDownloader::loadRules(const QByteArray &data) { - try { + try + { const auto rules = rulesFromJSON(data); for (const auto &rule : rules) setRule_impl(rule); } - catch (const ParsingError &error) { + catch (const ParsingError &error) + { LogMsg(tr("Couldn't load RSS AutoDownloader rules. Reason: %1") .arg(error.message()), Log::CRITICAL); } @@ -438,7 +452,8 @@ void AutoDownloader::loadRulesLegacy() { const SettingsPtr settings = Profile::instance()->applicationSettings(QStringLiteral("qBittorrent-rss")); const QVariantHash rules = settings->value(QStringLiteral("download_rules")).toHash(); - for (const QVariant &ruleVar : rules) { + for (const QVariant &ruleVar : rules) + { const auto rule = AutoDownloadRule::fromLegacyDict(ruleVar.toHash()); if (!rule.name().isEmpty()) insertRule(rule); @@ -475,7 +490,8 @@ void AutoDownloader::resetProcessingQueue() m_processingQueue.clear(); if (!m_processingEnabled) return; - for (Article *article : asConst(Session::instance()->rootFolder()->articles())) { + for (Article *article : asConst(Session::instance()->rootFolder()->articles())) + { if (!article->isRead() && !article->torrentUrl().isEmpty()) addJobForArticle(article); } @@ -489,13 +505,16 @@ void AutoDownloader::startProcessing() void AutoDownloader::setProcessingEnabled(const bool enabled) { - if (m_processingEnabled != enabled) { + if (m_processingEnabled != enabled) + { m_processingEnabled = enabled; SettingsStorage::instance()->storeValue(SettingsKey_ProcessingEnabled, m_processingEnabled); - if (m_processingEnabled) { + if (m_processingEnabled) + { startProcessing(); } - else { + else + { m_processingQueue.clear(); disconnect(Session::instance()->rootFolder(), &Folder::newArticle, this, &AutoDownloader::handleNewArticle); } diff --git a/src/base/rss/rss_autodownloadrule.cpp b/src/base/rss/rss_autodownloadrule.cpp index 40f9d1847..ba9c5d18a 100644 --- a/src/base/rss/rss_autodownloadrule.cpp +++ b/src/base/rss/rss_autodownloadrule.cpp @@ -64,7 +64,8 @@ namespace QJsonValue triStateBoolToJsonValue(const TriStateBool triStateBool) { - switch (static_cast(triStateBool)) { + switch (static_cast(triStateBool)) + { case 0: return false; case 1: return true; default: return {}; @@ -73,7 +74,8 @@ namespace TriStateBool addPausedLegacyToTriStateBool(const int val) { - switch (val) { + switch (val) + { case 1: return TriStateBool::True; // always case 2: return TriStateBool::False; // never default: return TriStateBool::Undefined; // default @@ -82,7 +84,8 @@ namespace int triStateBoolToAddPausedLegacy(const TriStateBool triStateBool) { - switch (static_cast(triStateBool)) { + switch (static_cast(triStateBool)) + { case 0: return 2; // never case 1: return 1; // always default: return 0; // default @@ -164,7 +167,8 @@ QString computeEpisodeName(const QString &article) return {}; QStringList ret; - for (int i = 1; i <= match.lastCapturedIndex(); ++i) { + for (int i = 1; i <= match.lastCapturedIndex(); ++i) + { const QString cap = match.captured(i); if (cap.isEmpty()) @@ -199,8 +203,10 @@ QRegularExpression AutoDownloadRule::cachedRegex(const QString &expression, cons Q_ASSERT(!expression.isEmpty()); QRegularExpression ®ex = m_dataPtr->cachedRegexes[expression]; - if (regex.pattern().isEmpty()) { - regex = QRegularExpression { + if (regex.pattern().isEmpty()) + { + regex = QRegularExpression + { (isRegex ? expression : Utils::String::wildcardToRegex(expression)) , QRegularExpression::CaseInsensitiveOption}; } @@ -212,12 +218,14 @@ bool AutoDownloadRule::matchesExpression(const QString &articleTitle, const QStr { const QRegularExpression whitespace {"\\s+"}; - if (expression.isEmpty()) { + if (expression.isEmpty()) + { // A regex of the form "expr|" will always match, so do the same for wildcards return true; } - if (m_dataPtr->useRegex) { + if (m_dataPtr->useRegex) + { const QRegularExpression reg(cachedRegex(expression)); return reg.match(articleTitle).hasMatch(); } @@ -225,7 +233,8 @@ bool AutoDownloadRule::matchesExpression(const QString &articleTitle, const QStr // Only match if every wildcard token (separated by spaces) is present in the article name. // Order of wildcard tokens is unimportant (if order is important, they should have used *). const QStringList wildcards {expression.split(whitespace, QString::SplitBehavior::SkipEmptyParts)}; - for (const QString &wildcard : wildcards) { + for (const QString &wildcard : wildcards) + { const QRegularExpression reg {cachedRegex(wildcard, false)}; if (!reg.match(articleTitle).hasMatch()) return false; @@ -279,7 +288,8 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl const QStringList episodes {matcher.captured(2).split(';')}; const int seasonOurs {season.toInt()}; - for (QString episode : episodes) { + for (QString episode : episodes) + { if (episode.isEmpty()) continue; @@ -287,7 +297,8 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl while ((episode.size() > 1) && episode.startsWith('0')) episode = episode.right(episode.size() - 1); - if (episode.indexOf('-') != -1) { // Range detected + if (episode.indexOf('-') != -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)"}; @@ -295,21 +306,25 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl QRegularExpressionMatch matcher = cachedRegex(partialPattern1).match(articleTitle); bool matched = matcher.hasMatch(); - if (!matched) { + if (!matched) + { matcher = cachedRegex(partialPattern2).match(articleTitle); matched = matcher.hasMatch(); } - if (matched) { + if (matched) + { const int seasonTheirs {matcher.captured(1).toInt()}; const int episodeTheirs {matcher.captured(2).toInt()}; - if (episode.endsWith('-')) { // Infinite range + if (episode.endsWith('-')) + { // Infinite range const int episodeOurs {episode.leftRef(episode.size() - 1).toInt()}; if (((seasonTheirs == seasonOurs) && (episodeTheirs >= episodeOurs)) || (seasonTheirs > seasonOurs)) return true; } - else { // Normal range + else + { // Normal range const QStringList range {episode.split('-')}; Q_ASSERT(range.size() == 2); if (range.first().toInt() > range.last().toInt()) @@ -322,7 +337,8 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl } } } - else { // Single number + else + { // Single number const QString expStr {QString::fromLatin1("\\b(?:s0?%1[ -_\\.]?e0?%2|%1x0?%2)(?:\\D|\\b)").arg(season, episode)}; if (cachedRegex(expStr).match(articleTitle).hasMatch()) return true; @@ -343,7 +359,8 @@ bool AutoDownloadRule::matchesSmartEpisodeFilter(const QString &articleTitle) co // See if this episode has been downloaded before const bool previouslyMatched = m_dataPtr->previouslyMatchedEpisodes.contains(episodeStr); - if (previouslyMatched) { + if (previouslyMatched) + { if (!AutoDownloader::instance()->downloadRepacks()) return false; @@ -365,7 +382,8 @@ bool AutoDownloadRule::matchesSmartEpisodeFilter(const QString &articleTitle) co // If this is a REPACK and PROPER download, add the individual entries to the list // so we don't download those - if (isRepack && isProper) { + if (isRepack && isProper) + { m_dataPtr->lastComputedEpisodes.append(episodeStr + QLatin1String("-REPACK")); m_dataPtr->lastComputedEpisodes.append(episodeStr + QLatin1String("-PROPER")); } @@ -378,7 +396,8 @@ bool AutoDownloadRule::matchesSmartEpisodeFilter(const QString &articleTitle) co bool AutoDownloadRule::matches(const QVariantHash &articleData) const { const QDateTime articleDate {articleData[Article::KeyDate].toDateTime()}; - if (ignoreDays() > 0) { + if (ignoreDays() > 0) + { if (lastMatch().isValid() && (articleDate < lastMatch().addDays(ignoreDays()))) return false; } @@ -404,7 +423,8 @@ bool AutoDownloadRule::accepts(const QVariantHash &articleData) setLastMatch(articleData[Article::KeyDate].toDateTime()); // If there's a matched episode string, add that to the previously matched list - if (!m_dataPtr->lastComputedEpisodes.isEmpty()) { + if (!m_dataPtr->lastComputedEpisodes.isEmpty()) + { m_dataPtr->previouslyMatchedEpisodes.append(m_dataPtr->lastComputedEpisodes); m_dataPtr->lastComputedEpisodes.clear(); } @@ -474,10 +494,12 @@ AutoDownloadRule AutoDownloadRule::fromJsonObject(const QJsonObject &jsonObj, co const QJsonValue previouslyMatchedVal = jsonObj.value(Str_PreviouslyMatched); QStringList previouslyMatched; - if (previouslyMatchedVal.isString()) { + if (previouslyMatchedVal.isString()) + { previouslyMatched << previouslyMatchedVal.toString(); } - else { + else + { for (const QJsonValue &val : asConst(previouslyMatchedVal.toArray())) previouslyMatched << val.toString(); } diff --git a/src/base/rss/rss_feed.cpp b/src/base/rss/rss_feed.cpp index 49f4c197d..a22186037 100644 --- a/src/base/rss/rss_feed.cpp +++ b/src/base/rss/rss_feed.cpp @@ -69,7 +69,8 @@ Feed::Feed(const QUuid &uid, const QString &url, const QString &path, Session *s m_dataFileName = QString::fromLatin1(m_uid.toRfc4122().toHex()) + QLatin1String(".json"); // Move to new file naming scheme (since v4.1.2) - const QString legacyFilename {Utils::Fs::toValidFileSystemName(m_url, false, QLatin1String("_")) + const QString legacyFilename + {Utils::Fs::toValidFileSystemName(m_url, false, QLatin1String("_")) + QLatin1String(".json")}; const QDir storageDir {m_session->dataFileStorage()->storageDir()}; if (!QFile::exists(storageDir.absoluteFilePath(m_dataFileName))) @@ -106,8 +107,10 @@ QList
Feed::articles() const void Feed::markAsRead() { const int oldUnreadCount = m_unreadCount; - for (Article *article : asConst(m_articles)) { - if (!article->isRead()) { + for (Article *article : asConst(m_articles)) + { + if (!article->isRead()) + { article->disconnect(this); article->markAsRead(); --m_unreadCount; @@ -115,7 +118,8 @@ void Feed::markAsRead() } } - if (m_unreadCount != oldUnreadCount) { + if (m_unreadCount != oldUnreadCount) + { m_dirty = true; store(); emit unreadCountChanged(this); @@ -180,7 +184,8 @@ void Feed::handleMaxArticlesPerFeedChanged(const int n) void Feed::handleIconDownloadFinished(const Net::DownloadResult &result) { - if (result.status == Net::DownloadStatus::Success) { + if (result.status == Net::DownloadStatus::Success) + { m_iconPath = Utils::Fs::toUniformPath(result.filePath); emit iconLoaded(this); } @@ -195,13 +200,15 @@ void Feed::handleDownloadFinished(const Net::DownloadResult &result) { m_downloadHandler = nullptr; // will be deleted by DownloadManager later - if (result.status == Net::DownloadStatus::Success) { + if (result.status == Net::DownloadStatus::Success) + { LogMsg(tr("RSS feed at '%1' is successfully downloaded. Starting to parse it.") .arg(result.url)); // Parse the download RSS m_parser->parse(result.data); } - else { + else + { m_isLoading = false; m_hasError = true; @@ -216,13 +223,15 @@ void Feed::handleParsingFinished(const RSS::Private::ParsingResult &result) { m_hasError = !result.error.isEmpty(); - if (!result.title.isEmpty() && (title() != result.title)) { + if (!result.title.isEmpty() && (title() != result.title)) + { m_title = result.title; m_dirty = true; emit titleChanged(this); } - if (!result.lastBuildDate.isEmpty()) { + if (!result.lastBuildDate.isEmpty()) + { m_lastBuildDate = result.lastBuildDate; m_dirty = true; } @@ -234,7 +243,8 @@ void Feed::handleParsingFinished(const RSS::Private::ParsingResult &result) const int newArticlesCount = updateArticles(result.articles); store(); - if (m_hasError) { + if (m_hasError) + { LogMsg(tr("Failed to parse RSS feed at '%1'. Reason: %2").arg(m_url, result.error) , Log::WARNING); } @@ -249,16 +259,19 @@ void Feed::load() { QFile file(m_session->dataFileStorage()->storageDir().absoluteFilePath(m_dataFileName)); - if (!file.exists()) { + if (!file.exists()) + { loadArticlesLegacy(); m_dirty = true; store(); // convert to new format } - else if (file.open(QFile::ReadOnly)) { + else if (file.open(QFile::ReadOnly)) + { loadArticles(file.readAll()); file.close(); } - else { + else + { LogMsg(tr("Couldn't read RSS Session data from %1. Error: %2") .arg(m_dataFileName, file.errorString()) , Log::WARNING); @@ -269,28 +282,33 @@ void Feed::loadArticles(const QByteArray &data) { QJsonParseError jsonError; const QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError); - if (jsonError.error != QJsonParseError::NoError) { + if (jsonError.error != QJsonParseError::NoError) + { LogMsg(tr("Couldn't parse RSS Session data. Error: %1").arg(jsonError.errorString()) , Log::WARNING); return; } - if (!jsonDoc.isArray()) { + if (!jsonDoc.isArray()) + { LogMsg(tr("Couldn't load RSS Session data. Invalid data format."), Log::WARNING); return; } const QJsonArray jsonArr = jsonDoc.array(); int i = -1; - for (const QJsonValue &jsonVal : jsonArr) { + for (const QJsonValue &jsonVal : jsonArr) + { ++i; - if (!jsonVal.isObject()) { + if (!jsonVal.isObject()) + { LogMsg(tr("Couldn't load RSS article '%1#%2'. Invalid data format.").arg(m_url).arg(i) , Log::WARNING); continue; } - try { + try + { auto article = new Article(this, jsonVal.toObject()); if (!addArticle(article)) delete article; @@ -304,13 +322,15 @@ void Feed::loadArticlesLegacy() const SettingsPtr qBTRSSFeeds = Profile::instance()->applicationSettings(QStringLiteral("qBittorrent-rss-feeds")); const QVariantHash allOldItems = qBTRSSFeeds->value("old_items").toHash(); - for (const QVariant &var : asConst(allOldItems.value(m_url).toList())) { + 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")); - try { + try + { auto article = new Article(this, hash); if (!addArticle(article)) delete article; @@ -353,7 +373,8 @@ bool Feed::addArticle(Article *article) m_articles[article->guid()] = article; m_articlesByDate.insert(lowerBound, article); - if (!article->isRead()) { + if (!article->isRead()) + { increaseUnreadCount(); connect(article, &Article::read, this, &Feed::handleArticleRead); } @@ -414,12 +435,14 @@ int Feed::updateArticles(const QList &loadedArticles) QDateTime dummyPubDate {QDateTime::currentDateTime()}; QVector newArticles; newArticles.reserve(loadedArticles.size()); - for (QVariantHash article : loadedArticles) { + for (QVariantHash article : loadedArticles) + { // If article has no publication date we use feed update time as a fallback. // To prevent processing of "out-of-limit" articles we must not assign dates // that are earlier than the dates of existing articles. const Article *existingArticle = articleByGUID(article[Article::KeyId].toString()); - if (existingArticle) { + if (existingArticle) + { dummyPubDate = existingArticle->date().addMSecs(-1); continue; } @@ -462,7 +485,8 @@ int Feed::updateArticles(const QList &loadedArticles) int newArticlesCount = 0; std::for_each(sortData.crbegin(), sortData.crend(), [this, &newArticlesCount](const ArticleSortAdaptor &a) { - if (a.second) { + if (a.second) + { addArticle(new Article {this, *a.second}); ++newArticlesCount; } @@ -482,7 +506,8 @@ QJsonValue Feed::toJsonValue(const bool withData) const jsonObj.insert(KEY_UID, uid().toString()); jsonObj.insert(KEY_URL, url()); - if (withData) { + if (withData) + { jsonObj.insert(KEY_TITLE, title()); jsonObj.insert(KEY_LASTBUILDDATE, lastBuildDate()); jsonObj.insert(KEY_ISLOADING, isLoading()); @@ -499,7 +524,8 @@ QJsonValue Feed::toJsonValue(const bool withData) const void Feed::handleSessionProcessingEnabledChanged(const bool enabled) { - if (enabled) { + if (enabled) + { downloadIcon(); disconnect(m_session, &Session::processingStateChanged , this, &Feed::handleSessionProcessingEnabledChanged); diff --git a/src/base/rss/rss_folder.cpp b/src/base/rss/rss_folder.cpp index 4616b4dde..01a8ac70a 100644 --- a/src/base/rss/rss_folder.cpp +++ b/src/base/rss/rss_folder.cpp @@ -57,7 +57,8 @@ QList
Folder::articles() const { QList
news; - for (Item *item : asConst(items())) { + for (Item *item : asConst(items())) + { int n = news.size(); news << item->articles(); std::inplace_merge(news.begin(), news.begin() + n, news.end() diff --git a/src/base/rss/rss_item.cpp b/src/base/rss/rss_item.cpp index 37d55102e..f1a337154 100644 --- a/src/base/rss/rss_item.cpp +++ b/src/base/rss/rss_item.cpp @@ -47,7 +47,8 @@ Item::~Item() {} void Item::setPath(const QString &path) { - if (path != m_path) { + if (path != m_path) + { m_path = path; emit pathChanged(this); } @@ -69,7 +70,8 @@ bool Item::isValidPath(const QString &path) QString(R"(\A[^\%1]+(\%1[^\%1]+)*\z)").arg(Item::PathSeparator) , QRegularExpression::DontCaptureOption); - if (path.isEmpty() || !re.match(path).hasMatch()) { + if (path.isEmpty() || !re.match(path).hasMatch()) + { qDebug() << "Incorrect RSS Item path:" << path; return false; } @@ -93,7 +95,8 @@ QStringList Item::expandPath(const QString &path) // return result; int index = 0; - while ((index = path.indexOf(Item::PathSeparator, index)) >= 0) { + while ((index = path.indexOf(Item::PathSeparator, index)) >= 0) + { result << path.left(index); ++index; } diff --git a/src/base/rss/rss_parser.cpp b/src/base/rss/rss_parser.cpp index 55d0194a0..db710f9e5 100644 --- a/src/base/rss/rss_parser.cpp +++ b/src/base/rss/rss_parser.cpp @@ -53,7 +53,8 @@ namespace // http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent // http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent // http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent - static const QHash HTMLEntities { + static const QHash HTMLEntities + { {"nbsp", " "}, // no-break space = non-breaking space, U+00A0 ISOnum {"iexcl", "¡"}, // inverted exclamation mark, U+00A1 ISOnum {"cent", "¢"}, // cent sign, U+00A2 ISOnum @@ -359,17 +360,20 @@ namespace // Ported to Qt from KDElibs4 QDateTime parseDate(const QString &string) { - const char shortDay[][4] = { + const char shortDay[][4] = + { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }; - const char longDay[][10] = { + const char longDay[][10] = + { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; - const char shortMonth[][4] = { + const char shortMonth[][4] = + { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" @@ -389,7 +393,8 @@ namespace // Also accept obsolete form "Weekday, DD-Mon-YY HH:MM:SS ±hhmm" QRegExp rx("^(?:([A-Z][a-z]+),\\s*)?(\\d{1,2})(\\s+|-)([^-\\s]+)(\\s+|-)(\\d{2,4})\\s+(\\d\\d):(\\d\\d)(?::(\\d\\d))?\\s+(\\S+)$"); QStringList parts; - if (!str.indexOf(rx)) { + if (!str.indexOf(rx)) + { // Check that if date has '-' separators, both separators are '-'. parts = rx.capturedTexts(); const bool h1 = (parts[3] == QLatin1String("-")); @@ -397,7 +402,8 @@ namespace if (h1 != h2) return QDateTime::currentDateTime(); } - else { + else + { // Check for the obsolete form "Wdy Mon DD HH:MM:SS YYYY" rx = QRegExp("^([A-Z][a-z]+)\\s+(\\S+)\\s+(\\d\\d)\\s+(\\d\\d):(\\d\\d):(\\d\\d)\\s+(\\d\\d\\d\\d)$"); if (str.indexOf(rx)) @@ -421,7 +427,8 @@ namespace return QDateTime::currentDateTime(); int second = 0; - if (!parts[nsec].isEmpty()) { + if (!parts[nsec].isEmpty()) + { second = parts[nsec].toInt(&ok[0]); if (!ok[0]) return QDateTime::currentDateTime(); @@ -433,7 +440,8 @@ namespace int month = 0; for ( ; (month < 12) && (parts[nmonth] != shortMonth[month]); ++month); int dayOfWeek = -1; - if (!parts[nwday].isEmpty()) { + if (!parts[nwday].isEmpty()) + { // Look up the weekday name while ((++dayOfWeek < 7) && (shortDay[dayOfWeek] != parts[nwday])); if (dayOfWeek >= 7) @@ -444,7 +452,8 @@ namespace // || (dayOfWeek < 0 && format == RFCDateDay)) // return QDateTime; const int i = parts[nyear].size(); - if (i < 4) { + if (i < 4) + { // It's an obsolete year specification with less than 4 digits year += ((i == 2) && (year < 50)) ? 2000 : 1900; } @@ -452,9 +461,11 @@ namespace // Parse the UTC offset part int offset = 0; // set default to '-0000' bool negOffset = false; - if (parts.count() > 10) { + if (parts.count() > 10) + { rx = QRegExp("^([+-])(\\d\\d)(\\d\\d)$"); - if (!parts[10].indexOf(rx)) { + if (!parts[10].indexOf(rx)) + { // It's a UTC offset ±hhmm parts = rx.capturedTexts(); offset = parts[2].toInt(&ok[0]) * 3600; @@ -466,13 +477,16 @@ namespace if (negOffset) offset = -offset; } - else { + else + { // Check for an obsolete time zone name const QByteArray zone = parts[10].toLatin1(); - if ((zone.length() == 1) && (isalpha(zone[0])) && (toupper(zone[0]) != 'J')) { + if ((zone.length() == 1) && (isalpha(zone[0])) && (toupper(zone[0]) != 'J')) + { negOffset = true; // military zone: RFC 2822 treats as '-0000' } - else if ((zone != "UT") && (zone != "GMT")) { // treated as '+0000' + else if ((zone != "UT") && (zone != "GMT")) + { // treated as '+0000' offset = (zone == "EDT") ? -4 * 3600 : ((zone == "EST") || (zone == "CDT")) @@ -484,7 +498,8 @@ namespace : (zone == "PST") ? -8 * 3600 : 0; - if (!offset) { + if (!offset) + { // Check for any other alphabetic time zone bool nonalpha = false; for (int i = 0, end = zone.size(); (i < end) && !nonalpha; ++i) @@ -509,7 +524,8 @@ namespace if (!result.isValid()) return QDateTime::currentDateTime(); // invalid date/time - if (leapSecond) { + if (leapSecond) + { // Validate a leap second time. Leap seconds are inserted after 23:59:59 UTC. // Convert the time to UTC and check that it is 00:00:00. if ((hour*3600 + minute*60 + 60 - offset + 86400*5) % 86400) // (max abs(offset) is 100 hours) @@ -548,11 +564,15 @@ void Parser::parse_impl(const QByteArray &feedData) xml.setEntityResolver(&resolver); bool foundChannel = false; - while (xml.readNextStartElement()) { - if (xml.name() == "rss") { + while (xml.readNextStartElement()) + { + if (xml.name() == "rss") + { // Find channels - while (xml.readNextStartElement()) { - if (xml.name() == "channel") { + while (xml.readNextStartElement()) + { + if (xml.name() == "channel") + { parseRSSChannel(xml); foundChannel = true; break; @@ -563,7 +583,8 @@ void Parser::parse_impl(const QByteArray &feedData) } break; } - if (xml.name() == "feed") { // Atom feed + if (xml.name() == "feed") + { // Atom feed parseAtomChannel(xml); foundChannel = true; break; @@ -573,10 +594,12 @@ void Parser::parse_impl(const QByteArray &feedData) xml.skipCurrentElement(); } - if (!foundChannel) { + if (!foundChannel) + { m_result.error = tr("Invalid RSS feed."); } - else if (xml.hasError()) { + else if (xml.hasError()) + { m_result.error = tr("%1 (line: %2, column: %3, offset: %4).") .arg(xml.errorString()).arg(xml.lineNumber()) .arg(xml.columnNumber()).arg(xml.characterOffset()); @@ -592,43 +615,53 @@ void Parser::parseRssArticle(QXmlStreamReader &xml) QVariantHash article; QString altTorrentUrl; - while (!xml.atEnd()) { + while (!xml.atEnd()) + { xml.readNext(); const QString name(xml.name().toString()); if (xml.isEndElement() && (name == QLatin1String("item"))) break; - if (xml.isStartElement()) { - if (name == QLatin1String("title")) { + if (xml.isStartElement()) + { + if (name == QLatin1String("title")) + { article[Article::KeyTitle] = xml.readElementText().trimmed(); } - else if (name == QLatin1String("enclosure")) { + else if (name == QLatin1String("enclosure")) + { if (xml.attributes().value("type") == QLatin1String("application/x-bittorrent")) article[Article::KeyTorrentURL] = xml.attributes().value(QLatin1String("url")).toString(); else if (xml.attributes().value("type").isEmpty()) altTorrentUrl = xml.attributes().value(QLatin1String("url")).toString(); } - else if (name == QLatin1String("link")) { + else if (name == QLatin1String("link")) + { const QString text {xml.readElementText().trimmed()}; if (text.startsWith(QLatin1String("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 == QLatin1String("description")) + { article[Article::KeyDescription] = xml.readElementText(QXmlStreamReader::IncludeChildElements); } - else if (name == QLatin1String("pubDate")) { + else if (name == QLatin1String("pubDate")) + { article[Article::KeyDate] = parseDate(xml.readElementText().trimmed()); } - else if (name == QLatin1String("author")) { + else if (name == QLatin1String("author")) + { article[Article::KeyAuthor] = xml.readElementText().trimmed(); } - else if (name == QLatin1String("guid")) { + else if (name == QLatin1String("guid")) + { article[Article::KeyId] = xml.readElementText().trimmed(); } - else { + else + { article[name] = xml.readElementText(QXmlStreamReader::IncludeChildElements); } } @@ -642,24 +675,31 @@ void Parser::parseRssArticle(QXmlStreamReader &xml) void Parser::parseRSSChannel(QXmlStreamReader &xml) { - while (!xml.atEnd()) { + while (!xml.atEnd()) + { xml.readNext(); - if (xml.isStartElement()) { - if (xml.name() == QLatin1String("title")) { + if (xml.isStartElement()) + { + if (xml.name() == QLatin1String("title")) + { m_result.title = xml.readElementText(); } - else if (xml.name() == QLatin1String("lastBuildDate")) { + else if (xml.name() == QLatin1String("lastBuildDate")) + { const QString lastBuildDate = xml.readElementText(); - if (!lastBuildDate.isEmpty()) { - if (m_result.lastBuildDate == lastBuildDate) { + if (!lastBuildDate.isEmpty()) + { + if (m_result.lastBuildDate == lastBuildDate) + { qDebug() << "The RSS feed has not changed since last time, aborting parsing."; return; } m_result.lastBuildDate = lastBuildDate; } } - else if (xml.name() == QLatin1String("item")) { + else if (xml.name() == QLatin1String("item")) + { parseRssArticle(xml); } } @@ -671,18 +711,22 @@ void Parser::parseAtomArticle(QXmlStreamReader &xml) QVariantHash article; bool doubleContent = false; - while (!xml.atEnd()) { + while (!xml.atEnd()) + { xml.readNext(); const QString name(xml.name().toString()); if (xml.isEndElement() && (name == QLatin1String("entry"))) break; - if (xml.isStartElement()) { - if (name == QLatin1String("title")) { + if (xml.isStartElement()) + { + if (name == QLatin1String("title")) + { article[Article::KeyTitle] = xml.readElementText().trimmed(); } - else if (name == QLatin1String("link")) { + else if (name == QLatin1String("link")) + { const QString link = (xml.attributes().isEmpty() ? xml.readElementText().trimmed() : xml.attributes().value(QLatin1String("href")).toString()); @@ -696,8 +740,10 @@ void Parser::parseAtomArticle(QXmlStreamReader &xml) article[Article::KeyLink] = (m_baseUrl.isEmpty() ? link : m_baseUrl + link); } - else if ((name == QLatin1String("summary")) || (name == QLatin1String("content"))) { - if (doubleContent) { // Duplicate content -> ignore + else if ((name == QLatin1String("summary")) || (name == QLatin1String("content"))) + { + if (doubleContent) + { // Duplicate content -> ignore xml.skipCurrentElement(); continue; } @@ -705,28 +751,34 @@ void Parser::parseAtomArticle(QXmlStreamReader &xml) // Try to also parse broken articles, which don't use html '&' escapes // Actually works great for non-broken content too const QString feedText = xml.readElementText(QXmlStreamReader::IncludeChildElements).trimmed(); - if (!feedText.isEmpty()) { + if (!feedText.isEmpty()) + { article[Article::KeyDescription] = feedText; doubleContent = true; } } - else if (name == QLatin1String("updated")) { + else if (name == QLatin1String("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")) { - while (xml.readNextStartElement()) { + else if (name == QLatin1String("author")) + { + while (xml.readNextStartElement()) + { if (xml.name() == QLatin1String("name")) article[Article::KeyAuthor] = xml.readElementText().trimmed(); else xml.skipCurrentElement(); } } - else if (name == QLatin1String("id")) { + else if (name == QLatin1String("id")) + { article[Article::KeyId] = xml.readElementText().trimmed(); } - else { + else + { article[name] = xml.readElementText(QXmlStreamReader::IncludeChildElements); } } @@ -739,24 +791,31 @@ void Parser::parseAtomChannel(QXmlStreamReader &xml) { m_baseUrl = xml.attributes().value("xml:base").toString(); - while (!xml.atEnd()) { + while (!xml.atEnd()) + { xml.readNext(); - if (xml.isStartElement()) { - if (xml.name() == QLatin1String("title")) { + if (xml.isStartElement()) + { + if (xml.name() == QLatin1String("title")) + { m_result.title = xml.readElementText(); } - else if (xml.name() == QLatin1String("updated")) { + else if (xml.name() == QLatin1String("updated")) + { const QString lastBuildDate = xml.readElementText(); - if (!lastBuildDate.isEmpty()) { - if (m_result.lastBuildDate == lastBuildDate) { + if (!lastBuildDate.isEmpty()) + { + if (m_result.lastBuildDate == lastBuildDate) + { qDebug() << "The RSS feed has not changed since last time, aborting parsing."; return; } m_result.lastBuildDate = lastBuildDate; } } - else if (xml.name() == QLatin1String("entry")) { + else if (xml.name() == QLatin1String("entry")) + { parseAtomArticle(xml); } } @@ -776,14 +835,16 @@ void Parser::addArticle(QVariantHash article) if (localId.toString().isEmpty()) localId = article.value(Article::KeyTitle); - if (localId.toString().isEmpty()) { + if (localId.toString().isEmpty()) + { // The article could not be uniquely identified // since it has no appropriate data. // Just ignore it. return; } - if (m_articleIDs.contains(localId.toString())) { + if (m_articleIDs.contains(localId.toString())) + { // The article could not be uniquely identified // since the Feed has duplicate identifiers. // Just ignore it. diff --git a/src/base/rss/rss_session.cpp b/src/base/rss/rss_session.cpp index 9bcfdeb91..04e39e26a 100644 --- a/src/base/rss/rss_session.cpp +++ b/src/base/rss/rss_session.cpp @@ -97,7 +97,8 @@ Session::Session() load(); connect(&m_refreshTimer, &QTimer::timeout, this, &Session::refresh); - if (m_processingEnabled) { + if (m_processingEnabled) + { m_refreshTimer.start(m_refreshInterval * MsecsPerMin); refresh(); } @@ -155,7 +156,8 @@ bool Session::addFolder(const QString &path, QString *error) bool Session::addFeed(const QString &url, const QString &path, QString *error) { - if (m_feedsByURL.contains(url)) { + if (m_feedsByURL.contains(url)) + { if (error) *error = tr("RSS feed with given URL already exists: %1.").arg(url); return false; @@ -174,14 +176,16 @@ bool Session::addFeed(const QString &url, const QString &path, QString *error) bool Session::moveItem(const QString &itemPath, const QString &destPath, QString *error) { - if (itemPath.isEmpty()) { + if (itemPath.isEmpty()) + { if (error) *error = tr("Cannot move root folder."); return false; } auto item = m_itemsByPath.value(itemPath); - if (!item) { + if (!item) + { if (error) *error = tr("Item doesn't exist: %1.").arg(itemPath); return false; @@ -200,7 +204,8 @@ bool Session::moveItem(Item *item, const QString &destPath, QString *error) return false; auto srcFolder = static_cast(m_itemsByPath.value(Item::parentPath(item->path()))); - if (srcFolder != destFolder) { + if (srcFolder != destFolder) + { srcFolder->removeItem(item); destFolder->addItem(item); } @@ -212,14 +217,16 @@ bool Session::moveItem(Item *item, const QString &destPath, QString *error) bool Session::removeItem(const QString &itemPath, QString *error) { - if (itemPath.isEmpty()) { + if (itemPath.isEmpty()) + { if (error) *error = tr("Cannot delete root folder."); return false; } auto item = m_itemsByPath.value(itemPath); - if (!item) { + if (!item) + { if (error) *error = tr("Item doesn't exist: %1.").arg(itemPath); return false; @@ -248,12 +255,14 @@ Item *Session::itemByPath(const QString &path) const void Session::load() { QFile itemsFile(m_confFileStorage->storageDir().absoluteFilePath(FeedsFileName)); - if (!itemsFile.exists()) { + if (!itemsFile.exists()) + { loadLegacy(); return; } - if (!itemsFile.open(QFile::ReadOnly)) { + 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); @@ -262,14 +271,16 @@ void Session::load() QJsonParseError jsonError; const QJsonDocument jsonDoc = QJsonDocument::fromJson(itemsFile.readAll(), &jsonError); - if (jsonError.error != QJsonParseError::NoError) { + 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); return; } - if (!jsonDoc.isObject()) { + if (!jsonDoc.isObject()) + { Logger::instance()->addMessage( QString("Couldn't load RSS Session data from %1. Invalid data format.") .arg(itemsFile.fileName()), Log::WARNING); @@ -282,9 +293,11 @@ void Session::load() void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder) { bool updated = false; - for (const QString &key : asConst(jsonObj.keys())) { + for (const QString &key : asConst(jsonObj.keys())) + { const QJsonValue val {jsonObj[key]}; - if (val.isString()) { + if (val.isString()) + { // previous format (reduced form) doesn't contain UID QString url = val.toString(); if (url.isEmpty()) @@ -292,31 +305,38 @@ void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder) addFeedToFolder(generateUID(), url, key, folder); updated = true; } - else if (val.isObject()) { + else if (val.isObject()) + { const QJsonObject valObj {val.toObject()}; - if (valObj.contains("url")) { - if (!valObj["url"].isString()) { + if (valObj.contains("url")) + { + if (!valObj["url"].isString()) + { LogMsg(tr("Couldn't load RSS Feed '%1'. URL is required.") .arg(QString("%1\\%2").arg(folder->path(), key)), Log::WARNING); continue; } QUuid uid; - if (valObj.contains("uid")) { + if (valObj.contains("uid")) + { uid = QUuid {valObj["uid"].toString()}; - if (uid.isNull()) { + if (uid.isNull()) + { LogMsg(tr("Couldn't load RSS Feed '%1'. UID is invalid.") .arg(QString("%1\\%2").arg(folder->path(), key)), Log::WARNING); continue; } - if (m_feedsByUID.contains(uid)) { + if (m_feedsByUID.contains(uid)) + { LogMsg(tr("Duplicate RSS Feed UID: %1. Configuration seems to be corrupted.") .arg(uid.toString()), Log::WARNING); continue; } } - else { + else + { // previous format doesn't contain UID uid = generateUID(); updated = true; @@ -324,11 +344,13 @@ void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder) addFeedToFolder(uid, valObj["url"].toString(), key, folder); } - else { + else + { loadFolder(valObj, addSubfolder(key, folder)); } } - else { + else + { LogMsg(tr("Couldn't load RSS Item '%1'. Invalid data format.") .arg(QString::fromLatin1("%1\\%2").arg(folder->path(), key)), Log::WARNING); } @@ -342,13 +364,15 @@ void Session::loadLegacy() { const QStringList legacyFeedPaths = SettingsStorage::instance()->loadValue("Rss/streamList").toStringList(); const QStringList feedAliases = SettingsStorage::instance()->loadValue("Rss/streamAlias").toStringList(); - if (legacyFeedPaths.size() != feedAliases.size()) { + if (legacyFeedPaths.size() != feedAliases.size()) + { Logger::instance()->addMessage("Corrupted RSS list, not loading it.", Log::WARNING); return; } uint i = 0; - for (QString legacyPath : legacyFeedPaths) { + for (QString legacyPath : legacyFeedPaths) + { if (Item::PathSeparator == QString(legacyPath[0])) legacyPath.remove(0, 1); const QString parentFolderPath = Item::parentPath(legacyPath); @@ -374,13 +398,15 @@ void Session::store() Folder *Session::prepareItemDest(const QString &path, QString *error) { - if (!Item::isValidPath(path)) { + if (!Item::isValidPath(path)) + { if (error) *error = tr("Incorrect RSS Item path: %1.").arg(path); return nullptr; } - if (m_itemsByPath.contains(path)) { + if (m_itemsByPath.contains(path)) + { if (error) *error = tr("RSS item with given path already exists: %1.").arg(path); return nullptr; @@ -388,7 +414,8 @@ Folder *Session::prepareItemDest(const QString &path, QString *error) const QString destFolderPath = Item::parentPath(path); auto destFolder = qobject_cast(m_itemsByPath.value(destFolderPath)); - if (!destFolder) { + if (!destFolder) + { if (error) *error = tr("Parent folder doesn't exist: %1.").arg(destFolderPath); return nullptr; @@ -413,7 +440,8 @@ Feed *Session::addFeedToFolder(const QUuid &uid, const QString &url, const QStri void Session::addItem(Item *item, Folder *destFolder) { - if (auto feed = qobject_cast(item)) { + if (auto feed = qobject_cast(item)) + { connect(feed, &Feed::titleChanged, this, &Session::handleFeedTitleChanged); connect(feed, &Feed::iconLoaded, this, &Session::feedIconLoaded); connect(feed, &Feed::stateChanged, this, &Session::feedStateChanged); @@ -435,14 +463,17 @@ bool Session::isProcessingEnabled() const void Session::setProcessingEnabled(bool enabled) { - if (m_processingEnabled != enabled) { + if (m_processingEnabled != enabled) + { m_processingEnabled = enabled; SettingsStorage::instance()->storeValue(SettingsKey_ProcessingEnabled, m_processingEnabled); - if (m_processingEnabled) { + if (m_processingEnabled) + { m_refreshTimer.start(m_refreshInterval * MsecsPerMin); refresh(); } - else { + else + { m_refreshTimer.stop(); } @@ -482,7 +513,8 @@ int Session::refreshInterval() const void Session::setRefreshInterval(const int refreshInterval) { - if (m_refreshInterval != refreshInterval) { + if (m_refreshInterval != refreshInterval) + { SettingsStorage::instance()->storeValue(SettingsKey_RefreshInterval, refreshInterval); m_refreshInterval = refreshInterval; m_refreshTimer.start(m_refreshInterval * MsecsPerMin); @@ -498,7 +530,8 @@ void Session::handleItemAboutToBeDestroyed(Item *item) { m_itemsByPath.remove(item->path()); auto feed = qobject_cast(item); - if (feed) { + if (feed) + { m_feedsByUID.remove(feed->uid()); m_feedsByURL.remove(feed->url()); } @@ -528,7 +561,8 @@ int Session::maxArticlesPerFeed() const void Session::setMaxArticlesPerFeed(const int n) { - if (m_maxArticlesPerFeed != n) { + if (m_maxArticlesPerFeed != n) + { m_maxArticlesPerFeed = n; SettingsStorage::instance()->storeValue(SettingsKey_MaxArticlesPerFeed, n); emit maxArticlesPerFeedChanged(n); diff --git a/src/base/rss/rss_session.h b/src/base/rss/rss_session.h index c31acee4b..e25347e75 100644 --- a/src/base/rss/rss_session.h +++ b/src/base/rss/rss_session.h @@ -34,20 +34,26 @@ * RSS Session configuration file format (JSON): * * =============== BEGIN =============== - * { - * "folder1": { - * "subfolder1": { - * "Feed name 1 (Alias)": { + * + { + * "folder1": + { + * "subfolder1": + { + * "Feed name 1 (Alias)": + { * "uid": "feed unique identifier", * "url": "http://some-feed-url1" * } - * "Feed name 2 (Alias)": { + * "Feed name 2 (Alias)": + { * "uid": "feed unique identifier", * "url": "http://some-feed-url2" * } * }, * "subfolder2": {}, - * "Feed name 3 (Alias)": { + * "Feed name 3 (Alias)": + { * "uid": "feed unique identifier", * "url": "http://some-feed-url3" * } diff --git a/src/base/scanfoldersmodel.cpp b/src/base/scanfoldersmodel.cpp index 9d9041bed..97a718a01 100644 --- a/src/base/scanfoldersmodel.cpp +++ b/src/base/scanfoldersmodel.cpp @@ -106,17 +106,21 @@ QVariant ScanFoldersModel::data(const QModelIndex &index, int role) const const PathData *pathData = m_pathList.at(index.row()); QVariant value; - switch (index.column()) { + switch (index.column()) + { case WATCH: if (role == Qt::DisplayRole) value = Utils::Fs::toNativePath(pathData->watchPath); break; case DOWNLOAD: - if (role == Qt::UserRole) { + if (role == Qt::UserRole) + { value = pathData->downloadType; } - else if (role == Qt::DisplayRole) { - switch (pathData->downloadType) { + else if (role == Qt::DisplayRole) + { + switch (pathData->downloadType) + { case DOWNLOAD_IN_WATCH_FOLDER: case DEFAULT_LOCATION: value = pathTypeDisplayName(pathData->downloadType); @@ -139,7 +143,8 @@ QVariant ScanFoldersModel::headerData(int section, Qt::Orientation orientation, QVariant title; - switch (section) { + switch (section) + { case WATCH: title = tr("Monitored Folder"); break; @@ -158,7 +163,8 @@ Qt::ItemFlags ScanFoldersModel::flags(const QModelIndex &index) const Qt::ItemFlags flags; - switch (index.column()) { + switch (index.column()) + { case WATCH: flags = QAbstractListModel::flags(index); break; @@ -176,7 +182,8 @@ bool ScanFoldersModel::setData(const QModelIndex &index, const QVariant &value, || (index.column() != DOWNLOAD)) return false; - if (role == Qt::UserRole) { + if (role == Qt::UserRole) + { const auto type = static_cast(value.toInt()); if (type == CUSTOM_LOCATION) return false; @@ -185,7 +192,8 @@ bool ScanFoldersModel::setData(const QModelIndex &index, const QVariant &value, m_pathList[index.row()]->downloadPath.clear(); emit dataChanged(index, index); } - else if (role == Qt::DisplayRole) { + else if (role == Qt::DisplayRole) + { const QString path = value.toString(); if (path.isEmpty()) // means we didn't pass CUSTOM_LOCATION type return false; @@ -194,7 +202,8 @@ bool ScanFoldersModel::setData(const QModelIndex &index, const QVariant &value, m_pathList[index.row()]->downloadPath = Utils::Fs::toNativePath(path); emit dataChanged(index, index); } - else { + else + { return false; } @@ -213,7 +222,8 @@ ScanFoldersModel::PathStatus ScanFoldersModel::addPath(const QString &watchPath, const QDir downloadDir(downloadPath); const QString canonicalDownloadPath = downloadDir.canonicalPath(); - if (!m_fsWatcher) { + if (!m_fsWatcher) + { m_fsWatcher = new FileSystemWatcher(this); connect(m_fsWatcher, &FileSystemWatcher::torrentsAdded, this, &ScanFoldersModel::addTorrentsToSession); } @@ -249,7 +259,8 @@ void ScanFoldersModel::addToFSWatcher(const QStringList &watchPaths) if (!m_fsWatcher) return; // addPath() wasn't called before this - for (const QString &path : watchPaths) { + for (const QString &path : watchPaths) + { const QDir watchDir(path); const QString canonicalWatchPath = watchDir.canonicalPath(); m_fsWatcher->addPath(canonicalWatchPath); @@ -321,7 +332,8 @@ void ScanFoldersModel::makePersistent() { QVariantHash dirs; - for (const PathData *pathData : asConst(m_pathList)) { + for (const PathData *pathData : asConst(m_pathList)) + { if (pathData->downloadType == CUSTOM_LOCATION) dirs.insert(Utils::Fs::toUniformPath(pathData->watchPath), Utils::Fs::toUniformPath(pathData->downloadPath)); else @@ -335,7 +347,8 @@ void ScanFoldersModel::configure() { const QVariantHash dirs = Preferences::instance()->getScanDirs(); - for (auto i = dirs.cbegin(); i != dirs.cend(); ++i) { + for (auto i = dirs.cbegin(); i != dirs.cend(); ++i) + { if (i.value().type() == QVariant::Int) addPath(i.key(), static_cast(i.value().toInt()), QString()); else @@ -345,22 +358,27 @@ void ScanFoldersModel::configure() void ScanFoldersModel::addTorrentsToSession(const QStringList &pathList) { - for (const QString &file : pathList) { + for (const QString &file : pathList) + { qDebug("File %s added", qUtf8Printable(file)); BitTorrent::AddTorrentParams params; - if (downloadInWatchFolder(file)) { + if (downloadInWatchFolder(file)) + { params.savePath = QFileInfo(file).dir().path(); params.useAutoTMM = TriStateBool::False; } - else if (!downloadInDefaultFolder(file)) { + else if (!downloadInDefaultFolder(file)) + { params.savePath = downloadPathTorrentFolder(file); params.useAutoTMM = TriStateBool::False; } - if (file.endsWith(".magnet", Qt::CaseInsensitive)) { + if (file.endsWith(".magnet", Qt::CaseInsensitive)) + { QFile f(file); - if (f.open(QIODevice::ReadOnly | QIODevice::Text)) { + if (f.open(QIODevice::ReadOnly | QIODevice::Text)) + { QTextStream str(&f); while (!str.atEnd()) BitTorrent::Session::instance()->addTorrent(str.readLine(), params); @@ -368,17 +386,21 @@ void ScanFoldersModel::addTorrentsToSession(const QStringList &pathList) f.close(); Utils::Fs::forceRemove(file); } - else { + else + { qDebug("Failed to open magnet file: %s", qUtf8Printable(f.errorString())); } } - else { + else + { const BitTorrent::TorrentInfo torrentInfo = BitTorrent::TorrentInfo::loadFromFile(file); - if (torrentInfo.isValid()) { + if (torrentInfo.isValid()) + { BitTorrent::Session::instance()->addTorrent(torrentInfo, params); Utils::Fs::forceRemove(file); } - else { + else + { qDebug("Ignoring incomplete torrent file: %s", qUtf8Printable(file)); } } @@ -387,7 +409,8 @@ void ScanFoldersModel::addTorrentsToSession(const QStringList &pathList) QString ScanFoldersModel::pathTypeDisplayName(const PathType type) { - switch (type) { + switch (type) + { case DOWNLOAD_IN_WATCH_FOLDER: return tr("Monitored folder"); case DEFAULT_LOCATION: diff --git a/src/base/search/searchdownloadhandler.cpp b/src/base/search/searchdownloadhandler.cpp index 0887bca8b..8fd823c0d 100644 --- a/src/base/search/searchdownloadhandler.cpp +++ b/src/base/search/searchdownloadhandler.cpp @@ -42,7 +42,8 @@ SearchDownloadHandler::SearchDownloadHandler(const QString &siteUrl, const QStri m_downloadProcess->setEnvironment(QProcess::systemEnvironment()); connect(m_downloadProcess, qOverload(&QProcess::finished) , this, &SearchDownloadHandler::downloadProcessFinished); - const QStringList params { + const QStringList params + { Utils::Fs::toNativePath(m_manager->engineLocation() + "/nova2dl.py"), siteUrl, url @@ -55,7 +56,8 @@ void SearchDownloadHandler::downloadProcessFinished(int exitcode) { QString path; - if ((exitcode == 0) && (m_downloadProcess->exitStatus() == QProcess::NormalExit)) { + if ((exitcode == 0) && (m_downloadProcess->exitStatus() == QProcess::NormalExit)) + { const QString line = QString::fromUtf8(m_downloadProcess->readAllStandardOutput()).trimmed(); const QVector parts = line.splitRef(' '); if (parts.size() == 2) diff --git a/src/base/search/searchhandler.cpp b/src/base/search/searchhandler.cpp index 903fe46d0..0d71d8c3b 100644 --- a/src/base/search/searchhandler.cpp +++ b/src/base/search/searchhandler.cpp @@ -64,7 +64,8 @@ SearchHandler::SearchHandler(const QString &pattern, const QString &category, co // Load environment variables (proxy) m_searchProcess->setEnvironment(QProcess::systemEnvironment()); - const QStringList params { + const QStringList params + { Utils::Fs::toNativePath(m_manager->engineLocation() + "/nova2.py"), m_usedPlugins.join(','), m_category @@ -137,13 +138,15 @@ void SearchHandler::readSearchOutput() QVector searchResultList; searchResultList.reserve(lines.size()); - for (const QByteArray &line : asConst(lines)) { + for (const QByteArray &line : asConst(lines)) + { SearchResult searchResult; if (parseSearchResult(QString::fromUtf8(line), searchResult)) searchResultList << searchResult; } - if (!searchResultList.isEmpty()) { + if (!searchResultList.isEmpty()) + { for (const SearchResult &result : searchResultList) m_results.append(result); emit newSearchResults(searchResultList); diff --git a/src/base/search/searchpluginmanager.cpp b/src/base/search/searchpluginmanager.cpp index 5904b8d35..a7027a716 100644 --- a/src/base/search/searchpluginmanager.cpp +++ b/src/base/search/searchpluginmanager.cpp @@ -61,16 +61,19 @@ namespace while (iter.hasNext()) dirs += iter.next(); - for (const QString &dir : asConst(dirs)) { + for (const QString &dir : asConst(dirs)) + { // python 3: remove "__pycache__" folders - if (dir.endsWith("/__pycache__")) { + if (dir.endsWith("/__pycache__")) + { Utils::Fs::removeDirRecursive(dir); continue; } // python 2: remove "*.pyc" files const QStringList files = QDir(dir).entryList(QDir::Files); - for (const QString &file : files) { + for (const QString &file : files) + { if (file.endsWith(".pyc")) Utils::Fs::forceRemove(file); } @@ -115,7 +118,8 @@ QStringList SearchPluginManager::allPlugins() const QStringList SearchPluginManager::enabledPlugins() const { QStringList plugins; - for (const PluginInfo *plugin : asConst(m_plugins)) { + for (const PluginInfo *plugin : asConst(m_plugins)) + { if (plugin->enabled) plugins << plugin->name; } @@ -126,9 +130,12 @@ QStringList SearchPluginManager::enabledPlugins() const QStringList SearchPluginManager::supportedCategories() const { QStringList result; - for (const PluginInfo *plugin : asConst(m_plugins)) { - if (plugin->enabled) { - for (const QString &cat : plugin->supportedCategories) { + for (const PluginInfo *plugin : asConst(m_plugins)) + { + if (plugin->enabled) + { + for (const QString &cat : plugin->supportedCategories) + { if (!result.contains(cat)) result << cat; } @@ -149,7 +156,8 @@ QStringList SearchPluginManager::getPluginCategories(const QString &pluginName) plugins << pluginName.trimmed(); QSet categories; - for (const QString &name : asConst(plugins)) { + for (const QString &name : asConst(plugins)) + { const PluginInfo *plugin = pluginInfo(name); if (!plugin) continue; // plugin wasn't found for (const QString &category : plugin->supportedCategories) @@ -167,7 +175,8 @@ PluginInfo *SearchPluginManager::pluginInfo(const QString &name) const void SearchPluginManager::enablePlugin(const QString &name, const bool enabled) { PluginInfo *plugin = m_plugins.value(name, nullptr); - if (plugin) { + if (plugin) + { plugin->enabled = enabled; // Save to Hard disk Preferences *const pref = Preferences::instance(); @@ -193,12 +202,14 @@ void SearchPluginManager::installPlugin(const QString &source) { clearPythonCache(engineLocation()); - if (Net::DownloadManager::hasSupportedScheme(source)) { + if (Net::DownloadManager::hasSupportedScheme(source)) + { using namespace Net; DownloadManager::instance()->download(DownloadRequest(source).saveToFile(true) , this, &SearchPluginManager::pluginDownloadFinished); } - else { + else + { QString path = source; if (path.startsWith("file:", Qt::CaseInsensitive)) path = QUrl(path).toLocalFile(); @@ -217,7 +228,8 @@ void SearchPluginManager::installPlugin_impl(const QString &name, const QString { const PluginVersion newVersion = getPluginVersion(path); const PluginInfo *plugin = pluginInfo(name); - if (plugin && !(plugin->version < newVersion)) { + if (plugin && !(plugin->version < newVersion)) + { LogMsg(tr("Plugin already at version %1, which is greater than %2").arg(plugin->version, newVersion), Log::INFO); emit pluginUpdateFailed(name, tr("A more recent version of this plugin is already installed.")); return; @@ -226,7 +238,8 @@ void SearchPluginManager::installPlugin_impl(const QString &name, const QString // Process with install const QString destPath = pluginPath(name); bool updated = false; - if (QFile::exists(destPath)) { + if (QFile::exists(destPath)) + { // Backup in case install fails QFile::copy(destPath, destPath + ".bak"); Utils::Fs::forceRemove(destPath); @@ -237,11 +250,13 @@ void SearchPluginManager::installPlugin_impl(const QString &name, const QString // Update supported plugins update(); // Check if this was correctly installed - if (!m_plugins.contains(name)) { + if (!m_plugins.contains(name)) + { // Remove broken file Utils::Fs::forceRemove(destPath); LogMsg(tr("Plugin %1 is not supported.").arg(name), Log::INFO); - if (updated) { + if (updated) + { // restore backup QFile::copy(destPath + ".bak", destPath); Utils::Fs::forceRemove(destPath + ".bak"); @@ -249,13 +264,16 @@ void SearchPluginManager::installPlugin_impl(const QString &name, const QString update(); emit pluginUpdateFailed(name, tr("Plugin is not supported.")); } - else { + else + { emit pluginInstallationFailed(name, tr("Plugin is not supported.")); } } - else { + else + { // Install was successful, remove backup - if (updated) { + if (updated) + { LogMsg(tr("Plugin %1 has been successfully updated.").arg(name), Log::INFO); Utils::Fs::forceRemove(destPath + ".bak"); } @@ -284,10 +302,12 @@ void SearchPluginManager::updateIconPath(PluginInfo *const plugin) { if (!plugin) return; QString iconPath = QString::fromLatin1("%1/%2.png").arg(pluginsLocation(), plugin->name); - if (QFile::exists(iconPath)) { + if (QFile::exists(iconPath)) + { plugin->iconPath = iconPath; } - else { + else + { iconPath = QString::fromLatin1("%1/%2.ico").arg(pluginsLocation(), plugin->name); if (QFile::exists(iconPath)) plugin->iconPath = iconPath; @@ -317,7 +337,8 @@ SearchHandler *SearchPluginManager::startSearch(const QString &pattern, const QS QString SearchPluginManager::categoryFullName(const QString &categoryName) { - const QHash categoryTable { + const QHash categoryTable + { {"all", tr("All categories")}, {"movies", tr("Movies")}, {"tv", tr("TV shows")}, @@ -344,7 +365,8 @@ QString SearchPluginManager::pluginsLocation() QString SearchPluginManager::engineLocation() { static QString location; - if (location.isEmpty()) { + if (location.isEmpty()) + { location = Utils::Fs::expandPathAbs(specialFolderLocation(SpecialFolder::Data) + "nova3"); const QDir locationDir(location); @@ -364,7 +386,8 @@ void SearchPluginManager::versionInfoDownloadFinished(const Net::DownloadResult void SearchPluginManager::pluginDownloadFinished(const Net::DownloadResult &result) { - if (result.status == Net::DownloadStatus::Success) { + if (result.status == Net::DownloadStatus::Success) + { const QString filePath = Utils::Fs::toUniformPath(result.filePath); QString pluginName = Utils::Fs::fileName(result.url); @@ -372,7 +395,8 @@ void SearchPluginManager::pluginDownloadFinished(const Net::DownloadResult &resu installPlugin_impl(pluginName, filePath); Utils::Fs::forceRemove(filePath); } - else { + else + { const QString url = result.url; QString pluginName = url.mid(url.lastIndexOf('/') + 1); pluginName.replace(".py", "", Qt::CaseInsensitive); @@ -432,21 +456,25 @@ void SearchPluginManager::update() const QString capabilities = nova.readAll(); QDomDocument xmlDoc; - if (!xmlDoc.setContent(capabilities)) { + if (!xmlDoc.setContent(capabilities)) + { qWarning() << "Could not parse Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data(); qWarning() << "Error: " << nova.readAllStandardError().constData(); return; } const QDomElement root = xmlDoc.documentElement(); - if (root.tagName() != "capabilities") { + if (root.tagName() != "capabilities") + { qWarning() << "Invalid XML file for Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data(); return; } - for (QDomNode engineNode = root.firstChild(); !engineNode.isNull(); engineNode = engineNode.nextSibling()) { + for (QDomNode engineNode = root.firstChild(); !engineNode.isNull(); engineNode = engineNode.nextSibling()) + { const QDomElement engineElem = engineNode.toElement(); - if (!engineElem.isNull()) { + if (!engineElem.isNull()) + { const QString pluginName = engineElem.tagName(); auto plugin = std::make_unique(); @@ -456,7 +484,8 @@ void SearchPluginManager::update() plugin->url = engineElem.elementsByTagName("url").at(0).toElement().text(); const QStringList categories = engineElem.elementsByTagName("categories").at(0).toElement().text().split(' '); - for (QString cat : categories) { + for (QString cat : categories) + { cat = cat.trimmed(); if (!cat.isEmpty()) plugin->supportedCategories << cat; @@ -467,11 +496,13 @@ void SearchPluginManager::update() updateIconPath(plugin.get()); - if (!m_plugins.contains(pluginName)) { + if (!m_plugins.contains(pluginName)) + { m_plugins[pluginName] = plugin.release(); emit pluginInstalled(pluginName); } - else if (m_plugins[pluginName]->version != plugin->version) { + else if (m_plugins[pluginName]->version != plugin->version) + { delete m_plugins.take(pluginName); m_plugins[pluginName] = plugin.release(); emit pluginUpdated(pluginName); @@ -486,7 +517,8 @@ void SearchPluginManager::parseVersionInfo(const QByteArray &info) int numCorrectData = 0; const QVector lines = Utils::ByteArray::splitToViews(info, "\n", QString::SkipEmptyParts); - for (QByteArray line : lines) { + for (QByteArray line : lines) + { line = line.trimmed(); if (line.isEmpty()) continue; if (line.startsWith('#')) continue; @@ -500,17 +532,20 @@ void SearchPluginManager::parseVersionInfo(const QByteArray &info) if (!version.isValid()) continue; ++numCorrectData; - if (isUpdateNeeded(pluginName, version)) { + if (isUpdateNeeded(pluginName, version)) + { LogMsg(tr("Plugin \"%1\" is outdated, updating to version %2").arg(pluginName, version), Log::INFO); updateInfo[pluginName] = version; } } - if (numCorrectData < lines.size()) { + if (numCorrectData < lines.size()) + { emit checkForUpdatesFailed(tr("Incorrect update info received for %1 out of %2 plugins.") .arg(QString::number(lines.size() - numCorrectData), QString::number(lines.size()))); } - else { + else + { emit checkForUpdatesFinished(updateInfo); } } @@ -535,7 +570,8 @@ PluginVersion SearchPluginManager::getPluginVersion(const QString &filePath) if (!pluginFile.open(QIODevice::ReadOnly | QIODevice::Text)) return {}; - while (!pluginFile.atEnd()) { + while (!pluginFile.atEnd()) + { const QString line = QString(pluginFile.readLine()).remove(' '); if (!line.startsWith("#VERSION:", Qt::CaseInsensitive)) continue; diff --git a/src/base/settingsstorage.cpp b/src/base/settingsstorage.cpp index 7b5b7d37e..54d5a70cf 100644 --- a/src/base/settingsstorage.cpp +++ b/src/base/settingsstorage.cpp @@ -67,7 +67,8 @@ namespace QString mapKey(const QString &key) { - static const QHash keyMapping = { + static const QHash keyMapping = + { {"BitTorrent/Session/MaxRatioAction", "Preferences/Bittorrent/MaxRatioAction"}, {"BitTorrent/Session/DefaultSavePath", "Preferences/Downloads/SavePath"}, {"BitTorrent/Session/TempPath", "Preferences/Downloads/TempPath"}, @@ -189,7 +190,8 @@ bool SettingsStorage::save() if (!m_dirty) return true; // something might have changed while we were getting the lock const TransactionalSettings settings(QLatin1String("qBittorrent")); - if (!settings.write(m_data)) { + if (!settings.write(m_data)) + { m_timer.start(); return false; } @@ -211,7 +213,8 @@ void SettingsStorage::storeValue(const QString &key, const QVariant &value) const QWriteLocker locker(&m_lock); QVariant ¤tValue = m_data[realKey]; - if (currentValue != value) { + if (currentValue != value) + { m_dirty = true; currentValue = value; m_timer.start(); @@ -222,7 +225,8 @@ void SettingsStorage::removeValue(const QString &key) { const QString realKey = mapKey(key); const QWriteLocker locker(&m_lock); - if (m_data.remove(realKey) > 0) { + if (m_data.remove(realKey) > 0) + { m_dirty = true; m_timer.start(); } @@ -233,7 +237,8 @@ QVariantHash TransactionalSettings::read() const QVariantHash res; const QString newPath = deserialize(m_name + QLatin1String("_new"), res); - if (!newPath.isEmpty()) { // "_new" file is NOT empty + if (!newPath.isEmpty()) + { // "_new" file is NOT empty // This means that the PC closed either due to power outage // or because the disk was full. In any case the settings weren't transferred // in their final position. So assume that qbittorrent_new.ini/qbittorrent_new.conf @@ -249,7 +254,8 @@ QVariantHash TransactionalSettings::read() const Utils::Fs::forceRemove(finalPath); QFile::rename(newPath, finalPath); } - else { + else + { deserialize(m_name, res); } @@ -264,7 +270,8 @@ bool TransactionalSettings::write(const QVariantHash &data) const // Write everything to qBittorrent_new.ini/qBittorrent_new.conf and if it succeeds // replace qBittorrent.ini/qBittorrent.conf with it. const QString newPath = serialize(m_name + QLatin1String("_new"), data); - if (newPath.isEmpty()) { + if (newPath.isEmpty()) + { Utils::Fs::forceRemove(newPath); return false; } @@ -301,7 +308,8 @@ QString TransactionalSettings::serialize(const QString &name, const QVariantHash settings->sync(); // Important to get error status - switch (settings->status()) { + switch (settings->status()) + { case QSettings::NoError: return settings->fileName(); case QSettings::AccessError: diff --git a/src/base/torrentfilter.cpp b/src/base/torrentfilter.cpp index 43d5a0ea7..f692f6284 100644 --- a/src/base/torrentfilter.cpp +++ b/src/base/torrentfilter.cpp @@ -73,7 +73,8 @@ TorrentFilter::TorrentFilter(const QString &filter, const QStringSet &hashSet, c bool TorrentFilter::setType(Type type) { - if (m_type != type) { + if (m_type != type) + { m_type = type; return true; } @@ -113,7 +114,8 @@ bool TorrentFilter::setTypeByName(const QString &filter) bool TorrentFilter::setHashSet(const QStringSet &hashSet) { - if (m_hashSet != hashSet) { + if (m_hashSet != hashSet) + { m_hashSet = hashSet; return true; } @@ -126,7 +128,8 @@ bool TorrentFilter::setCategory(const QString &category) // QString::operator==() doesn't distinguish between empty and null strings. if ((m_category != category) || (m_category.isNull() && !category.isNull()) - || (!m_category.isNull() && category.isNull())) { + || (!m_category.isNull() && category.isNull())) + { m_category = category; return true; } @@ -139,7 +142,8 @@ bool TorrentFilter::setTag(const QString &tag) // QString::operator==() doesn't distinguish between empty and null strings. if ((m_tag != tag) || (m_tag.isNull() && !tag.isNull()) - || (!m_tag.isNull() && tag.isNull())) { + || (!m_tag.isNull() && tag.isNull())) + { m_tag = tag; return true; } @@ -156,7 +160,8 @@ bool TorrentFilter::match(const TorrentHandle *const torrent) const bool TorrentFilter::matchState(const BitTorrent::TorrentHandle *const torrent) const { - switch (m_type) { + switch (m_type) + { case All: return true; case Downloading: diff --git a/src/base/utils/bytearray.cpp b/src/base/utils/bytearray.cpp index 128aa93a3..3c8817e5a 100644 --- a/src/base/utils/bytearray.cpp +++ b/src/base/utils/bytearray.cpp @@ -40,7 +40,8 @@ QVector 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(); diff --git a/src/base/utils/foreignapps.cpp b/src/base/utils/foreignapps.cpp index 2964b5ad4..2b6987ae0 100644 --- a/src/base/utils/foreignapps.cpp +++ b/src/base/utils/foreignapps.cpp @@ -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; diff --git a/src/base/utils/fs.cpp b/src/base/utils/fs.cpp index 079dd418c..6d9381304 100644 --- a/src/base/utils/fs.cpp +++ b/src/base/utils/fs.cpp @@ -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(buf.f_type)) { + switch (static_cast(buf.f_type)) + { case 0xFF534D42: // CIFS_MAGIC_NUMBER case 0x6969: // NFS_SUPER_MAGIC case 0x517B: // SMB_SUPER_MAGIC diff --git a/src/base/utils/gzip.cpp b/src/base/utils/gzip.cpp index b9f3eba26..4e28a2093 100644 --- a/src/base/utils/gzip.cpp +++ b/src/base/utils/gzip.cpp @@ -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 {}; } diff --git a/src/base/utils/io.cpp b/src/base/utils/io.cpp index 08b0f73c7..51cfaaeb1 100644 --- a/src/base/utils/io.cpp +++ b/src/base/utils/io.cpp @@ -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(); diff --git a/src/base/utils/misc.cpp b/src/base/utils/misc.cpp index 1566f08d8..b5fc3c76f 100644 --- a/src/base/utils/misc.cpp +++ b/src/base/utils/misc.cpp @@ -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(sizeInBytes); - while ((val >= 1024.) && (i <= static_cast(Utils::Misc::SizeUnit::ExbiByte))) { + while ((val >= 1024.) && (i <= static_cast(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(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 multimediaExtensions = { + static const QSet 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); diff --git a/src/base/utils/net.cpp b/src/base/utils/net.cpp index a92e658f5..6d148c7b2 100644 --- a/src/base/utils/net.cpp +++ b/src/base/utils/net.cpp @@ -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)); } diff --git a/src/base/utils/password.cpp b/src/base/utils/password.cpp index 06f425863..4fe12a0bd 100644 --- a/src/base/utils/password.cpp +++ b/src/base/utils/password.cpp @@ -71,7 +71,8 @@ QByteArray Utils::Password::PBKDF2::generate(const QString &password) QByteArray Utils::Password::PBKDF2::generate(const QByteArray &password) { - const std::array salt {{Random::rand(), Random::rand() + const std::array salt + {{Random::rand(), Random::rand() , Random::rand(), Random::rand()}}; std::array outBuf {}; diff --git a/src/base/utils/string.cpp b/src/base/utils/string.cpp index 29f6fa480..1505f0e96 100644 --- a/src/base/utils/string.cpp +++ b/src/base/utils/string.cpp @@ -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 nCmp; if (!nCmp.hasLocalData()) diff --git a/src/base/utils/string.h b/src/base/utils/string.h index de77fc900..aef5d3a9a 100644 --- a/src/base/utils/string.h +++ b/src/base/utils/string.h @@ -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)); } diff --git a/src/base/utils/version.h b/src/base/utils/version.h index b4bb4fee6..22952f7f6 100644 --- a/src/base/utils/version.h +++ b/src/base/utils/version.h @@ -151,10 +151,12 @@ namespace Utils template 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(versionParts.size()); ++i) { + for (std::size_t i = 0; i < static_cast(versionParts.size()); ++i) + { res[i] = static_cast(versionParts[static_cast(i)].toInt(&ok)); if (!ok) throw std::runtime_error("Can not parse version component"); diff --git a/src/gui/aboutdialog.cpp b/src/gui/aboutdialog.cpp index 95146e37f..bbe1433d5 100644 --- a/src/gui/aboutdialog.cpp +++ b/src/gui/aboutdialog.cpp @@ -70,21 +70,24 @@ AboutDialog::AboutDialog(QWidget *parent) // Thanks QFile thanksfile(":/thanks.html"); - if (thanksfile.open(QIODevice::ReadOnly | QIODevice::Text)) { + if (thanksfile.open(QIODevice::ReadOnly | QIODevice::Text)) + { m_ui->textBrowserThanks->setHtml(QString::fromUtf8(thanksfile.readAll().constData())); thanksfile.close(); } // Translation QFile translatorsfile(":/translators.html"); - if (translatorsfile.open(QIODevice::ReadOnly | QIODevice::Text)) { + if (translatorsfile.open(QIODevice::ReadOnly | QIODevice::Text)) + { m_ui->textBrowserTranslation->setHtml(QString::fromUtf8(translatorsfile.readAll().constData())); translatorsfile.close(); } // License QFile licensefile(":/gpl.html"); - if (licensefile.open(QIODevice::ReadOnly | QIODevice::Text)) { + if (licensefile.open(QIODevice::ReadOnly | QIODevice::Text)) + { m_ui->textBrowserLicense->setHtml(QString::fromUtf8(licensefile.readAll().constData())); licensefile.close(); } diff --git a/src/gui/addnewtorrentdialog.cpp b/src/gui/addnewtorrentdialog.cpp index 61f575e93..ae61834eb 100644 --- a/src/gui/addnewtorrentdialog.cpp +++ b/src/gui/addnewtorrentdialog.cpp @@ -230,7 +230,8 @@ void AddNewTorrentDialog::show(const QString &source, const BitTorrent::AddTorre { auto *dlg = new AddNewTorrentDialog(inParams, parent); - if (Net::DownloadManager::hasSupportedScheme(source)) { + if (Net::DownloadManager::hasSupportedScheme(source)) + { // Launch downloader Net::DownloadManager::instance()->download( Net::DownloadRequest(source).limit(MAX_TORRENT_SIZE) @@ -262,7 +263,8 @@ bool AddNewTorrentDialog::loadTorrentFile(const QString &torrentPath) QString error; m_torrentInfo = BitTorrent::TorrentInfo::loadFromFile(decodedPath, &error); - if (!m_torrentInfo.isValid()) { + if (!m_torrentInfo.isValid()) + { RaisedMessageBox::critical(this, tr("Invalid torrent") , tr("Failed to load the torrent: %1.\nError: %2", "Don't remove the '\n' characters. They insert a newline.") .arg(Utils::Fs::toNativePath(decodedPath), error)); @@ -280,19 +282,24 @@ bool AddNewTorrentDialog::loadTorrentImpl() const BitTorrent::InfoHash infoHash = m_torrentInfo.hash(); // Prevent showing the dialog if download is already present - if (BitTorrent::Session::instance()->isKnownTorrent(infoHash)) { + if (BitTorrent::Session::instance()->isKnownTorrent(infoHash)) + { BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(infoHash); - if (torrent) { - if (torrent->isPrivate() || m_torrentInfo.isPrivate()) { + if (torrent) + { + if (torrent->isPrivate() || m_torrentInfo.isPrivate()) + { RaisedMessageBox::warning(this, tr("Torrent is already present"), tr("Torrent '%1' is already in the transfer list. Trackers haven't been merged because it is a private torrent.").arg(torrent->name()), QMessageBox::Ok); } - else { + else + { torrent->addTrackers(m_torrentInfo.trackers()); torrent->addUrlSeeds(m_torrentInfo.urlSeeds()); RaisedMessageBox::information(this, tr("Torrent is already present"), tr("Torrent '%1' is already in the transfer list. Trackers have been merged.").arg(torrent->name()), QMessageBox::Ok); } } - else { + else + { RaisedMessageBox::information(this, tr("Torrent is already present"), tr("Torrent is already queued for processing."), QMessageBox::Ok); } return false; @@ -307,7 +314,8 @@ bool AddNewTorrentDialog::loadTorrentImpl() bool AddNewTorrentDialog::loadMagnet(const BitTorrent::MagnetUri &magnetUri) { - if (!magnetUri.isValid()) { + if (!magnetUri.isValid()) + { RaisedMessageBox::critical(this, tr("Invalid magnet link"), tr("This magnet link was not recognized")); return false; } @@ -316,19 +324,24 @@ bool AddNewTorrentDialog::loadMagnet(const BitTorrent::MagnetUri &magnetUri) const BitTorrent::InfoHash infoHash = magnetUri.hash(); // Prevent showing the dialog if download is already present - if (BitTorrent::Session::instance()->isKnownTorrent(infoHash)) { + if (BitTorrent::Session::instance()->isKnownTorrent(infoHash)) + { BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(infoHash); - if (torrent) { - if (torrent->isPrivate()) { + if (torrent) + { + if (torrent->isPrivate()) + { RaisedMessageBox::warning(this, tr("Torrent is already present"), tr("Torrent '%1' is already in the transfer list. Trackers haven't been merged because it is a private torrent.").arg(torrent->name()), QMessageBox::Ok); } - else { + else + { torrent->addTrackers(magnetUri.trackers()); torrent->addUrlSeeds(magnetUri.urlSeeds()); RaisedMessageBox::information(this, tr("Torrent is already present"), tr("Magnet link '%1' is already in the transfer list. Trackers have been merged.").arg(torrent->name()), QMessageBox::Ok); } } - else { + else + { RaisedMessageBox::information(this, tr("Torrent is already present"), tr("Magnet link is already queued for processing."), QMessageBox::Ok); } return false; @@ -395,15 +408,18 @@ void AddNewTorrentDialog::updateDiskSpaceLabel() // Determine torrent size qlonglong torrentSize = 0; - if (m_hasMetadata) { - if (m_contentModel) { + if (m_hasMetadata) + { + if (m_contentModel) + { const QVector priorities = m_contentModel->model()->getFilePriorities(); Q_ASSERT(priorities.size() == m_torrentInfo.filesCount()); for (int i = 0; i < priorities.size(); ++i) if (priorities[i] > BitTorrent::DownloadPriority::Ignored) torrentSize += m_torrentInfo.fileSize(i); } - else { + else + { torrentSize = m_torrentInfo.totalSize(); } } @@ -426,7 +442,8 @@ void AddNewTorrentDialog::categoryChanged(int index) { Q_UNUSED(index); - if (m_ui->comboTTM->currentIndex() == 1) { + if (m_ui->comboTTM->currentIndex() == 1) + { QString savePath = BitTorrent::Session::instance()->categorySavePath(m_ui->categoryComboBox->currentText()); m_ui->savePath->setSelectedPath(Utils::Fs::toNativePath(savePath)); updateDiskSpaceLabel(); @@ -436,7 +453,8 @@ void AddNewTorrentDialog::categoryChanged(int index) void AddNewTorrentDialog::setSavePath(const QString &newPath) { int existingIndex = indexOfSavePath(newPath); - if (existingIndex < 0) { + if (existingIndex < 0) + { // New path, prepend to combo box m_ui->savePath->insertItem(0, newPath); existingIndex = 0; @@ -461,10 +479,12 @@ void AddNewTorrentDialog::saveTorrentFile() if (!path.endsWith(torrentFileExtension, Qt::CaseInsensitive)) path += torrentFileExtension; - try { + try + { m_torrentInfo.saveToFile(path); } - catch (const RuntimeError &err) { + catch (const RuntimeError &err) + { QMessageBox::critical(this, tr("I/O Error"), err.message()); } } @@ -494,7 +514,8 @@ void AddNewTorrentDialog::displayContentTreeMenu(const QPoint &) const auto applyPriorities = [this, selectedRows](const BitTorrent::DownloadPriority prio) { - for (const QModelIndex &index : selectedRows) { + for (const QModelIndex &index : selectedRows) + { m_contentModel->setData( m_contentModel->index(index.row(), PRIORITY, index.parent()) , static_cast(prio)); @@ -504,7 +525,8 @@ void AddNewTorrentDialog::displayContentTreeMenu(const QPoint &) QMenu *menu = new QMenu(this); menu->setAttribute(Qt::WA_DeleteOnClose); - if (selectedRows.size() == 1) { + if (selectedRows.size() == 1) + { QAction *actRename = menu->addAction(UIThemeManager::instance()->getIcon("edit-rename"), tr("Rename...")); connect(actRename, &QAction::triggered, this, [this]() { m_ui->contentTreeView->renameSelectedFile(m_torrentInfo); }); @@ -563,12 +585,14 @@ void AddNewTorrentDialog::accept() m_torrentParams.firstLastPiecePriority = m_ui->firstLastCheckBox->isChecked(); QString savePath = m_ui->savePath->selectedPath(); - if (m_ui->comboTTM->currentIndex() != 1) { // 0 is Manual mode and 1 is Automatic mode. Handle all non 1 values as manual mode. + if (m_ui->comboTTM->currentIndex() != 1) + { // 0 is Manual mode and 1 is Automatic mode. Handle all non 1 values as manual mode. m_torrentParams.useAutoTMM = TriStateBool::False; m_torrentParams.savePath = savePath; saveSavePathHistory(); } - else { + else + { m_torrentParams.useAutoTMM = TriStateBool::True; } @@ -586,7 +610,8 @@ void AddNewTorrentDialog::accept() void AddNewTorrentDialog::reject() { - if (!m_hasMetadata) { + if (!m_hasMetadata) + { setMetadataProgressIndicator(false); BitTorrent::Session::instance()->cancelLoadMetadata(m_magnetURI.hash()); } @@ -600,7 +625,8 @@ void AddNewTorrentDialog::updateMetadata(const BitTorrent::TorrentInfo &metadata disconnect(BitTorrent::Session::instance(), &BitTorrent::Session::metadataLoaded, this, &AddNewTorrentDialog::updateMetadata); - if (!metadata.isValid()) { + if (!metadata.isValid()) + { RaisedMessageBox::critical(this, tr("I/O Error"), ("Invalid metadata.")); setMetadataProgressIndicator(false, tr("Invalid metadata")); return; @@ -628,11 +654,13 @@ void AddNewTorrentDialog::setMetadataProgressIndicator(bool visibleIndicator, co void AddNewTorrentDialog::setupTreeview() { - if (!m_hasMetadata) { + if (!m_hasMetadata) + { m_ui->labelCommentData->setText(tr("Not Available", "This comment is unavailable")); m_ui->labelDateData->setText(tr("Not Available", "This date is unavailable")); } - else { + else + { // Set dialog title setWindowTitle(m_torrentInfo.name()); @@ -662,7 +690,8 @@ void AddNewTorrentDialog::setupTreeview() // Expand single-item folders recursively QModelIndex currentIndex; - while (m_contentModel->rowCount(currentIndex) == 1) { + while (m_contentModel->rowCount(currentIndex) == 1) + { currentIndex = m_contentModel->index(0, 0, currentIndex); m_ui->contentTreeView->setExpanded(currentIndex, true); } @@ -674,10 +703,12 @@ void AddNewTorrentDialog::setupTreeview() void AddNewTorrentDialog::handleDownloadFinished(const Net::DownloadResult &result) { QString error; - switch (result.status) { + switch (result.status) + { case Net::DownloadStatus::Success: m_torrentInfo = BitTorrent::TorrentInfo::load(result.data, &error); - if (!m_torrentInfo.isValid()) { + if (!m_torrentInfo.isValid()) + { RaisedMessageBox::critical(this, tr("Invalid torrent"), tr("Failed to load from URL: %1.\nError: %2") .arg(result.url, error)); return; @@ -705,13 +736,15 @@ void AddNewTorrentDialog::handleDownloadFinished(const Net::DownloadResult &resu void AddNewTorrentDialog::TMMChanged(int index) { - if (index != 1) { // 0 is Manual mode and 1 is Automatic mode. Handle all non 1 values as manual mode. + if (index != 1) + { // 0 is Manual mode and 1 is Automatic mode. Handle all non 1 values as manual mode. populateSavePathComboBox(); m_ui->groupBoxSavePath->setEnabled(true); m_ui->savePath->blockSignals(false); m_ui->savePath->setCurrentIndex(m_oldIndex < m_ui->savePath->count() ? m_oldIndex : m_ui->savePath->count() - 1); } - else { + else + { m_ui->groupBoxSavePath->setEnabled(false); m_ui->savePath->blockSignals(true); m_ui->savePath->clear(); diff --git a/src/gui/advancedsettings.cpp b/src/gui/advancedsettings.cpp index 10563ac88..d7d7383f4 100644 --- a/src/gui/advancedsettings.cpp +++ b/src/gui/advancedsettings.cpp @@ -168,7 +168,8 @@ void AdvancedSettings::saveAdvancedSettings() #if defined(Q_OS_WIN) BitTorrent::OSMemoryPriority prio = BitTorrent::OSMemoryPriority::Normal; - switch (m_comboBoxOSMemoryPriority.currentIndex()) { + switch (m_comboBoxOSMemoryPriority.currentIndex()) + { case 0: default: prio = BitTorrent::OSMemoryPriority::Normal; @@ -248,12 +249,14 @@ void AdvancedSettings::saveAdvancedSettings() pref->resolvePeerCountries(m_checkBoxResolveCountries.isChecked()); pref->resolvePeerHostNames(m_checkBoxResolveHosts.isChecked()); // Network interface - if (m_comboBoxInterface.currentIndex() == 0) { + if (m_comboBoxInterface.currentIndex() == 0) + { // All interfaces (default) session->setNetworkInterface(QString()); session->setNetworkInterfaceName(QString()); } - else { + else + { session->setNetworkInterface(m_comboBoxInterface.itemData(m_comboBoxInterface.currentIndex()).toString()); session->setNetworkInterfaceName(m_comboBoxInterface.currentText()); } @@ -336,21 +339,25 @@ void AdvancedSettings::updateInterfaceAddressCombo() const auto populateCombo = [this](const QHostAddress &addr) { - if (addr.protocol() == QAbstractSocket::IPv4Protocol) { + if (addr.protocol() == QAbstractSocket::IPv4Protocol) + { const QString str = addr.toString(); m_comboBoxInterfaceAddress.addItem(str, str); } - else if (addr.protocol() == QAbstractSocket::IPv6Protocol) { + else if (addr.protocol() == QAbstractSocket::IPv6Protocol) + { const QString str = Utils::Net::canonicalIPv6Addr(addr).toString(); m_comboBoxInterfaceAddress.addItem(str, str); } }; - if (ifaceName.isEmpty()) { + if (ifaceName.isEmpty()) + { for (const QHostAddress &addr : asConst(QNetworkInterface::allAddresses())) populateCombo(addr); } - else { + else + { const QNetworkInterface iface = QNetworkInterface::interfaceFromName(ifaceName); const QList addresses = iface.addressEntries(); for (const QNetworkAddressEntry &entry : addresses) @@ -386,7 +393,8 @@ void AdvancedSettings::loadAdvancedSettings() #if defined(Q_OS_WIN) m_comboBoxOSMemoryPriority.addItems({tr("Normal"), tr("Below normal"), tr("Medium"), tr("Low"), tr("Very low")}); int OSMemoryPriorityIndex = 0; - switch (session->getOSMemoryPriority()) { + switch (session->getOSMemoryPriority()) + { default: case BitTorrent::OSMemoryPriority::Normal: OSMemoryPriorityIndex = 0; @@ -580,16 +588,19 @@ void AdvancedSettings::loadAdvancedSettings() const QString currentInterface = session->networkInterface(); bool interfaceExists = currentInterface.isEmpty(); int i = 1; - for (const QNetworkInterface &iface : asConst(QNetworkInterface::allInterfaces())) { + for (const QNetworkInterface &iface : asConst(QNetworkInterface::allInterfaces())) + { m_comboBoxInterface.addItem(iface.humanReadableName(), iface.name()); - if (!currentInterface.isEmpty() && (iface.name() == currentInterface)) { + if (!currentInterface.isEmpty() && (iface.name() == currentInterface)) + { m_comboBoxInterface.setCurrentIndex(i); interfaceExists = true; } ++i; } // Saved interface does not exist, show it anyway - if (!interfaceExists) { + if (!interfaceExists) + { m_comboBoxInterface.addItem(session->networkInterfaceName(), currentInterface); m_comboBoxInterface.setCurrentIndex(i); } diff --git a/src/gui/autoexpandabledialog.cpp b/src/gui/autoexpandabledialog.cpp index 5912e6b41..aa5f470d2 100644 --- a/src/gui/autoexpandabledialog.cpp +++ b/src/gui/autoexpandabledialog.cpp @@ -55,7 +55,8 @@ QString AutoExpandableDialog::getText(QWidget *parent, const QString &title, con d.m_ui->textEdit->setInputMethodHints(inputMethodHints); d.m_ui->textEdit->selectAll(); - if (excludeExtension) { + if (excludeExtension) + { int lastDotIndex = text.lastIndexOf('.'); if ((lastDotIndex > 3) && (text.mid(lastDotIndex - 4, 4).toLower() == ".tar")) lastDotIndex -= 4; @@ -86,7 +87,8 @@ void AutoExpandableDialog::showEvent(QShowEvent *e) int wd = m_ui->textEdit->fontMetrics().width(m_ui->textEdit->text()) + 4; #endif - if (!windowTitle().isEmpty()) { + if (!windowTitle().isEmpty()) + { // not really the font metrics in window title, so we enlarge it a bit, // including the small icon and close button width #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)) @@ -97,7 +99,8 @@ void AutoExpandableDialog::showEvent(QShowEvent *e) wd = std::max(wd, w); } - if (!m_ui->textLabel->text().isEmpty()) { + if (!m_ui->textLabel->text().isEmpty()) + { #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)) int w = m_ui->textLabel->fontMetrics().horizontalAdvance(m_ui->textLabel->text()); #else @@ -109,7 +112,8 @@ void AutoExpandableDialog::showEvent(QShowEvent *e) // Now resize the dialog to fit the contents // max width of text from either of: label, title, textedit // If the value is less than dialog default size, default size is used - if (wd > width()) { + if (wd > width()) + { QSize size = {width() - m_ui->verticalLayout->sizeHint().width() + wd, height()}; Utils::Gui::resize(this, size); } diff --git a/src/gui/banlistoptionsdialog.cpp b/src/gui/banlistoptionsdialog.cpp index 040cbc1df..9d047ffaf 100644 --- a/src/gui/banlistoptionsdialog.cpp +++ b/src/gui/banlistoptionsdialog.cpp @@ -64,18 +64,21 @@ BanListOptionsDialog::~BanListOptionsDialog() void BanListOptionsDialog::on_buttonBox_accepted() { - if (m_modified) { + if (m_modified) + { // save to session QStringList IPList; // Operate on the m_sortFilter to grab the strings in sorted order - for (int i = 0; i < m_sortFilter->rowCount(); ++i) { + for (int i = 0; i < m_sortFilter->rowCount(); ++i) + { QModelIndex index = m_sortFilter->index(i, 0); IPList << index.data().toString(); } BitTorrent::Session::instance()->setBannedIPs(IPList); QDialog::accept(); } - else { + else + { QDialog::reject(); } } @@ -83,7 +86,8 @@ void BanListOptionsDialog::on_buttonBox_accepted() void BanListOptionsDialog::on_buttonBanIP_clicked() { QString ip = m_ui->txtIP->text(); - if (!Utils::Net::isValidIP(ip)) { + if (!Utils::Net::isValidIP(ip)) + { QMessageBox::warning(this, tr("Warning"), tr("The entered IP address is invalid.")); return; } @@ -91,9 +95,11 @@ void BanListOptionsDialog::on_buttonBanIP_clicked() // QHostAddress::toString() result format follows RFC5952; // thus we avoid duplicate entries pointing to the same address ip = QHostAddress(ip).toString(); - for (int i = 0; i < m_sortFilter->rowCount(); ++i) { + for (int i = 0; i < m_sortFilter->rowCount(); ++i) + { QModelIndex index = m_sortFilter->index(i, 0); - if (ip == index.data().toString()) { + if (ip == index.data().toString()) + { QMessageBox::warning(this, tr("Warning"), tr("The entered IP is already banned.")); return; } diff --git a/src/gui/categoryfiltermodel.cpp b/src/gui/categoryfiltermodel.cpp index 25ad763c4..edbff6df5 100644 --- a/src/gui/categoryfiltermodel.cpp +++ b/src/gui/categoryfiltermodel.cpp @@ -57,7 +57,8 @@ public: ~CategoryModelItem() { clear(); - if (m_parent) { + if (m_parent) + { m_parent->m_torrentsCount -= m_torrentsCount; const QString uid = m_parent->m_children.key(this); m_parent->m_children.remove(uid); @@ -211,16 +212,19 @@ QVariant CategoryFilterModel::data(const QModelIndex &index, int role) const auto item = static_cast(index.internalPointer()); - if ((index.column() == 0) && (role == Qt::DecorationRole)) { + if ((index.column() == 0) && (role == Qt::DecorationRole)) + { return UIThemeManager::instance()->getIcon("inode-directory"); } - if ((index.column() == 0) && (role == Qt::DisplayRole)) { + if ((index.column() == 0) && (role == Qt::DisplayRole)) + { return QString(QStringLiteral("%1 (%2)")) .arg(item->name()).arg(item->torrentsCount()); } - if ((index.column() == 0) && (role == Qt::UserRole)) { + if ((index.column() == 0) && (role == Qt::UserRole)) + { return item->torrentsCount(); } @@ -306,7 +310,8 @@ void CategoryFilterModel::categoryAdded(const QString &categoryName) { CategoryModelItem *parent = m_rootItem; - if (m_isSubcategoriesEnabled) { + if (m_isSubcategoriesEnabled) + { QStringList expanded = BitTorrent::Session::expandCategory(categoryName); if (expanded.count() > 1) parent = findItem(expanded[expanded.count() - 2]); @@ -322,7 +327,8 @@ void CategoryFilterModel::categoryAdded(const QString &categoryName) void CategoryFilterModel::categoryRemoved(const QString &categoryName) { auto item = findItem(categoryName); - if (item) { + if (item) + { QModelIndex i = index(item); beginRemoveRows(i.parent(), i.row(), i.row()); delete item; @@ -357,7 +363,8 @@ void CategoryFilterModel::torrentCategoryChanged(BitTorrent::TorrentHandle *cons item->decreaseTorrentsCount(); i = index(item); - while (i.isValid()) { + while (i.isValid()) + { emit dataChanged(i, i); i = parent(i); } @@ -367,7 +374,8 @@ void CategoryFilterModel::torrentCategoryChanged(BitTorrent::TorrentHandle *cons item->increaseTorrentsCount(); i = index(item); - while (i.isValid()) { + while (i.isValid()) + { emit dataChanged(i, i); i = parent(i); } @@ -404,13 +412,17 @@ void CategoryFilterModel::populate() , [](Torrent *torrent) { return torrent->category().isEmpty(); }))); using Torrent = BitTorrent::TorrentHandle; - for (auto i = session->categories().cbegin(); i != session->categories().cend(); ++i) { + for (auto i = session->categories().cbegin(); i != session->categories().cend(); ++i) + { const QString &category = i.key(); - if (m_isSubcategoriesEnabled) { + if (m_isSubcategoriesEnabled) + { CategoryModelItem *parent = m_rootItem; - for (const QString &subcat : asConst(session->expandCategory(category))) { + for (const QString &subcat : asConst(session->expandCategory(category))) + { const QString subcatName = shortName(subcat); - if (!parent->hasChild(subcatName)) { + if (!parent->hasChild(subcatName)) + { new CategoryModelItem( parent, subcatName , std::count_if(torrents.cbegin(), torrents.cend() @@ -419,7 +431,8 @@ void CategoryFilterModel::populate() parent = parent->child(subcatName); } } - else { + else + { new CategoryModelItem( m_rootItem, category , std::count_if(torrents.begin(), torrents.end() @@ -437,7 +450,8 @@ CategoryModelItem *CategoryFilterModel::findItem(const QString &fullName) const return m_rootItem->child(fullName); CategoryModelItem *item = m_rootItem; - for (const QString &subcat : asConst(BitTorrent::Session::expandCategory(fullName))) { + for (const QString &subcat : asConst(BitTorrent::Session::expandCategory(fullName))) + { const QString subcatName = shortName(subcat); if (!item->hasChild(subcatName)) return nullptr; item = item->child(subcatName); diff --git a/src/gui/categoryfilterwidget.cpp b/src/gui/categoryfilterwidget.cpp index 84cb197bb..42461657f 100644 --- a/src/gui/categoryfilterwidget.cpp +++ b/src/gui/categoryfilterwidget.cpp @@ -44,7 +44,8 @@ namespace QString getCategoryFilter(const CategoryFilterProxyModel *const model, const QModelIndex &index) { QString categoryFilter; // Defaults to All - if (index.isValid()) { + if (index.isValid()) + { if (!index.parent().isValid() && (index.row() == 1)) categoryFilter = ""; // Uncategorized else if (index.parent().isValid() || (index.row() > 1)) @@ -115,8 +116,10 @@ void CategoryFilterWidget::showMenu(const QPoint &) connect(addAct, &QAction::triggered, this, &CategoryFilterWidget::addCategory); const auto selectedRows = selectionModel()->selectedRows(); - if (!selectedRows.empty() && !CategoryFilterModel::isSpecialItem(selectedRows.first())) { - if (BitTorrent::Session::instance()->isSubcategoriesEnabled()) { + if (!selectedRows.empty() && !CategoryFilterModel::isSpecialItem(selectedRows.first())) + { + if (BitTorrent::Session::instance()->isSubcategoriesEnabled()) + { const QAction *addSubAct = menu->addAction( UIThemeManager::instance()->getIcon("list-add") , tr("Add subcategory...")); @@ -175,7 +178,8 @@ QSize CategoryFilterWidget::sizeHint() const // otherwise widget will not correctly adjust the // size when subcategories are used. const QSize viewportSize {viewportSizeHint()}; - return { + return + { viewportSize.width(), viewportSize.height() + static_cast(0.5 * sizeHintForRow(0)) }; @@ -194,7 +198,8 @@ void CategoryFilterWidget::rowsInserted(const QModelIndex &parent, int start, in // Expand all parents if the parent(s) of the node are not expanded. QModelIndex p = parent; - while (p.isValid()) { + while (p.isValid()) + { if (!isExpanded(p)) expand(p); p = model()->parent(p); @@ -221,7 +226,8 @@ void CategoryFilterWidget::editCategory() void CategoryFilterWidget::removeCategory() { const auto selectedRows = selectionModel()->selectedRows(); - if (!selectedRows.empty() && !CategoryFilterModel::isSpecialItem(selectedRows.first())) { + if (!selectedRows.empty() && !CategoryFilterModel::isSpecialItem(selectedRows.first())) + { BitTorrent::Session::instance()->removeCategory( static_cast(model())->categoryName(selectedRows.first())); updateGeometry(); @@ -231,7 +237,8 @@ void CategoryFilterWidget::removeCategory() void CategoryFilterWidget::removeUnusedCategories() { auto session = BitTorrent::Session::instance(); - for (const QString &category : asConst(session->categories().keys())) { + for (const QString &category : asConst(session->categories().keys())) + { if (model()->data(static_cast(model())->index(category), Qt::UserRole) == 0) session->removeCategory(category); } diff --git a/src/gui/cookiesmodel.cpp b/src/gui/cookiesmodel.cpp index 1a63296ae..348561a0c 100644 --- a/src/gui/cookiesmodel.cpp +++ b/src/gui/cookiesmodel.cpp @@ -43,8 +43,10 @@ QList CookiesModel::cookies() const QVariant CookiesModel::headerData(int section, Qt::Orientation orientation, int role) const { - if ((role == Qt::DisplayRole) && (orientation == Qt::Horizontal)) { - switch (section) { + if ((role == Qt::DisplayRole) && (orientation == Qt::Horizontal)) + { + switch (section) + { case COL_DOMAIN: return tr("Domain"); case COL_PATH: @@ -96,7 +98,8 @@ QVariant CookiesModel::data(const QModelIndex &index, int role) const || ((role != Qt::DisplayRole) && (role != Qt::EditRole))) return {}; - switch (index.column()) { + switch (index.column()) + { case COL_DOMAIN: return m_cookies[index.row()].domain(); case COL_PATH: @@ -116,7 +119,8 @@ bool CookiesModel::setData(const QModelIndex &index, const QVariant &value, int { if (role != Qt::EditRole) return false; - switch (index.column()) { + switch (index.column()) + { case COL_DOMAIN: m_cookies[index.row()].setDomain(value.toString()); break; diff --git a/src/gui/downloadfromurldialog.cpp b/src/gui/downloadfromurldialog.cpp index 02e380926..8b35ec141 100644 --- a/src/gui/downloadfromurldialog.cpp +++ b/src/gui/downloadfromurldialog.cpp @@ -71,7 +71,8 @@ DownloadFromURLDialog::DownloadFromURLDialog(QWidget *parent) const QVector clipboardList = clipboardText.splitRef('\n'); QSet uniqueURLs; - for (QStringRef strRef : clipboardList) { + for (QStringRef strRef : clipboardList) + { strRef = strRef.trimmed(); if (strRef.isEmpty()) continue; @@ -96,14 +97,16 @@ void DownloadFromURLDialog::downloadButtonClicked() const QVector urls = plainText.splitRef('\n'); QSet uniqueURLs; - for (QStringRef url : urls) { + for (QStringRef url : urls) + { url = url.trimmed(); if (url.isEmpty()) continue; uniqueURLs << url.toString(); } - if (uniqueURLs.isEmpty()) { + if (uniqueURLs.isEmpty()) + { QMessageBox::warning(this, tr("No URL entered"), tr("Please type at least one URL.")); return; } diff --git a/src/gui/executionlogwidget.cpp b/src/gui/executionlogwidget.cpp index 2aa3e9cd5..6c94a0c9d 100644 --- a/src/gui/executionlogwidget.cpp +++ b/src/gui/executionlogwidget.cpp @@ -89,7 +89,8 @@ void ExecutionLogWidget::displayContextMenu(const QPoint &pos, const LogListView menu->setAttribute(Qt::WA_DeleteOnClose); // only show copy action if any of the row is selected - if (view->currentIndex().isValid()) { + if (view->currentIndex().isValid()) + { const QAction *copyAct = menu->addAction(UIThemeManager::instance()->getIcon("edit-copy"), tr("Copy")); connect(copyAct, &QAction::triggered, view, &LogListView::copySelection); } diff --git a/src/gui/fspathedit.cpp b/src/gui/fspathedit.cpp index 1683a1a5b..f4e0ac07e 100644 --- a/src/gui/fspathedit.cpp +++ b/src/gui/fspathedit.cpp @@ -115,7 +115,8 @@ void FileSystemPathEdit::FileSystemPathEditPrivate::browseActionTriggered() QString directory = q->currentDirectory().isEmpty() ? QDir::homePath() : q->currentDirectory(); QString selectedPath; - switch (m_mode) { + switch (m_mode) + { case FileSystemPathEdit::Mode::FileOpen: selectedPath = QFileDialog::getOpenFileName(q, dialogCaptionOrDefault(), directory, filter); break; @@ -139,7 +140,8 @@ QString FileSystemPathEdit::FileSystemPathEditPrivate::dialogCaptionOrDefault() if (!m_dialogCaption.isEmpty()) return m_dialogCaption; - switch (m_mode) { + switch (m_mode) + { case FileSystemPathEdit::Mode::FileOpen: case FileSystemPathEdit::Mode::FileSave: return defaultDialogCaptionForFile.tr(); @@ -155,7 +157,8 @@ void FileSystemPathEdit::FileSystemPathEditPrivate::modeChanged() { QStyle::StandardPixmap pixmap = QStyle::SP_DialogOpenButton; bool showDirsOnly = false; - switch (m_mode) { + switch (m_mode) + { case FileSystemPathEdit::Mode::FileOpen: case FileSystemPathEdit::Mode::FileSave: #ifdef Q_OS_WIN @@ -229,17 +232,21 @@ void FileSystemPathEdit::setFileNameFilter(const QString &val) // extract file masks const int openBracePos = val.indexOf(QLatin1Char('('), 0); const int closeBracePos = val.indexOf(QLatin1Char(')'), openBracePos + 1); - if ((openBracePos > 0) && (closeBracePos > 0) && (closeBracePos > openBracePos + 2)) { + if ((openBracePos > 0) && (closeBracePos > 0) && (closeBracePos > openBracePos + 2)) + { QString filterString = val.mid(openBracePos + 1, closeBracePos - openBracePos - 1); - if (filterString == QLatin1String("*")) { // no filters + if (filterString == QLatin1String("*")) + { // no filters d->m_editor->setFilenameFilters({}); } - else { + else + { QStringList filters = filterString.split(QLatin1Char(' '), QString::SkipEmptyParts); d->m_editor->setFilenameFilters(filters); } } - else { + else + { d->m_editor->setFilenameFilters({}); } #endif @@ -261,7 +268,8 @@ void FileSystemPathEdit::onPathEdited() { Q_D(FileSystemPathEdit); QString newPath = selectedPath(); - if (newPath != d->m_lastSignaledPath) { + if (newPath != d->m_lastSignaledPath) + { emit selectedPathChanged(newPath); d->m_lastSignaledPath = newPath; d->m_editor->widget()->setToolTip(editWidgetText()); diff --git a/src/gui/fspathedit_p.cpp b/src/gui/fspathedit_p.cpp index be2467473..6612fed60 100644 --- a/src/gui/fspathedit_p.cpp +++ b/src/gui/fspathedit_p.cpp @@ -115,7 +115,8 @@ QValidator::State Private::FileSystemPathValidator::validate(QString &input, int // components.size() - 1 because when path ends with QDir::separator(), we will not see the last // character in the components array, yet everything past the one before the last delimiter // belongs to the last component - for (; (componentWithCursorIndex < components.size() - 1) && (pathLength < pos); ++componentWithCursorIndex) { + for (; (componentWithCursorIndex < components.size() - 1) && (pathLength < pos); ++componentWithCursorIndex) + { pathLength = components[componentWithCursorIndex].position() + components[componentWithCursorIndex].size(); } @@ -140,12 +141,14 @@ QValidator::State Private::FileSystemPathValidator::validate(const QString &path if (pathComponents.empty()) return strict ? QValidator::Invalid : QValidator::Intermediate; - for (int i = firstComponentToTest; i < lastComponentToTest; ++i) { + for (int i = firstComponentToTest; i < lastComponentToTest; ++i) + { if (pathComponents[i].isEmpty()) continue; QStringRef componentPath(&path, 0, pathComponents[i].position() + pathComponents[i].size()); m_lastTestResult = testPath(componentPath, false); - if (m_lastTestResult != TestResult::OK) { + if (m_lastTestResult != TestResult::OK) + { m_lastTestedPath = componentPath.toString(); return strict ? QValidator::Invalid : QValidator::Intermediate; } @@ -155,7 +158,8 @@ QValidator::State Private::FileSystemPathValidator::validate(const QString &path QStringRef componentPath(&path, 0, pathComponents[lastComponentToTest].position() + pathComponents[lastComponentToTest].size()); m_lastTestResult = testPath(componentPath, finalPath); - if (m_lastTestResult != TestResult::OK) { + if (m_lastTestResult != TestResult::OK) + { m_lastTestedPath = componentPath.toString(); return strict ? QValidator::Invalid : QValidator::Intermediate; } @@ -172,7 +176,8 @@ Private::FileSystemPathValidator::testPath(const QStringRef &path, bool pathIsCo if ((!pathIsComplete || m_directoriesOnly) && !fi.isDir()) return TestResult::NotADir; - if (pathIsComplete) { + if (pathIsComplete) + { if (!m_directoriesOnly && fi.isDir()) return TestResult::NotAFile; @@ -249,27 +254,33 @@ QWidget *Private::FileLineEdit::widget() void Private::FileLineEdit::keyPressEvent(QKeyEvent *e) { QLineEdit::keyPressEvent(e); - if ((e->key() == Qt::Key_Space) && (e->modifiers() == Qt::CTRL)) { + if ((e->key() == Qt::Key_Space) && (e->modifiers() == Qt::CTRL)) + { m_completerModel->setRootPath(QFileInfo(text()).absoluteDir().absolutePath()); showCompletionPopup(); } auto *validator = qobject_cast(this->validator()); - if (validator) { + if (validator) + { FileSystemPathValidator::TestResult lastTestResult = validator->lastTestResult(); QValidator::State lastState = validator->lastValidationState(); - if (lastTestResult == FileSystemPathValidator::TestResult::OK) { + if (lastTestResult == FileSystemPathValidator::TestResult::OK) + { delete m_warningAction; m_warningAction = nullptr; } - else { - if (!m_warningAction) { + else + { + if (!m_warningAction) + { m_warningAction = new QAction(this); addAction(m_warningAction, QLineEdit::TrailingPosition); } } - if (m_warningAction) { + if (m_warningAction) + { if (lastState == QValidator::Invalid) m_warningAction->setIcon(style()->standardIcon(QStyle::SP_MessageBoxCritical)); else if (lastState == QValidator::Intermediate) @@ -284,7 +295,8 @@ void Private::FileLineEdit::contextMenuEvent(QContextMenuEvent *event) QMenu *menu = createStandardContextMenu(); menu->setAttribute(Qt::WA_DeleteOnClose); - if (m_browseAction) { + if (m_browseAction) + { menu->addSeparator(); menu->addAction(m_browseAction); } @@ -301,7 +313,8 @@ void Private::FileLineEdit::showCompletionPopup() QString Private::FileLineEdit::warningText(FileSystemPathValidator::TestResult r) { using TestResult = FileSystemPathValidator::TestResult; - switch (r) { + switch (r) + { case TestResult::DoesNotExist: return tr("'%1' does not exist"); case TestResult::NotADir: diff --git a/src/gui/ipsubnetwhitelistoptionsdialog.cpp b/src/gui/ipsubnetwhitelistoptionsdialog.cpp index 51a7f81a2..3474290a1 100644 --- a/src/gui/ipsubnetwhitelistoptionsdialog.cpp +++ b/src/gui/ipsubnetwhitelistoptionsdialog.cpp @@ -68,7 +68,8 @@ IPSubnetWhitelistOptionsDialog::~IPSubnetWhitelistOptionsDialog() void IPSubnetWhitelistOptionsDialog::on_buttonBox_accepted() { - if (m_modified) { + if (m_modified) + { // save to session QStringList subnets; // Operate on the m_sortFilter to grab the strings in sorted order @@ -77,7 +78,8 @@ void IPSubnetWhitelistOptionsDialog::on_buttonBox_accepted() Preferences::instance()->setWebUiAuthSubnetWhitelist(subnets); QDialog::accept(); } - else { + else + { QDialog::reject(); } } @@ -86,7 +88,8 @@ void IPSubnetWhitelistOptionsDialog::on_buttonWhitelistIPSubnet_clicked() { bool ok = false; const Utils::Net::Subnet subnet = Utils::Net::parseSubnet(m_ui->txtIPSubnet->text(), &ok); - if (!ok) { + if (!ok) + { QMessageBox::critical(this, tr("Error"), tr("The entered subnet is invalid.")); return; } diff --git a/src/gui/lineedit.cpp b/src/gui/lineedit.cpp index 13450ce26..f1cbb9f9c 100644 --- a/src/gui/lineedit.cpp +++ b/src/gui/lineedit.cpp @@ -47,7 +47,8 @@ void LineEdit::resizeEvent(QResizeEvent *e) void LineEdit::keyPressEvent(QKeyEvent *event) { - if ((event->modifiers() == Qt::NoModifier) && (event->key() == Qt::Key_Escape)) { + if ((event->modifiers() == Qt::NoModifier) && (event->key() == Qt::Key_Escape)) + { clear(); } QLineEdit::keyPressEvent(event); diff --git a/src/gui/log/logmodel.cpp b/src/gui/log/logmodel.cpp index ebccb5308..d15b66504 100644 --- a/src/gui/log/logmodel.cpp +++ b/src/gui/log/logmodel.cpp @@ -97,7 +97,8 @@ QVariant BaseLogModel::data(const QModelIndex &index, const int role) const return {}; const Message &message = m_messages[messageIndex]; - switch (role) { + switch (role) + { case TimeRole: return message.time(); case MessageRole: @@ -117,7 +118,8 @@ void BaseLogModel::addNewMessage(const BaseLogModel::Message &message) { // if row is inserted on filled up buffer, the size will not change // but because of calling of beginInsertRows function we'll have ghost rows. - if (m_messages.size() == MAX_VISIBLE_MESSAGES) { + if (m_messages.size() == MAX_VISIBLE_MESSAGES) + { const int lastMessage = m_messages.size() - 1; beginRemoveRows(QModelIndex(), lastMessage, lastMessage); m_messages.pop_back(); @@ -138,7 +140,8 @@ void BaseLogModel::reset() LogMessageModel::LogMessageModel(QObject *parent) : BaseLogModel(parent) - , m_foregroundForMessageTypes { + , m_foregroundForMessageTypes + { {Log::NORMAL, UIThemeManager::instance()->getColor(QLatin1String("Log.Normal"), QApplication::palette().color(QPalette::WindowText))}, {Log::INFO, UIThemeManager::instance()->getColor(QLatin1String("Log.Info"), Qt::blue)}, {Log::WARNING, UIThemeManager::instance()->getColor(QLatin1String("Log.Warning"), QColor {255, 165, 0})}, // orange diff --git a/src/gui/mainwindow.cpp b/src/gui/mainwindow.cpp index 026ffd333..8cf58d307 100644 --- a/src/gui/mainwindow.cpp +++ b/src/gui/mainwindow.cpp @@ -281,8 +281,10 @@ MainWindow::MainWindow(QWidget *parent) m_queueSeparatorMenu = m_ui->menuEdit->insertSeparator(m_ui->actionTopQueuePos); #ifdef Q_OS_MACOS - for (QAction *action : asConst(m_ui->toolBar->actions())) { - if (action->isSeparator()) { + for (QAction *action : asConst(m_ui->toolBar->actions())) + { + if (action->isSeparator()) + { QWidget *spacer = new QWidget(this); spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); spacer->setMinimumWidth(16); @@ -406,30 +408,38 @@ MainWindow::MainWindow(QWidget *parent) readSettings(); #ifndef Q_OS_MACOS - if (m_systrayIcon) { - if (!(pref->startMinimized() || m_uiLocked)) { + if (m_systrayIcon) + { + if (!(pref->startMinimized() || m_uiLocked)) + { show(); activateWindow(); raise(); } - else if (pref->startMinimized()) { + else if (pref->startMinimized()) + { showMinimized(); - if (pref->minimizeToTray()) { + if (pref->minimizeToTray()) + { hide(); - if (!pref->minimizeToTrayNotified()) { + if (!pref->minimizeToTrayNotified()) + { showNotificationBaloon(tr("qBittorrent is minimized to tray"), tr("This behavior can be changed in the settings. You won't be reminded again.")); pref->setMinimizeToTrayNotified(true); } } } } - else { + else + { #endif // Make sure the Window is visible if we don't have a tray icon - if (pref->startMinimized()) { + if (pref->startMinimized()) + { showMinimized(); } - else { + else + { show(); activateWindow(); raise(); @@ -456,14 +466,17 @@ MainWindow::MainWindow(QWidget *parent) qDebug("GUI Built"); #ifdef Q_OS_WIN - if (!pref->neverCheckFileAssoc() && (!Preferences::isTorrentFileAssocSet() || !Preferences::isMagnetLinkAssocSet())) { + if (!pref->neverCheckFileAssoc() && (!Preferences::isTorrentFileAssocSet() || !Preferences::isMagnetLinkAssocSet())) + { if (QMessageBox::question(this, tr("Torrent file association"), tr("qBittorrent is not the default application to open torrent files or Magnet links.\nDo you want to associate qBittorrent to torrent files and Magnet links?"), - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) + { Preferences::setTorrentFileAssoc(true); Preferences::setMagnetLinkAssoc(true); } - else { + else + { pref->setNeverCheckFileAssoc(); } } @@ -567,7 +580,8 @@ void MainWindow::addToolbarContextMenu() const auto buttonStyle = static_cast(pref->getToolbarTextPosition()); if ((buttonStyle >= Qt::ToolButtonIconOnly) && (buttonStyle <= Qt::ToolButtonFollowStyle)) m_ui->toolBar->setToolButtonStyle(buttonStyle); - switch (buttonStyle) { + switch (buttonStyle) + { case Qt::ToolButtonIconOnly: iconsOnly->setChecked(true); break; @@ -635,7 +649,8 @@ bool MainWindow::defineUILockPassword() if (!ok) return false; - if (newPassword.size() < 3) { + if (newPassword.size() < 3) + { QMessageBox::warning(this, tr("Invalid password"), tr("The password should contain at least 3 characters")); return false; } @@ -657,7 +672,8 @@ void MainWindow::on_actionLock_triggered() Preferences *const pref = Preferences::instance(); // Check if there is a password - if (pref->getUILockPassword().isEmpty()) { + if (pref->getUILockPassword().isEmpty()) + { if (!defineUILockPassword()) return; } @@ -676,9 +692,11 @@ void MainWindow::handleRSSUnreadCountUpdated(int count) void MainWindow::displayRSSTab(bool enable) { - if (enable) { + if (enable) + { // RSS tab - if (!m_rssWidget) { + if (!m_rssWidget) + { m_rssWidget = new RSSWidget(m_tabs); connect(m_rssWidget.data(), &RSSWidget::unreadCountUpdated, this, &MainWindow::handleRSSUnreadCountUpdated); #ifdef Q_OS_MACOS @@ -689,7 +707,8 @@ void MainWindow::displayRSSTab(bool enable) #endif } } - else { + else + { delete m_rssWidget; } } @@ -714,9 +733,11 @@ void MainWindow::showFilterContextMenu(const QPoint &) void MainWindow::displaySearchTab(bool enable) { Preferences::instance()->setSearchEnabled(enable); - if (enable) { + if (enable) + { // RSS tab - if (!m_searchWidget) { + if (!m_searchWidget) + { m_searchWidget = new SearchWidget(this); m_tabs->insertTab(1, m_searchWidget, #ifndef Q_OS_MACOS @@ -725,7 +746,8 @@ void MainWindow::displaySearchTab(bool enable) tr("Search")); } } - else { + else + { delete m_searchWidget; } } @@ -751,7 +773,8 @@ void MainWindow::tabChanged(int newTab) Q_UNUSED(newTab); // We cannot rely on the index newTab // because the tab order is undetermined now - if (m_tabs->currentWidget() == m_splitter) { + if (m_tabs->currentWidget() == m_splitter) + { qDebug("Changed tab to transfer list, refreshing the list"); m_propertiesWidget->loadDynamicData(); m_searchFilterAction->setVisible(true); @@ -759,7 +782,8 @@ void MainWindow::tabChanged(int newTab) } m_searchFilterAction->setVisible(false); - if (m_tabs->currentWidget() == m_searchWidget) { + if (m_tabs->currentWidget() == m_searchWidget) + { qDebug("Changed tab to search engine, giving focus to search input"); m_searchWidget->giveFocusToSearchInput(); } @@ -815,8 +839,10 @@ void MainWindow::readSettings() void MainWindow::balloonClicked() { - if (isHidden()) { - if (m_uiLocked) { + if (isHidden()) + { + if (m_uiLocked) + { // Ask for UI lock password if (!unlockUI()) return; @@ -916,7 +942,8 @@ void MainWindow::displayTransferTab() const void MainWindow::displaySearchTab() { - if (!m_searchWidget) { + if (!m_searchWidget) + { m_ui->actionSearchWidget->setChecked(true); displaySearchTab(true); } @@ -926,7 +953,8 @@ void MainWindow::displaySearchTab() void MainWindow::displayRSSTab() { - if (!m_rssWidget) { + if (!m_rssWidget) + { m_ui->actionRSSReader->setChecked(true); displayRSSTab(true); } @@ -936,7 +964,8 @@ void MainWindow::displayRSSTab() void MainWindow::displayExecutionLogTab() { - if (!m_executionLog) { + if (!m_executionLog) + { m_ui->actionExecutionLogs->setChecked(true); on_actionExecutionLogs_triggered(true); } @@ -988,7 +1017,8 @@ void MainWindow::on_actionSetGlobalUploadLimit_triggered() const long newLimit = SpeedLimitDialog::askSpeedLimit( this, &ok, tr("Global Upload Speed Limit"), session->uploadSpeedLimit()); - if (ok) { + if (ok) + { qDebug("Setting global upload rate limit to %.1fKb/s", newLimit / 1024.); session->setUploadSpeedLimit(newLimit); } @@ -1003,7 +1033,8 @@ void MainWindow::on_actionSetGlobalDownloadLimit_triggered() const long newLimit = SpeedLimitDialog::askSpeedLimit( this, &ok, tr("Global Download Speed Limit"), session->downloadSpeedLimit()); - if (ok) { + if (ok) + { qDebug("Setting global download rate limit to %.1fKb/s", newLimit / 1024.); session->setDownloadSpeedLimit(newLimit); } @@ -1059,7 +1090,8 @@ bool MainWindow::unlockUI() Preferences *const pref = Preferences::instance(); const QByteArray secret = pref->getUILockPassword(); - if (!Utils::Password::PBKDF2::verify(secret, password)) { + if (!Utils::Password::PBKDF2::verify(secret, password)) + { QMessageBox::warning(this, tr("Invalid password"), tr("The password is invalid")); return false; } @@ -1085,9 +1117,11 @@ void MainWindow::notifyOfUpdate(const QString &) // Toggle Main window visibility void MainWindow::toggleVisibility(const QSystemTrayIcon::ActivationReason reason) { - switch (reason) { + switch (reason) + { case QSystemTrayIcon::Trigger: - if (isHidden()) { + if (isHidden()) + { if (m_uiLocked && !unlockUI()) // Ask for UI lock password return; @@ -1099,7 +1133,8 @@ void MainWindow::toggleVisibility(const QSystemTrayIcon::ActivationReason reason raise(); activateWindow(); } - else { + else + { hide(); } break; @@ -1138,7 +1173,8 @@ void MainWindow::showEvent(QShowEvent *e) e->accept(); // Make sure the window is initially centered - if (!m_posInitialized) { + if (!m_posInitialized) + { move(Utils::Gui::screenCenter(this)); m_posInitialized = true; } @@ -1146,14 +1182,17 @@ void MainWindow::showEvent(QShowEvent *e) void MainWindow::keyPressEvent(QKeyEvent *event) { - if (event->matches(QKeySequence::Paste)) { + if (event->matches(QKeySequence::Paste)) + { const QMimeData *mimeData {QGuiApplication::clipboard()->mimeData()}; - if (mimeData->hasText()) { + if (mimeData->hasText()) + { const bool useTorrentAdditionDialog {AddNewTorrentDialog::isEnabled()}; const QStringList lines {mimeData->text().split('\n', QString::SkipEmptyParts)}; - for (QString line : lines) { + for (QString line : lines) + { line = line.trimmed(); if (!isTorrentLink(line)) @@ -1177,17 +1216,20 @@ void MainWindow::closeEvent(QCloseEvent *e) { Preferences *const pref = Preferences::instance(); #ifdef Q_OS_MACOS - if (!m_forceExit) { + if (!m_forceExit) + { hide(); e->accept(); return; } #else const bool goToSystrayOnExit = pref->closeToTray(); - if (!m_forceExit && m_systrayIcon && goToSystrayOnExit && !this->isHidden()) { + if (!m_forceExit && m_systrayIcon && goToSystrayOnExit && !this->isHidden()) + { e->ignore(); QTimer::singleShot(0, this, &QWidget::hide); - if (!pref->closeToTrayNotified()) { + if (!pref->closeToTrayNotified()) + { showNotificationBaloon(tr("qBittorrent is closed to tray"), tr("This behavior can be changed in the settings. You won't be reminded again.")); pref->setCloseToTrayNotified(true); } @@ -1195,8 +1237,10 @@ void MainWindow::closeEvent(QCloseEvent *e) } #endif // Q_OS_MACOS - if (pref->confirmOnExit() && BitTorrent::Session::instance()->hasActiveTorrents()) { - if (e->spontaneous() || m_forceExit) { + if (pref->confirmOnExit() && BitTorrent::Session::instance()->hasActiveTorrents()) + { + if (e->spontaneous() || m_forceExit) + { if (!isVisible()) show(); QMessageBox confirmBox(QMessageBox::Question, tr("Exiting qBittorrent"), @@ -1208,7 +1252,8 @@ void MainWindow::closeEvent(QCloseEvent *e) QPushButton *alwaysBtn = confirmBox.addButton(tr("&Always Yes"), QMessageBox::YesRole); confirmBox.setDefaultButton(noBtn); confirmBox.exec(); - if (!confirmBox.clickedButton() || (confirmBox.clickedButton() == noBtn)) { + if (!confirmBox.clickedButton() || (confirmBox.clickedButton() == noBtn)) + { // Cancel exit e->ignore(); m_forceExit = false; @@ -1242,7 +1287,8 @@ void MainWindow::on_actionCreateTorrent_triggered() void MainWindow::createTorrentTriggered(const QString &path) { - if (m_createTorrentDlg) { + if (m_createTorrentDlg) + { m_createTorrentDlg->updateInputPath(path); m_createTorrentDlg->activateWindow(); } @@ -1253,29 +1299,37 @@ void MainWindow::createTorrentTriggered(const QString &path) bool MainWindow::event(QEvent *e) { #ifndef Q_OS_MACOS - switch (e->type()) { - case QEvent::WindowStateChange: { + switch (e->type()) + { + case QEvent::WindowStateChange: + { qDebug("Window change event"); // Now check to see if the window is minimised - if (isMinimized()) { + if (isMinimized()) + { qDebug("minimisation"); Preferences *const pref = Preferences::instance(); - if (m_systrayIcon && pref->minimizeToTray()) { + if (m_systrayIcon && pref->minimizeToTray()) + { qDebug() << "Has active window:" << (qApp->activeWindow() != nullptr); // Check if there is a modal window bool hasModalWindow = false; - for (QWidget *widget : asConst(QApplication::allWidgets())) { - if (widget->isModal()) { + for (QWidget *widget : asConst(QApplication::allWidgets())) + { + if (widget->isModal()) + { hasModalWindow = true; break; } } // Iconify if there is no modal window - if (!hasModalWindow) { + if (!hasModalWindow) + { qDebug("Minimize to Tray enabled, hiding!"); e->ignore(); QTimer::singleShot(0, this, &QWidget::hide); - if (!pref->minimizeToTrayNotified()) { + if (!pref->minimizeToTrayNotified()) + { showNotificationBaloon(tr("qBittorrent is minimized to tray"), tr("This behavior can be changed in the settings. You won't be reminded again.")); pref->setMinimizeToTrayNotified(true); } @@ -1285,7 +1339,8 @@ bool MainWindow::event(QEvent *e) } break; } - case QEvent::ToolBarChange: { + case QEvent::ToolBarChange: + { qDebug("MAC: Received a toolbar change event!"); bool ret = QMainWindow::event(e); @@ -1309,8 +1364,10 @@ void MainWindow::dropEvent(QDropEvent *event) // remove scheme QStringList files; - if (event->mimeData()->hasUrls()) { - for (const QUrl &url : asConst(event->mimeData()->urls())) { + if (event->mimeData()->hasUrls()) + { + for (const QUrl &url : asConst(event->mimeData()->urls())) + { if (url.isEmpty()) continue; @@ -1319,13 +1376,15 @@ void MainWindow::dropEvent(QDropEvent *event) : url.toString()); } } - else { + else + { files = event->mimeData()->text().split('\n'); } // differentiate ".torrent" files/links & magnet links from others QStringList torrentFiles, otherFiles; - for (const QString &file : asConst(files)) { + for (const QString &file : asConst(files)) + { if (isTorrentLink(file)) torrentFiles << file; else @@ -1334,7 +1393,8 @@ void MainWindow::dropEvent(QDropEvent *event) // Download torrents const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled(); - for (const QString &file : asConst(torrentFiles)) { + for (const QString &file : asConst(torrentFiles)) + { if (useTorrentAdditionDialog) AddNewTorrentDialog::show(file, this); else @@ -1343,7 +1403,8 @@ void MainWindow::dropEvent(QDropEvent *event) if (!torrentFiles.isEmpty()) return; // Create torrent - for (const QString &file : asConst(otherFiles)) { + for (const QString &file : asConst(otherFiles)) + { createTorrentTriggered(file); // currently only handle the first entry @@ -1370,7 +1431,8 @@ static bool dockClickHandler(id self, SEL cmd, ...) Q_UNUSED(self) Q_UNUSED(cmd) - if (dockMainWindowHandle && !dockMainWindowHandle->isVisible()) { + if (dockMainWindowHandle && !dockMainWindowHandle->isVisible()) + { dockMainWindowHandle->activate(); } @@ -1407,7 +1469,8 @@ void MainWindow::on_actionOpen_triggered() const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled(); - for (const QString &file : pathsList) { + for (const QString &file : pathsList) + { if (useTorrentAdditionDialog) AddNewTorrentDialog::show(file, this); else @@ -1422,7 +1485,8 @@ void MainWindow::on_actionOpen_triggered() void MainWindow::activate() { - if (!m_uiLocked || unlockUI()) { + if (!m_uiLocked || unlockUI()) + { show(); activateWindow(); raise(); @@ -1436,11 +1500,13 @@ void MainWindow::optionsSaved() void MainWindow::showStatusBar(bool show) { - if (!show) { + if (!show) + { // Remove status bar setStatusBar(nullptr); } - else if (!m_statusBar) { + else if (!m_statusBar) + { // Create status bar m_statusBar = new StatusBar; connect(m_statusBar.data(), &StatusBar::connectionButtonClicked, this, &MainWindow::showConnectionSettings); @@ -1458,26 +1524,33 @@ void MainWindow::loadPreferences(const bool configureSession) #else const bool newSystrayIntegration = pref->systrayIntegration(); m_ui->actionLock->setVisible(newSystrayIntegration); - if (newSystrayIntegration != (m_systrayIcon != nullptr)) { - if (newSystrayIntegration) { + if (newSystrayIntegration != (m_systrayIcon != nullptr)) + { + if (newSystrayIntegration) + { // create the trayicon - if (!QSystemTrayIcon::isSystemTrayAvailable()) { - if (!configureSession) { // Program startup + if (!QSystemTrayIcon::isSystemTrayAvailable()) + { + if (!configureSession) + { // Program startup m_systrayCreator = new QTimer(this); connect(m_systrayCreator.data(), &QTimer::timeout, this, &MainWindow::createSystrayDelayed); m_systrayCreator->setSingleShot(true); m_systrayCreator->start(2000); qDebug("Info: System tray is unavailable, trying again later."); } - else { + else + { qDebug("Warning: System tray is unavailable."); } } - else { + else + { createTrayIcon(); } } - else { + else + { // Destroy trayicon delete m_systrayIcon; delete m_trayIconMenu; @@ -1488,10 +1561,12 @@ void MainWindow::loadPreferences(const bool configureSession) m_systrayIcon->setIcon(getSystrayIcon()); #endif // General - if (pref->isToolbarDisplayed()) { + if (pref->isToolbarDisplayed()) + { m_ui->toolBar->setVisible(true); } - else { + else + { // Clear search filter before hiding the top toolbar m_searchFilter->clear(); m_ui->toolBar->setVisible(false); @@ -1499,13 +1574,16 @@ void MainWindow::loadPreferences(const bool configureSession) showStatusBar(pref->isStatusbarDisplayed()); - if (pref->preventFromSuspendWhenDownloading() || pref->preventFromSuspendWhenSeeding()) { - if (!m_preventTimer->isActive()) { + if (pref->preventFromSuspendWhenDownloading() || pref->preventFromSuspendWhenSeeding()) + { + if (!m_preventTimer->isActive()) + { updatePowerManagementState(); m_preventTimer->start(PREVENT_SUSPEND_INTERVAL); } } - else { + else + { m_preventTimer->stop(); m_pwr->setActivityState(false); } @@ -1516,8 +1594,10 @@ void MainWindow::loadPreferences(const bool configureSession) m_propertiesWidget->getPeerList()->setAlternatingRowColors(pref->useAlternatingRowColors()); // Queueing System - if (BitTorrent::Session::instance()->isQueueingSystemEnabled()) { - if (!m_ui->actionDecreaseQueuePos->isVisible()) { + if (BitTorrent::Session::instance()->isQueueingSystemEnabled()) + { + if (!m_ui->actionDecreaseQueuePos->isVisible()) + { m_transferListWidget->hideQueuePosColumn(false); m_ui->actionDecreaseQueuePos->setVisible(true); m_ui->actionIncreaseQueuePos->setVisible(true); @@ -1529,8 +1609,10 @@ void MainWindow::loadPreferences(const bool configureSession) m_queueSeparatorMenu->setVisible(true); } } - else { - if (m_ui->actionDecreaseQueuePos->isVisible()) { + else + { + if (m_ui->actionDecreaseQueuePos->isVisible()) + { m_transferListWidget->hideQueuePosColumn(true); m_ui->actionDecreaseQueuePos->setVisible(false); m_ui->actionIncreaseQueuePos->setVisible(false); @@ -1547,11 +1629,13 @@ void MainWindow::loadPreferences(const bool configureSession) m_propertiesWidget->reloadPreferences(); #if defined(Q_OS_WIN) || defined(Q_OS_MACOS) - if (pref->isUpdateCheckEnabled() && !m_wasUpdateCheckEnabled) { + if (pref->isUpdateCheckEnabled() && !m_wasUpdateCheckEnabled) + { m_wasUpdateCheckEnabled = true; checkProgramUpdate(); } - else if (!pref->isUpdateCheckEnabled() && m_wasUpdateCheckEnabled) { + else if (!pref->isUpdateCheckEnabled() && m_wasUpdateCheckEnabled) + { m_wasUpdateCheckEnabled = false; m_programUpdateTimer->stop(); } @@ -1566,15 +1650,18 @@ void MainWindow::reloadSessionStats() // update global information #ifdef Q_OS_MACOS - if (status.payloadDownloadRate > 0) { + if (status.payloadDownloadRate > 0) + { QtMac::setBadgeLabelText(tr("%1/s", "s is a shorthand for seconds") .arg(Utils::Misc::friendlyUnit(status.payloadDownloadRate))); } - else if (!QtMac::badgeLabelText().isEmpty()) { + else if (!QtMac::badgeLabelText().isEmpty()) + { QtMac::setBadgeLabelText(""); } #else - if (m_systrayIcon) { + if (m_systrayIcon) + { const QString toolTip = QString::fromLatin1("%1\n%2").arg( tr("DL speed: %1", "e.g: Download speed: 10 KiB/s").arg(Utils::Misc::friendlyUnit(status.payloadDownloadRate, true)) , tr("UP speed: %1", "e.g: Upload speed: 10 KiB/s").arg(Utils::Misc::friendlyUnit(status.payloadUploadRate, true))); @@ -1582,7 +1669,8 @@ void MainWindow::reloadSessionStats() } #endif // Q_OS_MACOS - if (m_displaySpeedInTitle) { + if (m_displaySpeedInTitle) + { setWindowTitle(tr("[D: %1, U: %2] qBittorrent %3", "D = Download; U = Upload; %3 is qBittorrent version") .arg(Utils::Misc::friendlyUnit(status.payloadDownloadRate, true) , Utils::Misc::friendlyUnit(status.payloadUploadRate, true) @@ -1592,7 +1680,8 @@ void MainWindow::reloadSessionStats() void MainWindow::reloadTorrentStats(const QVector &torrents) { - if (currentTabWidget() == m_transferListWidget) { + if (currentTabWidget() == m_transferListWidget) + { if (torrents.contains(m_propertiesWidget->getCurrentTorrent())) m_propertiesWidget->loadDynamicData(); } @@ -1638,7 +1727,8 @@ void MainWindow::showNotificationBaloon(const QString &title, const QString &msg void MainWindow::downloadFromURLList(const QStringList &urlList) { const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled(); - for (const QString &url : urlList) { + for (const QString &url : urlList) + { if (useTorrentAdditionDialog) AddNewTorrentDialog::show(url, this); else @@ -1656,19 +1746,23 @@ void MainWindow::downloadFromURLList(const QStringList &urlList) void MainWindow::createSystrayDelayed() { static int timeout = 20; - if (QSystemTrayIcon::isSystemTrayAvailable()) { + if (QSystemTrayIcon::isSystemTrayAvailable()) + { // Ok, systray integration is now supported // Create systray icon createTrayIcon(); delete m_systrayCreator; } - else { - if (timeout) { + else + { + if (timeout) + { // Retry a bit later m_systrayCreator->start(2000); --timeout; } - else { + else + { // Timed out, apparently system really does not // support systray icon delete m_systrayCreator; @@ -1780,11 +1874,13 @@ void MainWindow::on_actionRSSReader_triggered() void MainWindow::on_actionSearchWidget_triggered() { - if (!m_hasPython && m_ui->actionSearchWidget->isChecked()) { + if (!m_hasPython && m_ui->actionSearchWidget->isChecked()) + { const Utils::ForeignApps::PythonInfo pyInfo = Utils::ForeignApps::pythonInfo(); // Not installed - if (!pyInfo.isValid()) { + if (!pyInfo.isValid()) + { m_ui->actionSearchWidget->setChecked(false); Preferences::instance()->setSearchEnabled(false); @@ -1802,7 +1898,8 @@ void MainWindow::on_actionSearchWidget_triggered() } // Check version requirement - if (!pyInfo.isSupportedVersion()) { + if (!pyInfo.isSupportedVersion()) + { m_ui->actionSearchWidget->setChecked(false); Preferences::instance()->setSearchEnabled(false); @@ -1839,7 +1936,8 @@ void MainWindow::on_actionSearchWidget_triggered() // an url void MainWindow::on_actionDownloadFromURL_triggered() { - if (!m_downloadFromURLDialog) { + if (!m_downloadFromURLDialog) + { m_downloadFromURLDialog = new DownloadFromURLDialog(this); connect(m_downloadFromURLDialog.data(), &DownloadFromURLDialog::urlsReadyToBeDownloaded, this, &MainWindow::downloadFromURLList); } @@ -1849,19 +1947,22 @@ void MainWindow::on_actionDownloadFromURL_triggered() void MainWindow::handleUpdateCheckFinished(bool updateAvailable, QString newVersion, bool invokedByUser) { QMessageBox::StandardButton answer = QMessageBox::Yes; - if (updateAvailable) { + if (updateAvailable) + { answer = QMessageBox::question(this, tr("qBittorrent Update Available") , tr("A new version is available.") + "
" + tr("Do you want to download %1?").arg(newVersion) + "

" + QString::fromLatin1("%1").arg(tr("Open changelog...")) , QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); - if (answer == QMessageBox::Yes) { + if (answer == QMessageBox::Yes) + { // The user want to update, let's download the update ProgramUpdater *updater = dynamic_cast(sender()); updater->updateProgram(); } } - else if (invokedByUser) { + else if (invokedByUser) + { QMessageBox::information(this, tr("Already Using the Latest qBittorrent Version"), tr("No updates available.\nYou are already using the latest version.")); } @@ -1899,7 +2000,8 @@ void MainWindow::minimizeWindow() void MainWindow::on_actionExecutionLogs_triggered(bool checked) { - if (checked) { + if (checked) + { Q_ASSERT(!m_executionLog); m_executionLog = new ExecutionLogWidget(static_cast(executionLogMsgTypes()), m_tabs); #ifdef Q_OS_MACOS @@ -1909,7 +2011,8 @@ void MainWindow::on_actionExecutionLogs_triggered(bool checked) m_tabs->setTabIcon(indexTab, UIThemeManager::instance()->getIcon("view-calendar-journal")); #endif } - else { + else + { delete m_executionLog; } @@ -1997,7 +2100,8 @@ QIcon MainWindow::getSystrayIcon() const const TrayIcon::Style style = Preferences::instance()->trayIconStyle(); // on Linux we use theme icons, and icons from resources everywhere else #if (defined(Q_OS_UNIX) && !defined(Q_OS_MACOS)) - switch (style) { + switch (style) + { case TrayIcon::NORMAL: return QIcon::fromTheme(QLatin1String("qbittorrent-tray")); case TrayIcon::MONO_DARK: @@ -2008,7 +2112,8 @@ QIcon MainWindow::getSystrayIcon() const break; } #else - switch (style) { + switch (style) + { case TrayIcon::NORMAL: return UIThemeManager::instance()->getIcon(QLatin1String("qbittorrent-tray")); case TrayIcon::MONO_DARK: @@ -2057,7 +2162,8 @@ void MainWindow::installPython() void MainWindow::pythonDownloadFinished(const Net::DownloadResult &result) { - if (result.status != Net::DownloadStatus::Success) { + if (result.status != Net::DownloadStatus::Success) + { setCursor(QCursor(Qt::ArrowCursor)); QMessageBox::warning( this, tr("Download error") @@ -2084,7 +2190,8 @@ void MainWindow::pythonDownloadFinished(const Net::DownloadResult &result) Utils::Fs::forceRemove(result.filePath + ".exe"); // Reload search engine - if (Utils::ForeignApps::pythonInfo().isSupportedVersion()) { + if (Utils::ForeignApps::pythonInfo().isSupportedVersion()) + { m_ui->actionSearchWidget->setChecked(true); displaySearchTab(true); } diff --git a/src/gui/optionsdialog.cpp b/src/gui/optionsdialog.cpp index 22962b5b4..b92872433 100644 --- a/src/gui/optionsdialog.cpp +++ b/src/gui/optionsdialog.cpp @@ -84,7 +84,8 @@ namespace QString languageToLocalizedString(const QLocale &locale) { - switch (locale.language()) { + switch (locale.language()) + { case QLocale::Arabic: return QString::fromUtf8(C_LOCALE_ARABIC); case QLocale::Armenian: return QString::fromUtf8(C_LOCALE_ARMENIAN); case QLocale::Basque: return QString::fromUtf8(C_LOCALE_BASQUE); @@ -92,7 +93,8 @@ namespace case QLocale::Byelorussian: return QString::fromUtf8(C_LOCALE_BYELORUSSIAN); case QLocale::Catalan: return QString::fromUtf8(C_LOCALE_CATALAN); case QLocale::Chinese: - switch (locale.country()) { + switch (locale.country()) + { case QLocale::China: return QString::fromUtf8(C_LOCALE_CHINESE_SIMPLIFIED); case QLocale::HongKong: return QString::fromUtf8(C_LOCALE_CHINESE_TRADITIONAL_HK); default: return QString::fromUtf8(C_LOCALE_CHINESE_TRADITIONAL_TW); @@ -102,7 +104,8 @@ namespace case QLocale::Danish: return QString::fromUtf8(C_LOCALE_DANISH); case QLocale::Dutch: return QString::fromUtf8(C_LOCALE_DUTCH); case QLocale::English: - switch (locale.country()) { + switch (locale.country()) + { case QLocale::Australia: return QString::fromUtf8(C_LOCALE_ENGLISH_AUSTRALIA); case QLocale::UnitedKingdom: return QString::fromUtf8(C_LOCALE_ENGLISH_UNITEDKINGDOM); default: return QString::fromUtf8(C_LOCALE_ENGLISH); @@ -195,7 +198,8 @@ OptionsDialog::OptionsDialog(QWidget *parent) int maxHeight = -1; for (int i = 0; i < m_ui->tabSelection->count(); ++i) maxHeight = std::max(maxHeight, m_ui->tabSelection->visualItemRect(m_ui->tabSelection->item(i)).size().height()); - for (int i = 0; i < m_ui->tabSelection->count(); ++i) { + for (int i = 0; i < m_ui->tabSelection->count(); ++i) + { const QSize size(std::numeric_limits::max(), static_cast(maxHeight * 1.2)); m_ui->tabSelection->item(i)->setSizeHint(size); } @@ -225,8 +229,10 @@ OptionsDialog::OptionsDialog(QWidget *parent) m_ui->hsplitter->setCollapsible(1, false); // Get apply button in button box const QList buttons = m_ui->buttonBox->buttons(); - for (QAbstractButton *button : buttons) { - if (m_ui->buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole) { + for (QAbstractButton *button : buttons) + { + if (m_ui->buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole) + { m_applyButton = button; break; } @@ -263,7 +269,8 @@ OptionsDialog::OptionsDialog(QWidget *parent) m_ui->checkShowSystray->setVisible(false); #else // Disable systray integration if it is not supported by the system - if (!QSystemTrayIcon::isSystemTrayAvailable()) { + if (!QSystemTrayIcon::isSystemTrayAvailable()) + { m_ui->checkShowSystray->setChecked(false); m_ui->checkShowSystray->setEnabled(false); m_ui->labelTrayIconStyle->setVisible(false); @@ -567,19 +574,23 @@ void OptionsDialog::initializeLanguageCombo() // List language files const QDir langDir(":/lang"); const QStringList langFiles = langDir.entryList(QStringList("qbittorrent_*.qm"), QDir::Files); - for (const QString &langFile : langFiles) { + for (const QString &langFile : langFiles) + { QString localeStr = langFile.mid(12); // remove "qbittorrent_" localeStr.chop(3); // Remove ".qm" QString languageName; - if (localeStr.startsWith("eo", Qt::CaseInsensitive)) { + if (localeStr.startsWith("eo", Qt::CaseInsensitive)) + { // QLocale doesn't work with that locale. Esperanto isn't a "real" language. languageName = QString::fromUtf8(C_LOCALE_ESPERANTO); } - else if (localeStr.startsWith("ltg", Qt::CaseInsensitive)) { + else if (localeStr.startsWith("ltg", Qt::CaseInsensitive)) + { // QLocale doesn't work with that locale. languageName = QString::fromUtf8(C_LOCALE_LATGALIAN); } - else { + else + { QLocale locale(localeStr); languageName = languageToLocalizedString(locale); } @@ -634,7 +645,8 @@ void OptionsDialog::saveWindowState() const pref->setPrefSize(size()); // Splitter size - const QStringList sizesStr = { + const QStringList sizesStr = + { QString::number(m_ui->hsplitter->sizes().first()), QString::number(m_ui->hsplitter->sizes().last()) }; @@ -647,7 +659,8 @@ void OptionsDialog::saveOptions() Preferences *const pref = Preferences::instance(); // Load the translation QString locale = getLocale(); - if (pref->getLocale() != locale) { + if (pref->getLocale() != locale) + { auto *translator = new QTranslator; if (translator->load(QLatin1String(":/lang/qbittorrent_") + locale)) qDebug("%s locale recognized, using translation.", qUtf8Printable(locale)); @@ -689,12 +702,14 @@ void OptionsDialog::saveOptions() Preferences::setMagnetLinkAssoc(m_ui->checkAssociateMagnetLinks->isChecked()); #endif #ifdef Q_OS_MACOS - if (m_ui->checkAssociateTorrents->isChecked()) { + if (m_ui->checkAssociateTorrents->isChecked()) + { Preferences::setTorrentFileAssoc(); m_ui->checkAssociateTorrents->setChecked(Preferences::isTorrentFileAssocSet()); m_ui->checkAssociateTorrents->setEnabled(!m_ui->checkAssociateTorrents->isChecked()); } - if (m_ui->checkAssociateMagnetLinks->isChecked()) { + if (m_ui->checkAssociateMagnetLinks->isChecked()) + { Preferences::setMagnetLinkAssoc(); m_ui->checkAssociateMagnetLinks->setChecked(Preferences::isMagnetLinkAssocSet()); m_ui->checkAssociateMagnetLinks->setEnabled(!m_ui->checkAssociateMagnetLinks->isChecked()); @@ -810,7 +825,8 @@ void OptionsDialog::saveOptions() session->setGlobalMaxRatio(getMaxRatio()); session->setGlobalMaxSeedingMinutes(getMaxSeedingMinutes()); - const QVector actIndex = { + const QVector actIndex = + { Pause, Remove, DeleteFiles, @@ -837,7 +853,8 @@ void OptionsDialog::saveOptions() // End Queueing system preferences // Web UI pref->setWebUiEnabled(isWebUiEnabled()); - if (isWebUiEnabled()) { + if (isWebUiEnabled()) + { pref->setServerDomains(m_ui->textServerDomains->text()); pref->setWebUiAddress(m_ui->textWebUiAddress->text()); pref->setWebUiPort(m_ui->spinWebUiPort->value()); @@ -888,7 +905,8 @@ bool OptionsDialog::isIPFilteringEnabled() const Net::ProxyType OptionsDialog::getProxyType() const { - switch (m_ui->comboProxyType->currentIndex()) { + switch (m_ui->comboProxyType->currentIndex()) + { case 1: return Net::ProxyType::SOCKS4; case 2: @@ -927,7 +945,8 @@ void OptionsDialog::loadOptions() #ifndef Q_OS_MACOS m_ui->checkShowSystray->setChecked(pref->systrayIntegration()); - if (m_ui->checkShowSystray->isChecked()) { + if (m_ui->checkShowSystray->isChecked()) + { m_ui->checkMinimizeToSysTray->setChecked(pref->minimizeToTray()); m_ui->checkCloseToSystray->setChecked(pref->closeToTray()); m_ui->comboTrayIcon->setCurrentIndex(pref->trayIconStyle()); @@ -1001,12 +1020,14 @@ void OptionsDialog::loadOptions() m_ui->checkRecursiveDownload->setChecked(!pref->recursiveDownloadDisabled()); strValue = session->torrentExportDirectory(); - if (strValue.isEmpty()) { + if (strValue.isEmpty()) + { // Disable m_ui->checkExportDir->setChecked(false); m_ui->textExportDir->setEnabled(false); } - else { + else + { // Enable m_ui->checkExportDir->setChecked(true); m_ui->textExportDir->setEnabled(true); @@ -1014,12 +1035,14 @@ void OptionsDialog::loadOptions() } strValue = session->finishedTorrentExportDirectory(); - if (strValue.isEmpty()) { + if (strValue.isEmpty()) + { // Disable m_ui->checkExportDirFin->setChecked(false); m_ui->textExportDirFin->setEnabled(false); } - else { + else + { // Enable m_ui->checkExportDirFin->setChecked(true); m_ui->textExportDirFin->setEnabled(true); @@ -1060,49 +1083,57 @@ void OptionsDialog::loadOptions() m_ui->spinPort->setDisabled(m_ui->checkRandomPort->isChecked()); intValue = session->maxConnections(); - if (intValue > 0) { + if (intValue > 0) + { // enable m_ui->checkMaxConnecs->setChecked(true); m_ui->spinMaxConnec->setEnabled(true); m_ui->spinMaxConnec->setValue(intValue); } - else { + else + { // disable m_ui->checkMaxConnecs->setChecked(false); m_ui->spinMaxConnec->setEnabled(false); } intValue = session->maxConnectionsPerTorrent(); - if (intValue > 0) { + if (intValue > 0) + { // enable m_ui->checkMaxConnecsPerTorrent->setChecked(true); m_ui->spinMaxConnecPerTorrent->setEnabled(true); m_ui->spinMaxConnecPerTorrent->setValue(intValue); } - else { + else + { // disable m_ui->checkMaxConnecsPerTorrent->setChecked(false); m_ui->spinMaxConnecPerTorrent->setEnabled(false); } intValue = session->maxUploads(); - if (intValue > 0) { + if (intValue > 0) + { // enable m_ui->checkMaxUploads->setChecked(true); m_ui->spinMaxUploads->setEnabled(true); m_ui->spinMaxUploads->setValue(intValue); } - else { + else + { // disable m_ui->checkMaxUploads->setChecked(false); m_ui->spinMaxUploads->setEnabled(false); } intValue = session->maxUploadsPerTorrent(); - if (intValue > 0) { + if (intValue > 0) + { // enable m_ui->checkMaxUploadsPerTorrent->setChecked(true); m_ui->spinMaxUploadsPerTorrent->setEnabled(true); m_ui->spinMaxUploadsPerTorrent->setValue(intValue); } - else { + else + { // disable m_ui->checkMaxUploadsPerTorrent->setChecked(false); m_ui->spinMaxUploadsPerTorrent->setEnabled(false); @@ -1112,7 +1143,8 @@ void OptionsDialog::loadOptions() Net::ProxyConfiguration proxyConf = proxyConfigManager->proxyConfiguration(); using Net::ProxyType; bool useProxyAuth = false; - switch (proxyConf.type) { + switch (proxyConf.type) + { case ProxyType::SOCKS4: m_ui->comboProxyType->setCurrentIndex(1); break; @@ -1185,32 +1217,37 @@ void OptionsDialog::loadOptions() m_ui->spinUploadRateForSlowTorrents->setValue(session->uploadRateForSlowTorrents()); m_ui->spinSlowTorrentsInactivityTimer->setValue(session->slowTorrentsInactivityTimer()); - if (session->globalMaxRatio() >= 0.) { + if (session->globalMaxRatio() >= 0.) + { // Enable m_ui->checkMaxRatio->setChecked(true); m_ui->spinMaxRatio->setEnabled(true); m_ui->comboRatioLimitAct->setEnabled(true); m_ui->spinMaxRatio->setValue(session->globalMaxRatio()); } - else { + else + { // Disable m_ui->checkMaxRatio->setChecked(false); m_ui->spinMaxRatio->setEnabled(false); } - if (session->globalMaxSeedingMinutes() >= 0) { + if (session->globalMaxSeedingMinutes() >= 0) + { // Enable m_ui->checkMaxSeedingMinutes->setChecked(true); m_ui->spinMaxSeedingMinutes->setEnabled(true); m_ui->spinMaxSeedingMinutes->setValue(session->globalMaxSeedingMinutes()); } - else { + else + { // Disable m_ui->checkMaxSeedingMinutes->setChecked(false); m_ui->spinMaxSeedingMinutes->setEnabled(false); } m_ui->comboRatioLimitAct->setEnabled((session->globalMaxSeedingMinutes() >= 0) || (session->globalMaxRatio() >= 0.)); - const QHash actIndex = { + const QHash actIndex = + { {Pause, 0}, {Remove, 1}, {DeleteFiles, 2}, @@ -1386,16 +1423,20 @@ int OptionsDialog::getMaxUploadsPerTorrent() const void OptionsDialog::on_buttonBox_accepted() { - if (m_applyButton->isEnabled()) { - if (!schedTimesOk()) { + if (m_applyButton->isEnabled()) + { + if (!schedTimesOk()) + { m_ui->tabSelection->setCurrentRow(TAB_SPEED); return; } - if (!webUIAuthenticationOk()) { + if (!webUIAuthenticationOk()) + { m_ui->tabSelection->setCurrentRow(TAB_WEBUI); return; } - if (!isAlternativeWebUIPathValid()) { + if (!isAlternativeWebUIPathValid()) + { m_ui->tabSelection->setCurrentRow(TAB_WEBUI); return; } @@ -1409,16 +1450,20 @@ void OptionsDialog::on_buttonBox_accepted() void OptionsDialog::applySettings(QAbstractButton *button) { - if (button == m_applyButton) { - if (!schedTimesOk()) { + if (button == m_applyButton) + { + if (!schedTimesOk()) + { m_ui->tabSelection->setCurrentRow(TAB_SPEED); return; } - if (!webUIAuthenticationOk()) { + if (!webUIAuthenticationOk()) + { m_ui->tabSelection->setCurrentRow(TAB_WEBUI); return; } - if (!isAlternativeWebUIPathValid()) { + if (!isAlternativeWebUIPathValid()) + { m_ui->tabSelection->setCurrentRow(TAB_WEBUI); return; } @@ -1456,24 +1501,28 @@ void OptionsDialog::toggleComboRatioLimitAct() void OptionsDialog::enableProxy(const int index) { - if (index >= 1) { // Any proxy type is used + if (index >= 1) + { // Any proxy type is used //enable m_ui->lblProxyIP->setEnabled(true); m_ui->textProxyIP->setEnabled(true); m_ui->lblProxyPort->setEnabled(true); m_ui->spinProxyPort->setEnabled(true); m_ui->checkProxyPeerConnecs->setEnabled(true); - if (index >= 2) { // SOCKS5 or HTTP + if (index >= 2) + { // SOCKS5 or HTTP m_ui->checkProxyAuth->setEnabled(true); m_ui->isProxyOnlyForTorrents->setEnabled(true); } - else { + else + { m_ui->checkProxyAuth->setEnabled(false); m_ui->isProxyOnlyForTorrents->setEnabled(false); m_ui->isProxyOnlyForTorrents->setChecked(true); } } - else { // No proxy + else + { // No proxy // disable m_ui->lblProxyIP->setEnabled(false); m_ui->textProxyIP->setEnabled(false); @@ -1550,13 +1599,16 @@ QString OptionsDialog::getLocale() const void OptionsDialog::setLocale(const QString &localeStr) { QString name; - if (localeStr.startsWith("eo", Qt::CaseInsensitive)) { + if (localeStr.startsWith("eo", Qt::CaseInsensitive)) + { name = "eo"; } - else if (localeStr.startsWith("ltg", Qt::CaseInsensitive)) { + else if (localeStr.startsWith("ltg", Qt::CaseInsensitive)) + { name = "ltg"; } - else { + else + { QLocale locale(localeStr); if (locale.language() == QLocale::Uzbek) name = "uz@Latn"; @@ -1565,15 +1617,18 @@ void OptionsDialog::setLocale(const QString &localeStr) } // Attempt to find exact match int index = m_ui->comboI18n->findData(name, Qt::UserRole); - if (index < 0) { + if (index < 0) + { //Attempt to find a language match without a country int pos = name.indexOf('_'); - if (pos > -1) { + if (pos > -1) + { QString lang = name.left(pos); index = m_ui->comboI18n->findData(lang, Qt::UserRole); } } - if (index < 0) { + if (index < 0) + { // Unrecognized, use US English index = m_ui->comboI18n->findData("en", Qt::UserRole); Q_ASSERT(index >= 0); @@ -1616,10 +1671,12 @@ void OptionsDialog::on_addScanFolderButton_clicked() Preferences *const pref = Preferences::instance(); const QString dir = QFileDialog::getExistingDirectory(this, tr("Select folder to monitor"), Utils::Fs::toNativePath(Utils::Fs::folderName(pref->getScanDirsLastPath()))); - if (!dir.isEmpty()) { + if (!dir.isEmpty()) + { const ScanFoldersModel::PathStatus status = ScanFoldersModel::instance()->addPath(dir, ScanFoldersModel::DEFAULT_LOCATION, QString(), false); QString error; - switch (status) { + switch (status) + { case ScanFoldersModel::AlreadyInList: error = tr("Folder is already being monitored:"); break; @@ -1649,7 +1706,8 @@ void OptionsDialog::on_removeScanFolderButton_clicked() if (selected.isEmpty()) return; Q_ASSERT(selected.count() == ScanFoldersModel::instance()->columnCount()); - for (const QModelIndex &index : selected) { + for (const QModelIndex &index : selected) + { if (index.column() == ScanFoldersModel::WATCH) m_removedScanDirs << index.data().toString(); } @@ -1704,13 +1762,15 @@ void OptionsDialog::webUIHttpsCertChanged(const QString &path, const ShowError s return; QFile file(path); - if (!file.open(QIODevice::ReadOnly)) { + if (!file.open(QIODevice::ReadOnly)) + { if (showError == ShowError::Show) QMessageBox::warning(this, tr("Invalid path"), file.errorString()); return; } - if (!Utils::Net::isSSLCertificatesValid(file.read(Utils::Net::MAX_SSL_FILE_SIZE))) { + if (!Utils::Net::isSSLCertificatesValid(file.read(Utils::Net::MAX_SSL_FILE_SIZE))) + { if (showError == ShowError::Show) QMessageBox::warning(this, tr("Invalid certificate"), tr("This is not a valid SSL certificate.")); return; @@ -1728,13 +1788,15 @@ void OptionsDialog::webUIHttpsKeyChanged(const QString &path, const ShowError sh return; QFile file(path); - if (!file.open(QIODevice::ReadOnly)) { + if (!file.open(QIODevice::ReadOnly)) + { if (showError == ShowError::Show) QMessageBox::warning(this, tr("Invalid path"), file.errorString()); return; } - if (!Utils::Net::isSSLKeyValid(file.read(Utils::Net::MAX_SSL_FILE_SIZE))) { + if (!Utils::Net::isSSLKeyValid(file.read(Utils::Net::MAX_SSL_FILE_SIZE))) + { if (showError == ShowError::Show) QMessageBox::warning(this, tr("Invalid key"), tr("This is not a valid SSL key.")); return; @@ -1779,7 +1841,8 @@ void OptionsDialog::handleIPFilterParsed(bool error, int ruleCount) bool OptionsDialog::schedTimesOk() { - if (m_ui->timeEditScheduleFrom->time() == m_ui->timeEditScheduleTo->time()) { + if (m_ui->timeEditScheduleFrom->time() == m_ui->timeEditScheduleTo->time()) + { QMessageBox::warning(this, tr("Time Error"), tr("The start time and the end time can't be the same.")); return false; } @@ -1788,11 +1851,13 @@ bool OptionsDialog::schedTimesOk() bool OptionsDialog::webUIAuthenticationOk() { - if (webUiUsername().length() < 3) { + if (webUiUsername().length() < 3) + { QMessageBox::warning(this, tr("Length Error"), tr("The Web UI username must be at least 3 characters long.")); return false; } - if (!webUiPassword().isEmpty() && (webUiPassword().length() < 6)) { + if (!webUiPassword().isEmpty() && (webUiPassword().length() < 6)) + { QMessageBox::warning(this, tr("Length Error"), tr("The Web UI password must be at least 6 characters long.")); return false; } @@ -1801,7 +1866,8 @@ bool OptionsDialog::webUIAuthenticationOk() bool OptionsDialog::isAlternativeWebUIPathValid() { - if (m_ui->groupAltWebUI->isChecked() && m_ui->textWebUIRootFolder->selectedPath().trimmed().isEmpty()) { + if (m_ui->groupAltWebUI->isChecked() && m_ui->textWebUIRootFolder->selectedPath().trimmed().isEmpty()) + { QMessageBox::warning(this, tr("Location Error"), tr("The alternative Web UI files location cannot be blank.")); return false; } diff --git a/src/gui/previewlistdelegate.cpp b/src/gui/previewlistdelegate.cpp index afa0d14a9..3137432e8 100644 --- a/src/gui/previewlistdelegate.cpp +++ b/src/gui/previewlistdelegate.cpp @@ -54,12 +54,14 @@ void PreviewListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &o QStyleOptionViewItem opt = QItemDelegate::setOptions(index, option); drawBackground(painter, opt, index); - switch (index.column()) { + switch (index.column()) + { case PreviewSelectDialog::SIZE: QItemDelegate::drawDisplay(painter, opt, option.rect, Utils::Misc::friendlyUnit(index.data().toLongLong())); break; - case PreviewSelectDialog::PROGRESS: { + case PreviewSelectDialog::PROGRESS: + { const qreal progress = (index.data().toReal() * 100); QStyleOptionProgressBar newopt; diff --git a/src/gui/previewselectdialog.cpp b/src/gui/previewselectdialog.cpp index 1b458d334..7f467971c 100644 --- a/src/gui/previewselectdialog.cpp +++ b/src/gui/previewselectdialog.cpp @@ -86,12 +86,14 @@ PreviewSelectDialog::PreviewSelectDialog(QWidget *parent, const BitTorrent::Torr // Fill list in const QVector fp = torrent->filesProgress(); int nbFiles = torrent->filesCount(); - for (int i = 0; i < nbFiles; ++i) { + for (int i = 0; i < nbFiles; ++i) + { QString fileName = torrent->fileName(i); if (fileName.endsWith(QB_EXT)) fileName.chop(4); QString extension = Utils::Fs::fileExtension(fileName).toUpper(); - if (Utils::Misc::isPreviewable(extension)) { + if (Utils::Misc::isPreviewable(extension)) + { int row = m_previewListModel->rowCount(); m_previewListModel->insertRow(row); m_previewListModel->setData(m_previewListModel->index(row, NAME), fileName); @@ -128,7 +130,8 @@ void PreviewSelectDialog::previewButtonClicked() // Only one file should be selected const QString path = absolutePaths.at(selectedIndexes.at(0).data().toInt()); // File - if (!QFile::exists(path)) { + if (!QFile::exists(path)) + { const bool isSingleFile = (m_previewListModel->rowCount() == 1); QWidget *parent = isSingleFile ? this->parentWidget() : this; QMessageBox::critical(parent, tr("Preview impossible") @@ -156,7 +159,8 @@ void PreviewSelectDialog::loadWindowState() Utils::Gui::resize(this, m_storeDialogSize); // Restore TreeView Header state - if (!m_storeTreeHeaderState.value().isEmpty()) { + if (!m_storeTreeHeaderState.value().isEmpty()) + { m_headerStateInitialized = m_ui->previewList->header()->restoreState(m_storeTreeHeaderState); } } @@ -164,14 +168,16 @@ void PreviewSelectDialog::loadWindowState() void PreviewSelectDialog::showEvent(QShowEvent *event) { // event originated from system - if (event->spontaneous()) { + if (event->spontaneous()) + { QDialog::showEvent(event); return; } // Default size, have to be called after show(), because width is needed // Set Name column width to 60% of TreeView - if (!m_headerStateInitialized) { + if (!m_headerStateInitialized) + { const int nameSize = (m_ui->previewList->size().width() * 0.6); m_ui->previewList->header()->resizeSection(0, nameSize); m_headerStateInitialized = true; diff --git a/src/gui/programupdater.cpp b/src/gui/programupdater.cpp index 80ddd8d99..fb56e88ea 100644 --- a/src/gui/programupdater.cpp +++ b/src/gui/programupdater.cpp @@ -70,7 +70,8 @@ void ProgramUpdater::checkForUpdates() void ProgramUpdater::rssDownloadFinished(const Net::DownloadResult &result) { - if (result.status != Net::DownloadStatus::Success) { + if (result.status != Net::DownloadStatus::Success) + { qDebug() << "Downloading the new qBittorrent updates RSS failed:" << result.errorString; emit updateCheckFinished(false, QString(), m_invokedByUser); return; @@ -81,7 +82,8 @@ void ProgramUpdater::rssDownloadFinished(const Net::DownloadResult &result) #ifdef Q_OS_MACOS const QString OS_TYPE {"Mac OS X"}; #elif defined(Q_OS_WIN) - const QString OS_TYPE {(::IsWindows7OrGreater() + const QString OS_TYPE + {(::IsWindows7OrGreater() && QSysInfo::currentCpuArchitecture().endsWith("64")) ? "Windows x64" : "Windows"}; #endif @@ -92,10 +94,12 @@ void ProgramUpdater::rssDownloadFinished(const Net::DownloadResult &result) QString updateLink; QString type; - while (!xml.atEnd()) { + while (!xml.atEnd()) + { xml.readNext(); - if (xml.isStartElement()) { + if (xml.isStartElement()) + { if (xml.name() == "item") inItem = true; else if (inItem && xml.name() == "link") @@ -105,11 +109,15 @@ void ProgramUpdater::rssDownloadFinished(const Net::DownloadResult &result) else if (inItem && xml.name() == "version") version = getStringValue(xml); } - else if (xml.isEndElement()) { - if (inItem && xml.name() == "item") { - if (type.compare(OS_TYPE, Qt::CaseInsensitive) == 0) { + else if (xml.isEndElement()) + { + if (inItem && xml.name() == "item") + { + if (type.compare(OS_TYPE, Qt::CaseInsensitive) == 0) + { qDebug("The last update available is %s", qUtf8Printable(version)); - if (!version.isEmpty()) { + if (!version.isEmpty()) + { qDebug("Detected version is %s", qUtf8Printable(version)); if (isVersionMoreRecent(version)) m_updateUrl = updateLink; @@ -138,12 +146,14 @@ void ProgramUpdater::updateProgram() bool ProgramUpdater::isVersionMoreRecent(const QString &remoteVersion) const { const QRegularExpressionMatch regVerMatch = QRegularExpression("([0-9.]+)").match(QBT_VERSION); - if (regVerMatch.hasMatch()) { + if (regVerMatch.hasMatch()) + { const QString localVersion = regVerMatch.captured(1); const QVector remoteParts = remoteVersion.splitRef('.'); const QVector localParts = localVersion.splitRef('.'); - for (int i = 0; i < qMin(remoteParts.size(), localParts.size()); ++i) { + for (int i = 0; i < qMin(remoteParts.size(), localParts.size()); ++i) + { if (remoteParts[i].toInt() > localParts[i].toInt()) return true; if (remoteParts[i].toInt() < localParts[i].toInt()) diff --git a/src/gui/properties/downloadedpiecesbar.cpp b/src/gui/properties/downloadedpiecesbar.cpp index 90e60a153..db0f25a13 100644 --- a/src/gui/properties/downloadedpiecesbar.cpp +++ b/src/gui/properties/downloadedpiecesbar.cpp @@ -59,7 +59,8 @@ QVector DownloadedPiecesBar::bitfieldToFloatVector(const QBitArray &vecin // image.x(0) = pieces.x(0.0 >= x < 1.7) // image.x(1) = pieces.x(1.7 >= x < 3.4) - for (int x = 0; x < reqSize; ++x) { + for (int x = 0; x < reqSize; ++x) + { // R - real const float fromR = x * ratio; const float toR = (x + 1) * ratio; @@ -80,15 +81,18 @@ QVector DownloadedPiecesBar::bitfieldToFloatVector(const QBitArray &vecin float value = 0; // case when calculated range is (15.2 >= x < 15.7) - if (x2 == toCMinusOne) { + if (x2 == toCMinusOne) + { if (vecin[x2]) value += ratio; ++x2; } // case when (15.2 >= x < 17.8) - else { + else + { // subcase (15.2 >= x < 16) - if (x2 != fromR) { + if (x2 != fromR) + { if (vecin[x2]) value += 1.0 - (fromR - fromC); ++x2; @@ -100,7 +104,8 @@ QVector DownloadedPiecesBar::bitfieldToFloatVector(const QBitArray &vecin value += 1.0; // subcase (17 >= x < 17.8) - if (x2 == toCMinusOne) { + if (x2 == toCMinusOne) + { if (vecin[x2]) value += 1.0 - (toC - toR); ++x2; @@ -123,12 +128,14 @@ bool DownloadedPiecesBar::updateImage(QImage &image) { // qDebug() << "updateImage"; QImage image2(width() - 2 * borderWidth, 1, QImage::Format_RGB888); - if (image2.isNull()) { + if (image2.isNull()) + { qDebug() << "QImage image2() allocation failed, width():" << width(); return false; } - if (m_pieces.isEmpty()) { + if (m_pieces.isEmpty()) + { image2.fill(backgroundColor()); image = image2; return true; @@ -138,10 +145,12 @@ bool DownloadedPiecesBar::updateImage(QImage &image) QVector scaledPiecesDl = bitfieldToFloatVector(m_downloadedPieces, image2.width()); // filling image - for (int x = 0; x < scaledPieces.size(); ++x) { + for (int x = 0; x < scaledPieces.size(); ++x) + { float piecesToValue = scaledPieces.at(x); float piecesToValueDl = scaledPiecesDl.at(x); - if (piecesToValueDl != 0) { + if (piecesToValueDl != 0) + { float fillRatio = piecesToValue + piecesToValueDl; float ratio = piecesToValueDl / fillRatio; @@ -150,7 +159,8 @@ bool DownloadedPiecesBar::updateImage(QImage &image) image2.setPixel(x, 0, mixedColor); } - else { + else + { image2.setPixel(x, 0, pieceColors()[piecesToValue * 255]); } } diff --git a/src/gui/properties/peerlistsortmodel.cpp b/src/gui/properties/peerlistsortmodel.cpp index 7aa160c32..158acb5b6 100644 --- a/src/gui/properties/peerlistsortmodel.cpp +++ b/src/gui/properties/peerlistsortmodel.cpp @@ -39,9 +39,11 @@ PeerListSortModel::PeerListSortModel(QObject *parent) bool PeerListSortModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - switch (sortColumn()) { + switch (sortColumn()) + { case PeerListWidget::IP: - case PeerListWidget::CLIENT: { + case PeerListWidget::CLIENT: + { const QString strL = left.data(UnderlyingDataRole).toString(); const QString strR = right.data(UnderlyingDataRole).toString(); const int result = Utils::String::naturalCompare(strL, strR, Qt::CaseInsensitive); diff --git a/src/gui/properties/peerlistwidget.cpp b/src/gui/properties/peerlistwidget.cpp index 8b10ccd72..96729a780 100644 --- a/src/gui/properties/peerlistwidget.cpp +++ b/src/gui/properties/peerlistwidget.cpp @@ -126,8 +126,10 @@ PeerListWidget::PeerListWidget(PropertiesWidget *parent) hideColumn(PeerListColumns::COUNTRY); // Ensure that at least one column is visible at all times bool atLeastOne = false; - for (int i = 0; i < PeerListColumns::IP_HIDDEN; ++i) { - if (!isColumnHidden(i)) { + for (int i = 0; i < PeerListColumns::IP_HIDDEN; ++i) + { + if (!isColumnHidden(i)) + { atLeastOne = true; break; } @@ -137,7 +139,8 @@ PeerListWidget::PeerListWidget(PropertiesWidget *parent) // To also mitigate the above issue, we have to resize each column when // its size is 0, because explicitly 'showing' the column isn't enough // in the above scenario. - for (int i = 0; i < PeerListColumns::IP_HIDDEN; ++i) { + for (int i = 0; i < PeerListColumns::IP_HIDDEN; ++i) + { if ((columnWidth(i) <= 0) && !isColumnHidden(i)) resizeColumnToContents(i); } @@ -178,7 +181,8 @@ void PeerListWidget::displayToggleColumnsMenu(const QPoint &) menu->setAttribute(Qt::WA_DeleteOnClose); menu->setTitle(tr("Column visibility")); - for (int i = 0; i < PeerListColumns::IP_HIDDEN; ++i) { + for (int i = 0; i < PeerListColumns::IP_HIDDEN; ++i) + { if ((i == PeerListColumns::COUNTRY) && !Preferences::instance()->resolvePeerCountries()) continue; @@ -191,7 +195,8 @@ void PeerListWidget::displayToggleColumnsMenu(const QPoint &) connect(menu, &QMenu::triggered, this, [this](const QAction *action) { int visibleCols = 0; - for (int i = 0; i < PeerListColumns::IP_HIDDEN; ++i) { + for (int i = 0; i < PeerListColumns::IP_HIDDEN; ++i) + { if (!isColumnHidden(i)) ++visibleCols; @@ -217,14 +222,17 @@ void PeerListWidget::displayToggleColumnsMenu(const QPoint &) void PeerListWidget::updatePeerHostNameResolutionState() { - if (Preferences::instance()->resolvePeerHostNames()) { - if (!m_resolver) { + if (Preferences::instance()->resolvePeerHostNames()) + { + if (!m_resolver) + { m_resolver = new Net::ReverseResolution(this); connect(m_resolver, &Net::ReverseResolution::ipResolved, this, &PeerListWidget::handleResolved); loadPeers(m_properties->getCurrentTorrent()); } } - else { + else + { delete m_resolver; m_resolver = nullptr; } @@ -237,13 +245,15 @@ void PeerListWidget::updatePeerCountryResolutionState() return; m_resolveCountries = resolveCountries; - if (m_resolveCountries) { + if (m_resolveCountries) + { loadPeers(m_properties->getCurrentTorrent()); showColumn(PeerListColumns::COUNTRY); if (columnWidth(PeerListColumns::COUNTRY) <= 0) resizeColumnToContents(PeerListColumns::COUNTRY); } - else { + else + { hideColumn(PeerListColumns::COUNTRY); } } @@ -258,7 +268,8 @@ void PeerListWidget::showPeerListMenu(const QPoint &) // Add Peer Action // Do not allow user to add peers in a private torrent - if (!torrent->isQueued() && !torrent->isChecking() && !torrent->isPrivate()) { + if (!torrent->isQueued() && !torrent->isChecking() && !torrent->isPrivate()) + { const QAction *addPeerAct = menu->addAction(UIThemeManager::instance()->getIcon("user-group-new"), tr("Add a new peer...")); connect(addPeerAct, &QAction::triggered, this, [this, torrent]() { @@ -274,7 +285,8 @@ void PeerListWidget::showPeerListMenu(const QPoint &) }); } - if (!selectionModel()->selectedRows().isEmpty()) { + if (!selectionModel()->selectedRows().isEmpty()) + { const QAction *copyPeerAct = menu->addAction(UIThemeManager::instance()->getIcon("edit-copy"), tr("Copy IP:port")); connect(copyPeerAct, &QAction::triggered, this, &PeerListWidget::copySelectedPeers); @@ -298,7 +310,8 @@ void PeerListWidget::banSelectedPeers() QVector selectedIPs; selectedIPs.reserve(selectedIndexes.size()); - for (const QModelIndex &index : selectedIndexes) { + for (const QModelIndex &index : selectedIndexes) + { const int row = m_proxyModel->mapToSource(index).row(); const QString ip = m_listModel->item(row, PeerListColumns::IP_HIDDEN)->text(); selectedIPs += ip; @@ -309,7 +322,8 @@ void PeerListWidget::banSelectedPeers() , tr("Are you sure you want to permanently ban the selected peers?")); if (btn != QMessageBox::Yes) return; - for (const QString &ip : selectedIPs) { + for (const QString &ip : selectedIPs) + { BitTorrent::Session::instance()->banIP(ip); LogMsg(tr("Peer \"%1\" is manually banned").arg(ip)); } @@ -322,7 +336,8 @@ void PeerListWidget::copySelectedPeers() const QModelIndexList selectedIndexes = selectionModel()->selectedRows(); QStringList selectedPeers; - for (const QModelIndex &index : selectedIndexes) { + for (const QModelIndex &index : selectedIndexes) + { const int row = m_proxyModel->mapToSource(index).row(); const QString ip = m_listModel->item(row, PeerListColumns::IP_HIDDEN)->text(); const QString port = m_listModel->item(row, PeerListColumns::PORT)->text(); @@ -364,19 +379,22 @@ void PeerListWidget::loadPeers(const BitTorrent::TorrentHandle *torrent) for (auto i = m_peerItems.cbegin(); i != m_peerItems.cend(); ++i) existingPeers << i.key(); - for (const BitTorrent::PeerInfo &peer : peers) { + for (const BitTorrent::PeerInfo &peer : peers) + { if (peer.address().ip.isNull()) continue; bool isNewPeer = false; updatePeer(torrent, peer, isNewPeer); - if (!isNewPeer) { + if (!isNewPeer) + { const PeerEndpoint peerEndpoint {peer.address(), peer.connectionType()}; existingPeers.remove(peerEndpoint); } } // Remove peers that are gone - for (const PeerEndpoint &peerEndpoint : asConst(existingPeers)) { + for (const PeerEndpoint &peerEndpoint : asConst(existingPeers)) + { QStandardItem *item = m_peerItems.take(peerEndpoint); QSet &items = m_itemsByIP[peerEndpoint.address.ip]; @@ -411,7 +429,8 @@ void PeerListWidget::updatePeer(const BitTorrent::TorrentHandle *torrent, const auto itemIter = m_peerItems.find(peerEndpoint); isNewPeer = (itemIter == m_peerItems.end()); - if (isNewPeer) { + if (isNewPeer) + { // new item const int row = m_listModel->rowCount(); m_listModel->insertRow(row); @@ -449,9 +468,11 @@ void PeerListWidget::updatePeer(const BitTorrent::TorrentHandle *torrent, const if (m_resolver) m_resolver->resolve(peerEndpoint.address.ip); - if (m_resolveCountries) { + if (m_resolveCountries) + { const QIcon icon = UIThemeManager::instance()->getFlagIcon(peer.country()); - if (!icon.isNull()) { + if (!icon.isNull()) + { m_listModel->setData(m_listModel->index(row, PeerListColumns::COUNTRY), icon, Qt::DecorationRole); const QString countryName = Net::GeoIPManager::CountryName(peer.country()); m_listModel->setData(m_listModel->index(row, PeerListColumns::COUNTRY), countryName, Qt::ToolTipRole); @@ -479,7 +500,8 @@ void PeerListWidget::handleSortColumnChanged(const int col) void PeerListWidget::wheelEvent(QWheelEvent *event) { - if (event->modifiers() & Qt::ShiftModifier) { + if (event->modifiers() & Qt::ShiftModifier) + { // Shift + scroll = horizontal scroll event->accept(); diff --git a/src/gui/properties/peersadditiondialog.cpp b/src/gui/properties/peersadditiondialog.cpp index 2d18a5e5b..f0349ed85 100644 --- a/src/gui/properties/peersadditiondialog.cpp +++ b/src/gui/properties/peersadditiondialog.cpp @@ -57,18 +57,22 @@ QVector PeersAdditionDialog::askForPeers(QWidget *paren void PeersAdditionDialog::validateInput() { - if (m_ui->textEditPeers->toPlainText().trimmed().isEmpty()) { + if (m_ui->textEditPeers->toPlainText().trimmed().isEmpty()) + { QMessageBox::warning(this, tr("No peer entered"), tr("Please type at least one peer."), QMessageBox::Ok); return; } - for (const QString &peer : asConst(m_ui->textEditPeers->toPlainText().trimmed().split('\n'))) { + for (const QString &peer : asConst(m_ui->textEditPeers->toPlainText().trimmed().split('\n'))) + { const BitTorrent::PeerAddress addr = BitTorrent::PeerAddress::parse(peer); - if (!addr.ip.isNull()) { + if (!addr.ip.isNull()) + { m_peersList.append(addr); } - else { + else + { QMessageBox::warning(this, tr("Invalid peer"), tr("The peer '%1' is invalid.").arg(peer), QMessageBox::Ok); diff --git a/src/gui/properties/pieceavailabilitybar.cpp b/src/gui/properties/pieceavailabilitybar.cpp index f03b6b855..3eba18020 100644 --- a/src/gui/properties/pieceavailabilitybar.cpp +++ b/src/gui/properties/pieceavailabilitybar.cpp @@ -58,7 +58,8 @@ QVector PieceAvailabilityBar::intToFloatVector(const QVector &vecin, // image.x(0) = pieces.x(0.0 >= x < 1.7) // image.x(1) = pieces.x(1.7 >= x < 3.4) - for (int x = 0; x < reqSize; ++x) { + for (int x = 0; x < reqSize; ++x) + { // R - real const float fromR = x * ratio; const float toR = (x + 1) * ratio; @@ -79,15 +80,18 @@ QVector PieceAvailabilityBar::intToFloatVector(const QVector &vecin, float value = 0; // case when calculated range is (15.2 >= x < 15.7) - if (x2 == toCMinusOne) { + if (x2 == toCMinusOne) + { if (vecin[x2]) value += ratio * vecin[x2]; ++x2; } // case when (15.2 >= x < 17.8) - else { + else + { // subcase (15.2 >= x < 16) - if (x2 != fromR) { + if (x2 != fromR) + { if (vecin[x2]) value += (1.0 - (fromR - fromC)) * vecin[x2]; ++x2; @@ -99,7 +103,8 @@ QVector PieceAvailabilityBar::intToFloatVector(const QVector &vecin, value += vecin[x2]; // subcase (17 >= x < 17.8) - if (x2 == toCMinusOne) { + if (x2 == toCMinusOne) + { if (vecin[x2]) value += (1.0 - (toC - toR)) * vecin[x2]; ++x2; @@ -121,12 +126,14 @@ QVector PieceAvailabilityBar::intToFloatVector(const QVector &vecin, bool PieceAvailabilityBar::updateImage(QImage &image) { QImage image2(width() - 2 * borderWidth, 1, QImage::Format_RGB888); - if (image2.isNull()) { + if (image2.isNull()) + { qDebug() << "QImage image2() allocation failed, width():" << width(); return false; } - if (m_pieces.empty()) { + if (m_pieces.empty()) + { image2.fill(backgroundColor()); image = image2; return true; @@ -135,7 +142,8 @@ bool PieceAvailabilityBar::updateImage(QImage &image) QVector scaledPieces = intToFloatVector(m_pieces, image2.width()); // filling image - for (int x = 0; x < scaledPieces.size(); ++x) { + for (int x = 0; x < scaledPieces.size(); ++x) + { float piecesToValue = scaledPieces.at(x); image2.setPixel(x, 0, pieceColors()[piecesToValue * 255]); } diff --git a/src/gui/properties/piecesbar.cpp b/src/gui/properties/piecesbar.cpp index 458edcf3e..9acaa572b 100644 --- a/src/gui/properties/piecesbar.cpp +++ b/src/gui/properties/piecesbar.cpp @@ -53,7 +53,8 @@ namespace { public: PieceIndexToImagePos(const BitTorrent::TorrentInfo &torrentInfo, const QImage &image) - : m_bytesPerPixel {((image.width() > 0) && (torrentInfo.totalSize() >= image.width())) + : m_bytesPerPixel + {((image.width() > 0) && (torrentInfo.totalSize() >= image.width())) ? torrentInfo.totalSize() / image.width() : -1} , m_torrentInfo {torrentInfo} { @@ -133,7 +134,8 @@ void PiecesBar::clear() bool PiecesBar::event(QEvent *e) { - if (e->type() == QEvent::ToolTip) { + if (e->type() == QEvent::ToolTip) + { showToolTip(static_cast(e)); return true; } @@ -167,17 +169,20 @@ void PiecesBar::paintEvent(QPaintEvent *) { QPainter painter(this); QRect imageRect(borderWidth, borderWidth, width() - 2 * borderWidth, height() - 2 * borderWidth); - if (m_image.isNull()) { + if (m_image.isNull()) + { painter.setBrush(backgroundColor()); painter.drawRect(imageRect); } - else { + else + { if (m_image.width() != imageRect.width()) updateImage(m_image); painter.drawImage(imageRect, m_image); } - if (!m_highlitedRegion.isNull()) { + if (!m_highlitedRegion.isNull()) + { QColor highlightColor {this->palette().color(QPalette::Active, QPalette::Highlight)}; highlightColor.setAlphaF(0.35); QRect targetHighlightRect {m_highlitedRegion.adjusted(borderWidth, borderWidth, borderWidth, height() - 2 * borderWidth)}; @@ -247,19 +252,23 @@ void PiecesBar::showToolTip(const QHelpEvent *e) QString toolTipText; QTextStream stream(&toolTipText, QIODevice::WriteOnly); const bool showDetailedInformation = QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier); - if (showDetailedInformation && m_torrent->hasMetadata()) { + if (showDetailedInformation && m_torrent->hasMetadata()) + { const int imagePos = e->pos().x() - borderWidth; - if ((imagePos >=0) && (imagePos < m_image.width())) { + if ((imagePos >=0) && (imagePos < m_image.width())) + { stream << ""; PieceIndexToImagePos transform {m_torrent->info(), m_image}; int pieceIndex = transform.pieceIndex(imagePos); const QVector files {m_torrent->info().fileIndicesForPiece(pieceIndex)}; QString tooltipTitle; - if (files.count() > 1) { + if (files.count() > 1) + { tooltipTitle = tr("Files in this piece:"); } - else { + else + { if (m_torrent->info().fileSize(files.front()) == m_torrent->info().pieceLength(pieceIndex)) tooltipTitle = tr("File in this piece"); else @@ -268,14 +277,16 @@ void PiecesBar::showToolTip(const QHelpEvent *e) DetailedTooltipRenderer renderer(stream, tooltipTitle); - for (int f : files) { + for (int f : files) + { const QString filePath {m_torrent->info().filePath(f)}; renderer(Utils::Misc::friendlyUnit(m_torrent->info().fileSize(f)), filePath); } stream << ""; } } - else { + else + { stream << simpleToolTipText(); if (showDetailedInformation) // metadata are not available at this point stream << '\n' << tr("Wait until metadata become available to see detailed information"); @@ -297,17 +308,20 @@ void PiecesBar::highlightFile(int imagePos) int pieceIndex = transform.pieceIndex(imagePos); QVector fileIndices {m_torrent->info().fileIndicesForPiece(pieceIndex)}; - if (fileIndices.count() == 1) { + if (fileIndices.count() == 1) + { BitTorrent::TorrentInfo::PieceRange filePieces = m_torrent->info().filePieces(fileIndices.first()); ImageRange imageRange = transform.imagePos(filePieces); QRect newHighlitedRegion {imageRange.first(), 0, imageRange.size(), m_image.height()}; - if (newHighlitedRegion != m_highlitedRegion) { + if (newHighlitedRegion != m_highlitedRegion) + { m_highlitedRegion = newHighlitedRegion; update(); } } - else if (!m_highlitedRegion.isEmpty()) { + else if (!m_highlitedRegion.isEmpty()) + { m_highlitedRegion = QRect(); update(); } @@ -316,7 +330,8 @@ void PiecesBar::highlightFile(int imagePos) void PiecesBar::updatePieceColors() { m_pieceColors = QVector(256); - for (int i = 0; i < 256; ++i) { + for (int i = 0; i < 256; ++i) + { float ratio = (i / 255.0); m_pieceColors[i] = mixTwoColors(backgroundColor().rgb(), pieceColor().rgb(), ratio); } diff --git a/src/gui/properties/propertieswidget.cpp b/src/gui/properties/propertieswidget.cpp index 618081200..7b8c41d7e 100644 --- a/src/gui/properties/propertieswidget.cpp +++ b/src/gui/properties/propertieswidget.cpp @@ -194,7 +194,8 @@ void PropertiesWidget::showPiecesDownloaded(bool show) void PropertiesWidget::setVisibility(const bool visible) { - if (!visible && (m_state == VISIBLE)) { + if (!visible && (m_state == VISIBLE)) + { const int tabBarHeight = m_tabBar->geometry().height(); // take height before hiding auto *hSplitter = static_cast(parentWidget()); m_ui->stackedProperties->setVisible(false); @@ -210,7 +211,8 @@ void PropertiesWidget::setVisibility(const bool visible) return; } - if (visible && (m_state == REDUCED)) { + if (visible && (m_state == REDUCED)) + { m_ui->stackedProperties->setVisible(true); auto *hSplitter = static_cast(parentWidget()); if (m_handleWidth != -1) @@ -314,7 +316,8 @@ void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent // Hash m_ui->labelHashVal->setText(m_torrent->hash()); m_propListModel->model()->clear(); - if (m_torrent->hasMetadata()) { + if (m_torrent->hasMetadata()) + { // Creation date m_ui->labelCreatedOnVal->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate)); @@ -333,7 +336,8 @@ void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent // Expand single-item folders recursively QModelIndex currentIndex; - while (m_propListModel->rowCount(currentIndex) == 1) { + while (m_propListModel->rowCount(currentIndex) == 1) + { currentIndex = m_propListModel->index(0, 0, currentIndex); m_ui->filesList->setExpanded(currentIndex, true); } @@ -350,7 +354,8 @@ void PropertiesWidget::readSettings() const Preferences *const pref = Preferences::instance(); // Restore splitter sizes QStringList sizesStr = pref->getPropSplitterSizes().split(','); - if (sizesStr.size() == 2) { + if (sizesStr.size() == 2) + { m_slideSizes << sizesStr.first().toInt(); m_slideSizes << sizesStr.last().toInt(); auto *hSplitter = static_cast(parentWidget()); @@ -396,8 +401,10 @@ void PropertiesWidget::loadDynamicData() if (!m_torrent || (m_state != VISIBLE)) return; // Transfer infos - switch (m_ui->stackedProperties->currentIndex()) { - case PropTabBar::MainTab: { + switch (m_ui->stackedProperties->currentIndex()) + { + case PropTabBar::MainTab: + { m_ui->labelWastedVal->setText(Utils::Misc::friendlyUnit(m_torrent->wastedSize())); m_ui->labelUpTotalVal->setText(tr("%1 (%2 this session)").arg(Utils::Misc::friendlyUnit(m_torrent->totalUpload()) @@ -456,16 +463,19 @@ void PropertiesWidget::loadDynamicData() m_ui->labelAddedOnVal->setText(m_torrent->addedTime().toString(Qt::DefaultLocaleShortDate)); - if (m_torrent->hasMetadata()) { + if (m_torrent->hasMetadata()) + { m_ui->labelTotalPiecesVal->setText(tr("%1 x %2 (have %3)", "(torrent pieces) eg 152 x 4MB (have 25)").arg(m_torrent->piecesCount()).arg(Utils::Misc::friendlyUnit(m_torrent->pieceLength())).arg(m_torrent->piecesHave())); - if (!m_torrent->isSeed() && !m_torrent->isPaused() && !m_torrent->isQueued() && !m_torrent->isChecking()) { + if (!m_torrent->isSeed() && !m_torrent->isPaused() && !m_torrent->isQueued() && !m_torrent->isChecking()) + { // Pieces availability showPiecesAvailability(true); m_piecesAvailability->setAvailability(m_torrent->pieceAvailability()); m_ui->labelAverageAvailabilityVal->setText(Utils::String::fromDouble(m_torrent->distributedCopies(), 3)); } - else { + else + { showPiecesAvailability(false); } @@ -474,7 +484,8 @@ void PropertiesWidget::loadDynamicData() m_ui->labelProgressVal->setText(Utils::String::fromDouble(progress, 1) + '%'); m_downloadedPieces->setProgress(m_torrent->pieces(), m_torrent->downloadingPieces()); } - else { + else + { showPiecesAvailability(false); } } @@ -489,7 +500,8 @@ void PropertiesWidget::loadDynamicData() break; case PropTabBar::FilesTab: // Files progress - if (m_torrent->hasMetadata()) { + if (m_torrent->hasMetadata()) + { qDebug("Updating priorities in files tab"); m_ui->filesList->setUpdatesEnabled(false); m_propListModel->model()->updateFilesProgress(m_torrent->filesProgress()); @@ -511,7 +523,8 @@ void PropertiesWidget::loadUrlSeeds() qDebug("Loading URL seeds"); const QVector hcSeeds = m_torrent->urlSeeds(); // Add url seeds - for (const QUrl &hcSeed : hcSeeds) { + for (const QUrl &hcSeed : hcSeeds) + { qDebug("Loading URL seed: %s", qUtf8Printable(hcSeed.toString())); new QListWidgetItem(hcSeed.toString(), m_ui->listWebSeeds); } @@ -519,7 +532,8 @@ void PropertiesWidget::loadUrlSeeds() QString PropertiesWidget::getFullPath(const QModelIndex &index) const { - if (m_propListModel->itemType(index) == TorrentContentModelItem::FileType) { + if (m_propListModel->itemType(index) == TorrentContentModelItem::FileType) + { const int fileIdx = m_propListModel->getFileIndex(index); const QString filename {m_torrent->filePath(fileIdx)}; const QDir saveDir {m_torrent->savePath(true)}; @@ -568,7 +582,8 @@ void PropertiesWidget::displayFilesListMenu(const QPoint &) QMenu *menu = new QMenu(this); menu->setAttribute(Qt::WA_DeleteOnClose); - if (selectedRows.size() == 1) { + if (selectedRows.size() == 1) + { const QModelIndex index = selectedRows[0]; const QAction *actOpen = menu->addAction(UIThemeManager::instance()->getIcon("folder-documents"), tr("Open")); @@ -583,12 +598,14 @@ void PropertiesWidget::displayFilesListMenu(const QPoint &) menu->addSeparator(); } - if (!m_torrent->isSeed()) { + if (!m_torrent->isSeed()) + { QMenu *subMenu = menu->addMenu(tr("Priority")); const auto applyPriorities = [this, selectedRows](const BitTorrent::DownloadPriority prio) { - for (const QModelIndex &index : selectedRows) { + for (const QModelIndex &index : selectedRows) + { m_propListModel->setData( m_propListModel->index(index.row(), PRIORITY, index.parent()), static_cast(prio)); } @@ -646,7 +663,8 @@ void PropertiesWidget::displayWebSeedListMenu(const QPoint &) const QAction *actAdd = menu->addAction(UIThemeManager::instance()->getIcon("list-add"), tr("New Web seed")); connect(actAdd, &QAction::triggered, this, &PropertiesWidget::askWebSeed); - if (!rows.isEmpty()) { + if (!rows.isEmpty()) + { const QAction *actDel = menu->addAction(UIThemeManager::instance()->getIcon("list-remove"), tr("Remove Web seed")); connect(actDel, &QAction::triggered, this, &PropertiesWidget::deleteSelectedUrlSeeds); @@ -673,16 +691,20 @@ void PropertiesWidget::openSelectedFile() void PropertiesWidget::configure() { // Speed widget - if (Preferences::instance()->isSpeedWidgetEnabled()) { - if (!m_speedWidget || !qobject_cast(m_speedWidget)) { + if (Preferences::instance()->isSpeedWidgetEnabled()) + { + if (!m_speedWidget || !qobject_cast(m_speedWidget)) + { m_ui->speedLayout->removeWidget(m_speedWidget); delete m_speedWidget; m_speedWidget = new SpeedWidget {this}; m_ui->speedLayout->addWidget(m_speedWidget); } } - else { - if (!m_speedWidget || !qobject_cast(m_speedWidget)) { + else + { + if (!m_speedWidget || !qobject_cast(m_speedWidget)) + { m_ui->speedLayout->removeWidget(m_speedWidget); delete m_speedWidget; auto *label = new QLabel(tr("
Speed graphs are disabled

You may change this setting in Advanced Options

"), this); @@ -702,7 +724,8 @@ void PropertiesWidget::askWebSeed() QLatin1String("http://www."), &ok); if (!ok) return; qDebug("Adding %s web seed", qUtf8Printable(urlSeed)); - if (!m_ui->listWebSeeds->findItems(urlSeed, Qt::MatchFixedString).empty()) { + if (!m_ui->listWebSeeds->findItems(urlSeed, Qt::MatchFixedString).empty()) + { QMessageBox::warning(this, "qBittorrent", tr("This URL seed is already in the list."), QMessageBox::Ok); @@ -755,7 +778,8 @@ void PropertiesWidget::editWebSeed() oldSeed, &result); if (!result) return; - if (!m_ui->listWebSeeds->findItems(newSeed, Qt::MatchFixedString).empty()) { + if (!m_ui->listWebSeeds->findItems(newSeed, Qt::MatchFixedString).empty()) + { QMessageBox::warning(this, tr("qBittorrent"), tr("This URL seed is already in the list."), QMessageBox::Ok); @@ -781,11 +805,13 @@ void PropertiesWidget::filteredFilesChanged() void PropertiesWidget::filterText(const QString &filter) { m_propListModel->setFilterRegExp(QRegExp(filter, Qt::CaseInsensitive, QRegExp::WildcardUnix)); - if (filter.isEmpty()) { + if (filter.isEmpty()) + { m_ui->filesList->collapseAll(); m_ui->filesList->expand(m_propListModel->index(0, 0)); } - else { + else + { m_ui->filesList->expandAll(); } } diff --git a/src/gui/properties/proplistdelegate.cpp b/src/gui/properties/proplistdelegate.cpp index b3382ade6..3df53663f 100644 --- a/src/gui/properties/proplistdelegate.cpp +++ b/src/gui/properties/proplistdelegate.cpp @@ -72,11 +72,13 @@ void PropListDelegate::initProgressStyleOption(QStyleOptionProgressBar &option, ProgressBarDelegate::initProgressStyleOption(option, index); const int priority = index.sibling(index.row(), PRIORITY).data(TorrentContentModel::UnderlyingDataRole).toInt(); - if (static_cast(priority) == BitTorrent::DownloadPriority::Ignored) { + if (static_cast(priority) == BitTorrent::DownloadPriority::Ignored) + { option.state &= ~QStyle::State_Enabled; option.palette = progressBarDisabledPalette(); } - else { + else + { option.state |= QStyle::State_Enabled; } } @@ -86,7 +88,8 @@ void PropListDelegate::setEditorData(QWidget *editor, const QModelIndex &index) auto *combobox = static_cast(editor); // Set combobox index const int priority = index.data(TorrentContentModel::UnderlyingDataRole).toInt(); - switch (static_cast(priority)) { + switch (static_cast(priority)) + { case BitTorrent::DownloadPriority::Ignored: combobox->setCurrentIndex(0); break; @@ -106,7 +109,8 @@ QWidget *PropListDelegate::createEditor(QWidget *parent, const QStyleOptionViewI { if (index.column() != PRIORITY) return nullptr; - if (m_properties) { + if (m_properties) + { const BitTorrent::TorrentHandle *torrent = m_properties->getCurrentTorrent(); if (!torrent || !torrent->hasMetadata() || torrent->isSeed()) return nullptr; @@ -131,7 +135,8 @@ void PropListDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const int value = combobox->currentIndex(); BitTorrent::DownloadPriority prio = BitTorrent::DownloadPriority::Normal; // NORMAL - switch (value) { + switch (value) + { case 0: prio = BitTorrent::DownloadPriority::Ignored; // IGNORED break; diff --git a/src/gui/properties/proptabbar.cpp b/src/gui/properties/proptabbar.cpp index 96397e438..1f6b53e42 100644 --- a/src/gui/properties/proptabbar.cpp +++ b/src/gui/properties/proptabbar.cpp @@ -122,8 +122,10 @@ void PropTabBar::setCurrentIndex(int index) if (index >= m_btnGroup->buttons().size()) index = 0; // If asked to hide or if the currently selected tab is clicked - if ((index < 0) || (m_currentIndex == index)) { - if (m_currentIndex >= 0) { + if ((index < 0) || (m_currentIndex == index)) + { + if (m_currentIndex >= 0) + { m_btnGroup->button(m_currentIndex)->setDown(false); m_currentIndex = -1; emit visibilityToggled(false); @@ -131,10 +133,12 @@ void PropTabBar::setCurrentIndex(int index) return; } // Unselect previous tab - if (m_currentIndex >= 0) { + if (m_currentIndex >= 0) + { m_btnGroup->button(m_currentIndex)->setDown(false); } - else { + else + { // Nothing was selected, show! emit visibilityToggled(true); } diff --git a/src/gui/properties/speedplotview.cpp b/src/gui/properties/speedplotview.cpp index 26ce80b86..7c3677743 100644 --- a/src/gui/properties/speedplotview.cpp +++ b/src/gui/properties/speedplotview.cpp @@ -79,26 +79,30 @@ namespace if (value <= 12.0) return {12, SizeUnit::Byte}; SizeUnit calculatedUnit = SizeUnit::Byte; - while (value > 1024) { + while (value > 1024) + { value /= 1024; calculatedUnit = static_cast(static_cast(calculatedUnit) + 1); } - if (value > 100.0) { + if (value > 100.0) + { int roundedValue = static_cast(value / 40) * 40; while (roundedValue < value) roundedValue += 40; return {static_cast(roundedValue), calculatedUnit}; } - if (value > 10.0) { + if (value > 10.0) + { int roundedValue = static_cast(value / 4) * 4; while (roundedValue < value) roundedValue += 4; return {static_cast(roundedValue), calculatedUnit}; } - for (const auto &roundedValue : roundingTable) { + for (const auto &roundedValue : roundingTable) + { if (value <= roundedValue) return {roundedValue, calculatedUnit}; } @@ -215,7 +219,8 @@ void SpeedPlotView::setPeriod(const TimePeriod period) { m_period = period; - switch (period) { + switch (period) + { case SpeedPlotView::MIN1: m_viewablePointsCount = MIN1_SEC; m_currentData = &m_data5Min; @@ -266,7 +271,8 @@ quint64 SpeedPlotView::maxYValue() boost::circular_buffer &queue = getCurrentData(); quint64 maxYValue = 0; - for (int id = UP; id < NB_GRAPHS; ++id) { + for (int id = UP; id < NB_GRAPHS; ++id) + { if (!m_properties[static_cast(id)].enable) continue; @@ -292,7 +298,8 @@ void SpeedPlotView::paintEvent(QPaintEvent *) rect.adjust(0, fontMetrics.height(), 0, 0); // Add top padding for top speed text // draw Y axis speed labels - const QVector speedLabels = { + const QVector speedLabels = + { formatLabel(niceScale.arg, niceScale.unit), formatLabel((0.75 * niceScale.arg), niceScale.unit), formatLabel((0.50 * niceScale.arg), niceScale.unit), @@ -311,7 +318,8 @@ void SpeedPlotView::paintEvent(QPaintEvent *) #endif int i = 0; - for (const QString &label : speedLabels) { + for (const QString &label : speedLabels) + { QRectF labelRect(rect.topLeft() + QPointF(-yAxisWidth, (i++) * 0.25 * rect.height() - fontMetrics.height()), QSizeF(2 * yAxisWidth, fontMetrics.height())); painter.drawText(labelRect, label, Qt::AlignRight | Qt::AlignTop); @@ -333,7 +341,8 @@ void SpeedPlotView::paintEvent(QPaintEvent *) painter.drawLine(fullRect.left(), rect.bottom(), rect.right(), rect.bottom()); const int TIME_AXIS_DIVISIONS = 6; - for (int i = 0; i < TIME_AXIS_DIVISIONS; ++i) { + for (int i = 0; i < TIME_AXIS_DIVISIONS; ++i) + { const int x = rect.left() + (i * rect.width()) / TIME_AXIS_DIVISIONS; painter.drawLine(x, fullRect.top(), x, fullRect.bottom()); } @@ -349,12 +358,14 @@ void SpeedPlotView::paintEvent(QPaintEvent *) boost::circular_buffer &queue = getCurrentData(); - for (int id = UP; id < NB_GRAPHS; ++id) { + for (int id = UP; id < NB_GRAPHS; ++id) + { if (!m_properties[static_cast(id)].enable) continue; QVector points; - for (int i = static_cast(queue.size()) - 1, j = 0; (i >= 0) && (j < m_viewablePointsCount); --i, ++j) { + for (int i = static_cast(queue.size()) - 1, j = 0; (i >= 0) && (j < m_viewablePointsCount); --i, ++j) + { int newX = rect.right() - j * xTickSize; int newY = rect.bottom() - queue[i].y[id] * yMultiplier; @@ -371,7 +382,8 @@ void SpeedPlotView::paintEvent(QPaintEvent *) double legendHeight = 0; int legendWidth = 0; - for (const auto &property : asConst(m_properties)) { + for (const auto &property : asConst(m_properties)) + { if (!property.enable) continue; @@ -391,7 +403,8 @@ void SpeedPlotView::paintEvent(QPaintEvent *) painter.fillRect(legendBackgroundRect, legendBackgroundColor); i = 0; - for (const auto &property : asConst(m_properties)) { + for (const auto &property : asConst(m_properties)) + { if (!property.enable) continue; diff --git a/src/gui/properties/speedwidget.cpp b/src/gui/properties/speedwidget.cpp index 804a35bc4..880d5921e 100644 --- a/src/gui/properties/speedwidget.cpp +++ b/src/gui/properties/speedwidget.cpp @@ -92,7 +92,8 @@ SpeedWidget::SpeedWidget(PropertiesWidget *parent) m_graphsMenuActions = m_graphsMenu->actions(); - for (int id = SpeedPlotView::UP; id < SpeedPlotView::NB_GRAPHS; ++id) { + for (int id = SpeedPlotView::UP; id < SpeedPlotView::NB_GRAPHS; ++id) + { QAction *action = m_graphsMenuActions.at(id); action->setCheckable(true); action->setChecked(true); @@ -168,7 +169,8 @@ void SpeedWidget::loadSettings() m_periodCombobox->setCurrentIndex(periodIndex); onPeriodChange(static_cast(periodIndex)); - for (int id = SpeedPlotView::UP; id < SpeedPlotView::NB_GRAPHS; ++id) { + for (int id = SpeedPlotView::UP; id < SpeedPlotView::NB_GRAPHS; ++id) + { QAction *action = m_graphsMenuActions.at(id); bool enable = preferences->getSpeedWidgetGraphEnable(id); @@ -183,7 +185,8 @@ void SpeedWidget::saveSettings() const preferences->setSpeedWidgetPeriod(m_periodCombobox->currentIndex()); - for (int id = SpeedPlotView::UP; id < SpeedPlotView::NB_GRAPHS; ++id) { + for (int id = SpeedPlotView::UP; id < SpeedPlotView::NB_GRAPHS; ++id) + { QAction *action = m_graphsMenuActions.at(id); preferences->setSpeedWidgetGraphEnable(id, action->isChecked()); } diff --git a/src/gui/properties/trackerlistwidget.cpp b/src/gui/properties/trackerlistwidget.cpp index 3a4d57e8b..5d1676ba9 100644 --- a/src/gui/properties/trackerlistwidget.cpp +++ b/src/gui/properties/trackerlistwidget.cpp @@ -152,7 +152,8 @@ QVector TrackerListWidget::getSelectedTrackerItems() const QVector selectedTrackers; selectedTrackers.reserve(selectedTrackerItems.size()); - for (QTreeWidgetItem *item : selectedTrackerItems) { + for (QTreeWidgetItem *item : selectedTrackerItems) + { if (indexOfTopLevelItem(item) >= NB_STICKY_ITEM) // Ignore STICKY ITEMS selectedTrackers << item; } @@ -171,7 +172,8 @@ void TrackerListWidget::setRowColor(const int row, const QColor &color) void TrackerListWidget::moveSelectionUp() { BitTorrent::TorrentHandle *const torrent = m_properties->getCurrentTorrent(); - if (!torrent) { + if (!torrent) + { clear(); return; } @@ -179,9 +181,11 @@ void TrackerListWidget::moveSelectionUp() if (selectedTrackerItems.isEmpty()) return; bool change = false; - for (QTreeWidgetItem *item : selectedTrackerItems) { + for (QTreeWidgetItem *item : selectedTrackerItems) + { int index = indexOfTopLevelItem(item); - if (index > NB_STICKY_ITEM) { + if (index > NB_STICKY_ITEM) + { insertTopLevelItem(index - 1, takeTopLevelItem(index)); change = true; } @@ -197,7 +201,8 @@ void TrackerListWidget::moveSelectionUp() // Update torrent trackers QVector trackers; trackers.reserve(topLevelItemCount()); - for (int i = NB_STICKY_ITEM; i < topLevelItemCount(); ++i) { + for (int i = NB_STICKY_ITEM; i < topLevelItemCount(); ++i) + { const QString trackerURL = topLevelItem(i)->data(COL_URL, Qt::DisplayRole).toString(); BitTorrent::TrackerEntry e(trackerURL); e.setTier(i - NB_STICKY_ITEM); @@ -213,7 +218,8 @@ void TrackerListWidget::moveSelectionUp() void TrackerListWidget::moveSelectionDown() { BitTorrent::TorrentHandle *const torrent = m_properties->getCurrentTorrent(); - if (!torrent) { + if (!torrent) + { clear(); return; } @@ -221,9 +227,11 @@ void TrackerListWidget::moveSelectionDown() if (selectedTrackerItems.isEmpty()) return; bool change = false; - for (int i = selectedItems().size() - 1; i >= 0; --i) { + for (int i = selectedItems().size() - 1; i >= 0; --i) + { int index = indexOfTopLevelItem(selectedTrackerItems.at(i)); - if (index < (topLevelItemCount() - 1)) { + if (index < (topLevelItemCount() - 1)) + { insertTopLevelItem(index + 1, takeTopLevelItem(index)); change = true; } @@ -239,7 +247,8 @@ void TrackerListWidget::moveSelectionDown() // Update torrent trackers QVector trackers; trackers.reserve(topLevelItemCount()); - for (int i = NB_STICKY_ITEM; i < topLevelItemCount(); ++i) { + for (int i = NB_STICKY_ITEM; i < topLevelItemCount(); ++i) + { const QString trackerURL = topLevelItem(i)->data(COL_URL, Qt::DisplayRole).toString(); BitTorrent::TrackerEntry e(trackerURL); e.setTier(i - NB_STICKY_ITEM); @@ -294,7 +303,8 @@ void TrackerListWidget::loadStickyItems(const BitTorrent::TorrentHandle *torrent else m_LSDItem->setText(COL_STATUS, disabled); - if (torrent->isPrivate()) { + if (torrent->isPrivate()) + { QString privateMsg = tr("This torrent is private"); m_DHTItem->setText(COL_MSG, privateMsg); m_PEXItem->setText(COL_MSG, privateMsg); @@ -304,22 +314,26 @@ void TrackerListWidget::loadStickyItems(const BitTorrent::TorrentHandle *torrent // XXX: libtorrent should provide this info... // Count peers from DHT, PeX, LSD uint seedsDHT = 0, seedsPeX = 0, seedsLSD = 0, peersDHT = 0, peersPeX = 0, peersLSD = 0; - for (const BitTorrent::PeerInfo &peer : asConst(torrent->peers())) { + for (const BitTorrent::PeerInfo &peer : asConst(torrent->peers())) + { if (peer.isConnecting()) continue; - if (peer.fromDHT()) { + if (peer.fromDHT()) + { if (peer.isSeed()) ++seedsDHT; else ++peersDHT; } - if (peer.fromPeX()) { + if (peer.fromPeX()) + { if (peer.isSeed()) ++seedsPeX; else ++peersPeX; } - if (peer.fromLSD()) { + if (peer.fromLSD()) + { if (peer.isSeed()) ++seedsLSD; else @@ -347,17 +361,20 @@ void TrackerListWidget::loadTrackers() const QHash trackerData = torrent->trackerInfos(); QStringList oldTrackerURLs = m_trackerItems.keys(); - for (const BitTorrent::TrackerEntry &entry : asConst(torrent->trackers())) { + for (const BitTorrent::TrackerEntry &entry : asConst(torrent->trackers())) + { const QString trackerURL = entry.url(); QTreeWidgetItem *item = m_trackerItems.value(trackerURL, nullptr); - if (!item) { + if (!item) + { item = new QTreeWidgetItem(); item->setText(COL_URL, trackerURL); addTopLevelItem(item); m_trackerItems[trackerURL] = item; } - else { + else + { oldTrackerURLs.removeOne(trackerURL); } @@ -365,7 +382,8 @@ void TrackerListWidget::loadTrackers() const BitTorrent::TrackerInfo data = trackerData.value(trackerURL); - switch (entry.status()) { + switch (entry.status()) + { case BitTorrent::TrackerEntry::Working: item->setText(COL_STATUS, tr("Working")); item->setText(COL_MSG, ""); @@ -427,7 +445,8 @@ void TrackerListWidget::copyTrackerUrl() if (selectedTrackerItems.isEmpty()) return; QStringList urlsToCopy; - for (const QTreeWidgetItem *item : selectedTrackerItems) { + for (const QTreeWidgetItem *item : selectedTrackerItems) + { QString trackerURL = item->data(COL_URL, Qt::DisplayRole).toString(); qDebug() << QString("Copy: ") + trackerURL; urlsToCopy << trackerURL; @@ -439,7 +458,8 @@ void TrackerListWidget::copyTrackerUrl() void TrackerListWidget::deleteSelectedTrackers() { BitTorrent::TorrentHandle *const torrent = m_properties->getCurrentTorrent(); - if (!torrent) { + if (!torrent) + { clear(); return; } @@ -448,7 +468,8 @@ void TrackerListWidget::deleteSelectedTrackers() if (selectedTrackerItems.isEmpty()) return; QStringList urlsToRemove; - for (const QTreeWidgetItem *item : selectedTrackerItems) { + for (const QTreeWidgetItem *item : selectedTrackerItems) + { QString trackerURL = item->data(COL_URL, Qt::DisplayRole).toString(); urlsToRemove << trackerURL; m_trackerItems.remove(trackerURL); @@ -460,7 +481,8 @@ void TrackerListWidget::deleteSelectedTrackers() QVector remainingTrackers; remainingTrackers.reserve(trackers.size()); - for (const BitTorrent::TrackerEntry &entry : trackers) { + for (const BitTorrent::TrackerEntry &entry : trackers) + { if (!urlsToRemove.contains(entry.url())) remainingTrackers.push_back(entry); } @@ -487,7 +509,8 @@ void TrackerListWidget::editSelectedTracker() QLineEdit::Normal, trackerURL.toString(), &ok).trimmed(); if (!ok) return; - if (!newTrackerURL.isValid()) { + if (!newTrackerURL.isValid()) + { QMessageBox::warning(this, tr("Tracker editing failed"), tr("The tracker URL entered is invalid.")); return; } @@ -495,13 +518,16 @@ void TrackerListWidget::editSelectedTracker() QVector trackers = torrent->trackers(); bool match = false; - for (BitTorrent::TrackerEntry &entry : trackers) { - if (newTrackerURL == QUrl(entry.url())) { + for (BitTorrent::TrackerEntry &entry : trackers) + { + if (newTrackerURL == QUrl(entry.url())) + { QMessageBox::warning(this, tr("Tracker editing failed"), tr("The tracker URL already exists.")); return; } - if (!match && (trackerURL == QUrl(entry.url()))) { + if (!match && (trackerURL == QUrl(entry.url()))) + { match = true; BitTorrent::TrackerEntry newEntry(newTrackerURL.toString()); newEntry.setTier(entry.tier()); @@ -525,16 +551,20 @@ void TrackerListWidget::reannounceSelected() const QVector trackers = torrent->trackers(); - for (const QTreeWidgetItem *item : selItems) { + for (const QTreeWidgetItem *item : selItems) + { // DHT case - if (item == m_DHTItem) { + if (item == m_DHTItem) + { torrent->forceDHTAnnounce(); continue; } // Trackers case - for (int i = 0; i < trackers.size(); ++i) { - if (item->text(COL_URL) == trackers[i].url()) { + for (int i = 0; i < trackers.size(); ++i) + { + if (item->text(COL_URL) == trackers[i].url()) + { torrent->forceReannounce(i); break; } @@ -556,7 +586,8 @@ void TrackerListWidget::showTrackerListMenu(const QPoint &) const QAction *addAct = menu->addAction(UIThemeManager::instance()->getIcon("list-add"), tr("Add a new tracker...")); connect(addAct, &QAction::triggered, this, &TrackerListWidget::askForTrackers); - if (!getSelectedTrackerItems().isEmpty()) { + if (!getSelectedTrackerItems().isEmpty()) + { const QAction *editAct = menu->addAction(UIThemeManager::instance()->getIcon("edit-rename"),tr("Edit tracker URL...")); connect(editAct, &QAction::triggered, this, &TrackerListWidget::editSelectedTracker); @@ -567,7 +598,8 @@ void TrackerListWidget::showTrackerListMenu(const QPoint &) connect(copyAct, &QAction::triggered, this, &TrackerListWidget::copyTrackerUrl); } - if (!torrent->isPaused()) { + if (!torrent->isPaused()) + { const QAction *reannounceSelAct = menu->addAction(UIThemeManager::instance()->getIcon("view-refresh"), tr("Force reannounce to selected trackers")); connect(reannounceSelAct, &QAction::triggered, this, &TrackerListWidget::reannounceSelected); @@ -597,7 +629,8 @@ void TrackerListWidget::saveSettings() const QStringList TrackerListWidget::headerLabels() { - return { + return + { tr("Tier") , tr("URL") , tr("Status") @@ -612,7 +645,8 @@ QStringList TrackerListWidget::headerLabels() int TrackerListWidget::visibleColumnsCount() const { int visibleCols = 0; - for (int i = 0; i < COL_COUNT; ++i) { + for (int i = 0; i < COL_COUNT; ++i) + { if (!isColumnHidden(i)) ++visibleCols; } @@ -626,7 +660,8 @@ void TrackerListWidget::displayToggleColumnsMenu(const QPoint &) menu->setAttribute(Qt::WA_DeleteOnClose); menu->setTitle(tr("Column visibility")); - for (int i = 0; i < COL_COUNT; ++i) { + for (int i = 0; i < COL_COUNT; ++i) + { QAction *myAct = menu->addAction(headerLabels().at(i)); myAct->setCheckable(true); myAct->setChecked(!isColumnHidden(i)); diff --git a/src/gui/properties/trackersadditiondialog.cpp b/src/gui/properties/trackersadditiondialog.cpp index 33c3e1e38..6dbe8d48e 100644 --- a/src/gui/properties/trackersadditiondialog.cpp +++ b/src/gui/properties/trackersadditiondialog.cpp @@ -59,7 +59,8 @@ QStringList TrackersAdditionDialog::newTrackers() const const QString plainText = m_ui->textEditTrackersList->toPlainText(); QStringList cleanTrackers; - for (QStringRef url : asConst(plainText.splitRef('\n'))) { + for (QStringRef url : asConst(plainText.splitRef('\n'))) + { url = url.trimmed(); if (!url.isEmpty()) cleanTrackers << url.toString(); @@ -78,7 +79,8 @@ void TrackersAdditionDialog::on_uTorrentListButton_clicked() void TrackersAdditionDialog::torrentListDownloadFinished(const Net::DownloadResult &result) { - if (result.status != Net::DownloadStatus::Success) { + if (result.status != Net::DownloadStatus::Success) + { // To restore the cursor ... setCursor(Qt::ArrowCursor); m_ui->uTorrentListButton->setEnabled(true); @@ -92,7 +94,8 @@ void TrackersAdditionDialog::torrentListDownloadFinished(const Net::DownloadResu const QStringList trackersFromUser = m_ui->textEditTrackersList->toPlainText().split('\n'); QVector existingTrackers = m_torrent->trackers(); existingTrackers.reserve(trackersFromUser.size()); - for (const QString &userURL : trackersFromUser) { + for (const QString &userURL : trackersFromUser) + { const BitTorrent::TrackerEntry userTracker(userURL); if (!existingTrackers.contains(userTracker)) existingTrackers << userTracker; @@ -105,12 +108,14 @@ void TrackersAdditionDialog::torrentListDownloadFinished(const Net::DownloadResu QBuffer buffer; buffer.setData(result.data); buffer.open(QBuffer::ReadOnly); - while (!buffer.atEnd()) { + while (!buffer.atEnd()) + { const QString line = buffer.readLine().trimmed(); if (line.isEmpty()) continue; BitTorrent::TrackerEntry newTracker(line); - if (!existingTrackers.contains(newTracker)) { + if (!existingTrackers.contains(newTracker)) + { m_ui->textEditTrackersList->insertPlainText(line + '\n'); ++nb; } diff --git a/src/gui/rss/articlelistwidget.cpp b/src/gui/rss/articlelistwidget.cpp index bf3c3b90d..bb43ee919 100644 --- a/src/gui/rss/articlelistwidget.cpp +++ b/src/gui/rss/articlelistwidget.cpp @@ -65,13 +65,16 @@ void ArticleListWidget::setRSSItem(RSS::Item *rssItem, bool unreadOnly) m_unreadOnly = unreadOnly; m_rssItem = rssItem; - if (m_rssItem) { + if (m_rssItem) + { connect(m_rssItem, &RSS::Item::newArticle, this, &ArticleListWidget::handleArticleAdded); connect(m_rssItem, &RSS::Item::articleRead, this, &ArticleListWidget::handleArticleRead); connect(m_rssItem, &RSS::Item::articleAboutToBeRemoved, this, &ArticleListWidget::handleArticleAboutToBeRemoved); - for (const auto article : asConst(rssItem->articles())) { - if (!(m_unreadOnly && article->isRead())) { + for (const auto article : asConst(rssItem->articles())) + { + if (!(m_unreadOnly && article->isRead())) + { auto item = createItem(article); addItem(item); m_rssArticleToListItemMapping.insert(article, item); @@ -84,7 +87,8 @@ void ArticleListWidget::setRSSItem(RSS::Item *rssItem, bool unreadOnly) void ArticleListWidget::handleArticleAdded(RSS::Article *rssArticle) { - if (!(m_unreadOnly && rssArticle->isRead())) { + if (!(m_unreadOnly && rssArticle->isRead())) + { auto item = createItem(rssArticle); insertItem(0, item); m_rssArticleToListItemMapping.insert(rssArticle, item); @@ -124,13 +128,15 @@ QListWidgetItem *ArticleListWidget::createItem(RSS::Article *article) const item->setData(Qt::DisplayRole, article->title()); item->setData(Qt::UserRole, reinterpret_cast(article)); - if (article->isRead()) { + if (article->isRead()) + { const QColor defaultColor {palette().color(QPalette::Inactive, QPalette::WindowText)}; const QBrush foregroundBrush {UIThemeManager::instance()->getColor("RSS.ReadArticle", defaultColor)}; item->setData(Qt::ForegroundRole, foregroundBrush); item->setData(Qt::DecorationRole, UIThemeManager::instance()->getIcon(QLatin1String("sphere"))); } - else { + else + { const QColor defaultColor {palette().color(QPalette::Active, QPalette::Link)}; const QBrush foregroundBrush {UIThemeManager::instance()->getColor("RSS.UnreadArticle", defaultColor)}; item->setData(Qt::ForegroundRole, foregroundBrush); diff --git a/src/gui/rss/automatedrssdownloader.cpp b/src/gui/rss/automatedrssdownloader.cpp index 846e2c85f..1e3eb6f2d 100644 --- a/src/gui/rss/automatedrssdownloader.cpp +++ b/src/gui/rss/automatedrssdownloader.cpp @@ -181,7 +181,8 @@ void AutomatedRssDownloader::loadFeedList() { const QSignalBlocker feedListSignalBlocker(m_ui->listFeeds); - for (const auto feed : asConst(RSS::Session::instance()->feeds())) { + for (const auto feed : asConst(RSS::Session::instance()->feeds())) + { QListWidgetItem *item = new QListWidgetItem(feed->name(), m_ui->listFeeds); item->setData(Qt::UserRole, feed->url()); item->setFlags(item->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsTristate); @@ -203,7 +204,8 @@ void AutomatedRssDownloader::updateFeedList() bool enable = !selection.isEmpty(); - for (int i = 0; i < m_ui->listFeeds->count(); ++i) { + for (int i = 0; i < m_ui->listFeeds->count(); ++i) + { QListWidgetItem *item = m_ui->listFeeds->item(i); const QString feedURL = item->data(Qt::UserRole).toString(); item->setHidden(!enable); @@ -211,7 +213,8 @@ void AutomatedRssDownloader::updateFeedList() bool allEnabled = true; bool anyEnabled = false; - for (const QListWidgetItem *ruleItem : asConst(selection)) { + for (const QListWidgetItem *ruleItem : asConst(selection)) + { const auto rule = RSS::AutoDownloader::instance()->ruleByName(ruleItem->text()); if (rule.feedURLs().contains(feedURL)) anyEnabled = true; @@ -236,14 +239,16 @@ void AutomatedRssDownloader::updateRuleDefinitionBox() { const QList selection = m_ui->listRules->selectedItems(); QListWidgetItem *currentRuleItem = ((selection.count() == 1) ? selection.first() : nullptr); - if (m_currentRuleItem != currentRuleItem) { + if (m_currentRuleItem != currentRuleItem) + { saveEditedRule(); // Save previous rule first m_currentRuleItem = currentRuleItem; //m_ui->listRules->setCurrentItem(m_currentRuleItem); } // Update rule definition box - if (m_currentRuleItem) { + if (m_currentRuleItem) + { m_currentRule = RSS::AutoDownloader::instance()->ruleByName(m_currentRuleItem->text()); m_ui->lineContains->setText(m_currentRule.mustContain()); @@ -290,7 +295,8 @@ void AutomatedRssDownloader::updateRuleDefinitionBox() updateFieldsToolTips(m_ui->checkRegex->isChecked()); m_ui->ruleDefBox->setEnabled(true); } - else { + else + { m_currentRule = RSS::AutoDownloadRule(); clearRuleDefinitionBox(); m_ui->ruleDefBox->setEnabled(false); @@ -376,7 +382,8 @@ void AutomatedRssDownloader::on_addRuleBtn_clicked() if (ruleName.isEmpty()) return; // Check if this rule name already exists - if (RSS::AutoDownloader::instance()->hasRule(ruleName)) { + if (RSS::AutoDownloader::instance()->hasRule(ruleName)) + { QMessageBox::warning(this, tr("Rule name conflict") , tr("A rule with this name already exists, please choose another name.")); return; @@ -404,7 +411,8 @@ void AutomatedRssDownloader::on_removeRuleBtn_clicked() void AutomatedRssDownloader::on_exportBtn_clicked() { - if (RSS::AutoDownloader::instance()->rules().isEmpty()) { + if (RSS::AutoDownloader::instance()->rules().isEmpty()) + { QMessageBox::warning(this, tr("Invalid action") , tr("The list is empty, there is nothing to export.")); return; @@ -416,24 +424,28 @@ void AutomatedRssDownloader::on_exportBtn_clicked() , QString::fromLatin1("%1;;%2").arg(m_formatFilterJSON, m_formatFilterLegacy), &selectedFilter); if (path.isEmpty()) return; - const RSS::AutoDownloader::RulesFileFormat format { + const RSS::AutoDownloader::RulesFileFormat format + { (selectedFilter == m_formatFilterJSON) ? RSS::AutoDownloader::RulesFileFormat::JSON : RSS::AutoDownloader::RulesFileFormat::Legacy }; - if (format == RSS::AutoDownloader::RulesFileFormat::JSON) { + if (format == RSS::AutoDownloader::RulesFileFormat::JSON) + { if (!path.endsWith(EXT_JSON, Qt::CaseInsensitive)) path += EXT_JSON; } - else { + else + { if (!path.endsWith(EXT_LEGACY, Qt::CaseInsensitive)) path += EXT_LEGACY; } QFile file {path}; if (!file.open(QFile::WriteOnly) - || (file.write(RSS::AutoDownloader::instance()->exportRules(format)) == -1)) { + || (file.write(RSS::AutoDownloader::instance()->exportRules(format)) == -1)) + { QMessageBox::critical( this, tr("I/O Error") , tr("Failed to create the destination file. Reason: %1").arg(file.errorString())); @@ -450,23 +462,27 @@ void AutomatedRssDownloader::on_importBtn_clicked() return; QFile file {path}; - if (!file.open(QIODevice::ReadOnly)) { + if (!file.open(QIODevice::ReadOnly)) + { QMessageBox::critical( this, tr("I/O Error") , tr("Failed to open the file. Reason: %1").arg(file.errorString())); return; } - const RSS::AutoDownloader::RulesFileFormat format { + const RSS::AutoDownloader::RulesFileFormat format + { (selectedFilter == m_formatFilterJSON) ? RSS::AutoDownloader::RulesFileFormat::JSON : RSS::AutoDownloader::RulesFileFormat::Legacy }; - try { + try + { RSS::AutoDownloader::instance()->importRules(file.readAll(),format); } - catch (const RSS::ParsingError &error) { + catch (const RSS::ParsingError &error) + { QMessageBox::critical( this, tr("Import Error") , tr("Failed to import the selected rules file. Reason: %1").arg(error.message())); @@ -483,8 +499,10 @@ void AutomatedRssDownloader::displayRulesListMenu() const QList selection = m_ui->listRules->selectedItems(); - if (!selection.isEmpty()) { - if (selection.count() == 1) { + if (!selection.isEmpty()) + { + if (selection.count() == 1) + { const QAction *delAct = menu->addAction(UIThemeManager::instance()->getIcon("list-remove"), tr("Delete rule")); connect(delAct, &QAction::triggered, this, &AutomatedRssDownloader::on_removeRuleBtn_clicked); @@ -493,7 +511,8 @@ void AutomatedRssDownloader::displayRulesListMenu() const QAction *renameAct = menu->addAction(UIThemeManager::instance()->getIcon("edit-rename"), tr("Rename rule...")); connect(renameAct, &QAction::triggered, this, &AutomatedRssDownloader::renameSelectedRule); } - else { + else + { const QAction *delAct = menu->addAction(UIThemeManager::instance()->getIcon("list-remove"), tr("Delete selected rules")); connect(delAct, &QAction::triggered, this, &AutomatedRssDownloader::on_removeRuleBtn_clicked); } @@ -513,18 +532,21 @@ void AutomatedRssDownloader::renameSelectedRule() if (selection.isEmpty()) return; QListWidgetItem *item = selection.first(); - forever { + forever + { QString newName = AutoExpandableDialog::getText( this, tr("Rule renaming"), tr("Please type the new rule name") , QLineEdit::Normal, item->text()); newName = newName.trimmed(); if (newName.isEmpty()) return; - if (RSS::AutoDownloader::instance()->hasRule(newName)) { + if (RSS::AutoDownloader::instance()->hasRule(newName)) + { QMessageBox::warning(this, tr("Rule name conflict") , tr("A rule with this name already exists, please choose another name.")); } - else { + else + { // Rename the rule RSS::AutoDownloader::instance()->renameRule(item->text(), newName); return; @@ -545,7 +567,8 @@ void AutomatedRssDownloader::clearSelectedRuleDownloadedEpisodeList() tr("Are you sure you want to clear the list of downloaded episodes for the selected rule?"), QMessageBox::Yes | QMessageBox::No); - if (reply == QMessageBox::Yes) { + if (reply == QMessageBox::Yes) + { m_currentRule.setPreviouslyMatchedEpisodes(QStringList()); handleRuleDefinitionChanged(); } @@ -554,7 +577,8 @@ void AutomatedRssDownloader::clearSelectedRuleDownloadedEpisodeList() void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feedItem) { const QString feedURL = feedItem->data(Qt::UserRole).toString(); - for (QListWidgetItem *ruleItem : asConst(m_ui->listRules->selectedItems())) { + for (QListWidgetItem *ruleItem : asConst(m_ui->listRules->selectedItems())) + { RSS::AutoDownloadRule rule = (ruleItem == m_currentRuleItem ? m_currentRule : RSS::AutoDownloader::instance()->ruleByName(ruleItem->text())); @@ -578,11 +602,13 @@ void AutomatedRssDownloader::updateMatchingArticles() { m_ui->treeMatchingArticles->clear(); - for (const QListWidgetItem *ruleItem : asConst(m_ui->listRules->selectedItems())) { + for (const QListWidgetItem *ruleItem : asConst(m_ui->listRules->selectedItems())) + { RSS::AutoDownloadRule rule = (ruleItem == m_currentRuleItem ? m_currentRule : RSS::AutoDownloader::instance()->ruleByName(ruleItem->text())); - for (const QString &feedURL : asConst(rule.feedURLs())) { + for (const QString &feedURL : asConst(rule.feedURLs())) + { auto feed = RSS::Session::instance()->feedByURL(feedURL); if (!feed) continue; // feed doesn't exist @@ -605,16 +631,19 @@ void AutomatedRssDownloader::addFeedArticlesToTree(RSS::Feed *feed, const QStrin // Check if this feed is already in the tree QTreeWidgetItem *treeFeedItem = nullptr; - for (int i = 0; i < m_ui->treeMatchingArticles->topLevelItemCount(); ++i) { + for (int i = 0; i < m_ui->treeMatchingArticles->topLevelItemCount(); ++i) + { QTreeWidgetItem *item = m_ui->treeMatchingArticles->topLevelItem(i); - if (item->data(0, Qt::UserRole).toString() == feed->url()) { + if (item->data(0, Qt::UserRole).toString() == feed->url()) + { treeFeedItem = item; break; } } // If there is none, create it - if (!treeFeedItem) { + if (!treeFeedItem) + { treeFeedItem = new QTreeWidgetItem(QStringList() << feed->name()); treeFeedItem->setToolTip(0, feed->name()); QFont f = treeFeedItem->font(0); @@ -626,10 +655,12 @@ void AutomatedRssDownloader::addFeedArticlesToTree(RSS::Feed *feed, const QStrin } // Insert the articles - for (const QString &article : articles) { + for (const QString &article : articles) + { QPair key(feed->name(), article); - if (!m_treeListEntries.contains(key)) { + if (!m_treeListEntries.contains(key)) + { m_treeListEntries << key; QTreeWidgetItem *item = new QTreeWidgetItem(QStringList() << article); item->setToolTip(0, article); @@ -645,10 +676,12 @@ void AutomatedRssDownloader::addFeedArticlesToTree(RSS::Feed *feed, const QStrin void AutomatedRssDownloader::updateFieldsToolTips(bool regex) { QString tip; - if (regex) { + if (regex) + { tip = "

" + tr("Regex mode: use Perl-compatible regular expressions") + "

"; } - else { + else + { tip = "

" + tr("Wildcard mode: you can use") + "

    " + "
  • " + tr("? to match any single character") + "
  • " + "
  • " + tr("* to match zero or more of any characters") + "
  • " @@ -676,7 +709,8 @@ void AutomatedRssDownloader::updateMustLineValidity() bool valid = true; QString error; - if (!text.isEmpty()) { + if (!text.isEmpty()) + { QStringList tokens; if (isRegex) tokens << text; @@ -684,9 +718,11 @@ void AutomatedRssDownloader::updateMustLineValidity() for (const QString &token : asConst(text.split('|'))) tokens << Utils::String::wildcardToRegex(token); - for (const QString &token : asConst(tokens)) { + for (const QString &token : asConst(tokens)) + { QRegularExpression reg(token, QRegularExpression::CaseInsensitiveOption); - if (!reg.isValid()) { + if (!reg.isValid()) + { if (isRegex) error = tr("Position %1: %2").arg(reg.patternErrorOffset()).arg(reg.errorString()); valid = false; @@ -695,12 +731,14 @@ void AutomatedRssDownloader::updateMustLineValidity() } } - if (valid) { + if (valid) + { m_ui->lineContains->setStyleSheet(""); m_ui->labelMustStat->setPixmap(QPixmap()); m_ui->labelMustStat->setToolTip(""); } - else { + else + { m_ui->lineContains->setStyleSheet("QLineEdit { color: #ff0000; }"); m_ui->labelMustStat->setPixmap(UIThemeManager::instance()->getIcon("task-attention").pixmap(16, 16)); m_ui->labelMustStat->setToolTip(error); @@ -714,7 +752,8 @@ void AutomatedRssDownloader::updateMustNotLineValidity() bool valid = true; QString error; - if (!text.isEmpty()) { + if (!text.isEmpty()) + { QStringList tokens; if (isRegex) tokens << text; @@ -722,9 +761,11 @@ void AutomatedRssDownloader::updateMustNotLineValidity() for (const QString &token : asConst(text.split('|'))) tokens << Utils::String::wildcardToRegex(token); - for (const QString &token : asConst(tokens)) { + for (const QString &token : asConst(tokens)) + { QRegularExpression reg(token, QRegularExpression::CaseInsensitiveOption); - if (!reg.isValid()) { + if (!reg.isValid()) + { if (isRegex) error = tr("Position %1: %2").arg(reg.patternErrorOffset()).arg(reg.errorString()); valid = false; @@ -733,12 +774,14 @@ void AutomatedRssDownloader::updateMustNotLineValidity() } } - if (valid) { + if (valid) + { m_ui->lineNotContains->setStyleSheet(""); m_ui->labelMustNotStat->setPixmap(QPixmap()); m_ui->labelMustNotStat->setToolTip(""); } - else { + else + { m_ui->lineNotContains->setStyleSheet("QLineEdit { color: #ff0000; }"); m_ui->labelMustNotStat->setPixmap(UIThemeManager::instance()->getIcon("task-attention").pixmap(16, 16)); m_ui->labelMustNotStat->setToolTip(error); @@ -750,11 +793,13 @@ void AutomatedRssDownloader::updateEpisodeFilterValidity() const QString text = m_ui->lineEFilter->text(); bool valid = text.isEmpty() || m_episodeRegex->match(text).hasMatch(); - if (valid) { + if (valid) + { m_ui->lineEFilter->setStyleSheet(""); m_ui->labelEpFilterStat->setPixmap(QPixmap()); } - else { + else + { m_ui->lineEFilter->setStyleSheet("QLineEdit { color: #ff0000; }"); m_ui->labelEpFilterStat->setPixmap(UIThemeManager::instance()->getIcon("task-attention").pixmap(16, 16)); } diff --git a/src/gui/rss/feedlistwidget.cpp b/src/gui/rss/feedlistwidget.cpp index beb287eca..137b54096 100644 --- a/src/gui/rss/feedlistwidget.cpp +++ b/src/gui/rss/feedlistwidget.cpp @@ -97,7 +97,8 @@ void FeedListWidget::handleFeedStateChanged(RSS::Feed *feed) void FeedListWidget::handleFeedIconLoaded(RSS::Feed *feed) { - if (!feed->isLoading() && !feed->hasError()) { + if (!feed->isLoading() && !feed->hasError()) + { QTreeWidgetItem *item = m_rssToTreeItemMapping.value(feed); Q_ASSERT(item); @@ -107,10 +108,12 @@ void FeedListWidget::handleFeedIconLoaded(RSS::Feed *feed) void FeedListWidget::handleItemUnreadCountChanged(RSS::Item *rssItem) { - if (rssItem == RSS::Session::instance()->rootFolder()) { + if (rssItem == RSS::Session::instance()->rootFolder()) + { m_unreadStickyItem->setText(0, tr("Unread (%1)").arg(RSS::Session::instance()->rootFolder()->unreadCount())); } - else { + else + { QTreeWidgetItem *item = mapRSSItem(rssItem); Q_ASSERT(item); item->setData(0, Qt::DisplayRole, QString::fromLatin1("%1 (%2)").arg(rssItem->name(), QString::number(rssItem->unreadCount()))); @@ -151,9 +154,11 @@ QList FeedListWidget::getAllOpenedFolders(QTreeWidgetItem *pa { QList openedFolders; int nbChildren = (parent ? parent->childCount() : topLevelItemCount()); - for (int i = 0; i < nbChildren; ++i) { + for (int i = 0; i < nbChildren; ++i) + { QTreeWidgetItem *item (parent ? parent->child(i) : topLevelItem(i)); - if (isFolder(item) && item->isExpanded()) { + if (isFolder(item) && item->isExpanded()) + { QList openedSubfolders = getAllOpenedFolders(item); if (!openedSubfolders.empty()) openedFolders << openedSubfolders; @@ -215,7 +220,8 @@ void FeedListWidget::dropEvent(QDropEvent *event) : RSS::Session::instance()->rootFolder()); // move as much items as possible - for (QTreeWidgetItem *srcItem : asConst(selectedItems())) { + for (QTreeWidgetItem *srcItem : asConst(selectedItems())) + { auto rssItem = getRSSItem(srcItem); RSS::Session::instance()->moveItem(rssItem, RSS::Item::joinPath(destFolder->path(), rssItem->name())); } @@ -233,7 +239,8 @@ QTreeWidgetItem *FeedListWidget::createItem(RSS::Item *rssItem, QTreeWidgetItem m_rssToTreeItemMapping[rssItem] = item; QIcon icon; - if (auto feed = qobject_cast(rssItem)) { + if (auto feed = qobject_cast(rssItem)) + { if (feed->isLoading()) icon = UIThemeManager::instance()->getIcon(QLatin1String("loading")); else if (feed->hasError()) @@ -243,7 +250,8 @@ QTreeWidgetItem *FeedListWidget::createItem(RSS::Item *rssItem, QTreeWidgetItem else icon = UIThemeManager::instance()->getIcon(QLatin1String("application-rss+xml")); } - else { + else + { icon = UIThemeManager::instance()->getIcon(QLatin1String("inode-directory")); } item->setData(0, Qt::DecorationRole, icon); @@ -260,7 +268,8 @@ QTreeWidgetItem *FeedListWidget::createItem(RSS::Item *rssItem, QTreeWidgetItem void FeedListWidget::fill(QTreeWidgetItem *parent, RSS::Folder *rssParent) { - for (const auto rssItem : asConst(rssParent->items())) { + for (const auto rssItem : asConst(rssParent->items())) + { QTreeWidgetItem *item = createItem(rssItem, parent); // Recursive call if this is a folder. if (auto folder = qobject_cast(rssItem)) diff --git a/src/gui/rss/htmlbrowser.cpp b/src/gui/rss/htmlbrowser.cpp index 2db06509c..89dbbacd4 100644 --- a/src/gui/rss/htmlbrowser.cpp +++ b/src/gui/rss/htmlbrowser.cpp @@ -59,20 +59,23 @@ HtmlBrowser::~HtmlBrowser() QVariant HtmlBrowser::loadResource(int type, const QUrl &name) { - if (type == QTextDocument::ImageResource) { + if (type == QTextDocument::ImageResource) + { QUrl url(name); if (url.scheme().isEmpty()) url.setScheme("http"); QIODevice *dev = m_diskCache->data(url); - if (dev) { + if (dev) + { qDebug() << "HtmlBrowser::loadResource() cache " << url.toString(); QByteArray res = dev->readAll(); delete dev; return res; } - if (!m_activeRequests.contains(url)) { + if (!m_activeRequests.contains(url)) + { m_activeRequests.insert(url, true); qDebug() << "HtmlBrowser::loadResource() get " << url.toString(); QNetworkRequest req(url); @@ -90,10 +93,12 @@ void HtmlBrowser::resourceLoaded(QNetworkReply *reply) { m_activeRequests.remove(reply->request().url()); - if ((reply->error() == QNetworkReply::NoError) && (reply->size() > 0)) { + if ((reply->error() == QNetworkReply::NoError) && (reply->size() > 0)) + { qDebug() << "HtmlBrowser::resourceLoaded() save " << reply->request().url().toString(); } - else { + else + { // If resource failed to load, replace it with warning icon and store it in cache for 1 day. // Otherwise HTMLBrowser will keep trying to download it every time article is displayed, // since it's not possible to cache error responses. diff --git a/src/gui/rss/rsswidget.cpp b/src/gui/rss/rsswidget.cpp index c945906dc..ff085c38f 100644 --- a/src/gui/rss/rsswidget.cpp +++ b/src/gui/rss/rsswidget.cpp @@ -150,13 +150,16 @@ void RSSWidget::displayRSSListMenu(const QPoint &pos) menu->setAttribute(Qt::WA_DeleteOnClose); const QList selectedItems = m_feedListWidget->selectedItems(); - if (!selectedItems.isEmpty()) { + if (!selectedItems.isEmpty()) + { menu->addAction(m_ui->actionUpdate); menu->addAction(m_ui->actionMarkItemsRead); menu->addSeparator(); - if (selectedItems.size() == 1) { - if (selectedItems.first() != m_feedListWidget->stickyUnreadItem()) { + if (selectedItems.size() == 1) + { + if (selectedItems.first() != m_feedListWidget->stickyUnreadItem()) + { menu->addAction(m_ui->actionRename); menu->addAction(m_ui->actionDelete); menu->addSeparator(); @@ -164,19 +167,22 @@ void RSSWidget::displayRSSListMenu(const QPoint &pos) menu->addAction(m_ui->actionNewFolder); } } - else { + else + { menu->addAction(m_ui->actionDelete); menu->addSeparator(); } menu->addAction(m_ui->actionNewSubscription); - if (m_feedListWidget->isFeed(selectedItems.first())) { + if (m_feedListWidget->isFeed(selectedItems.first())) + { menu->addSeparator(); menu->addAction(m_ui->actionCopyFeedURL); } } - else { + else + { menu->addAction(m_ui->actionNewSubscription); menu->addAction(m_ui->actionNewFolder); menu->addSeparator(); @@ -190,7 +196,8 @@ void RSSWidget::displayItemsListMenu(const QPoint &) { bool hasTorrent = false; bool hasLink = false; - for (const QListWidgetItem *item : asConst(m_articleListWidget->selectedItems())) { + for (const QListWidgetItem *item : asConst(m_articleListWidget->selectedItems())) + { auto article = reinterpret_cast(item->data(Qt::UserRole).value()); Q_ASSERT(article); @@ -228,7 +235,8 @@ void RSSWidget::askNewFolder() // Determine destination folder for new item QTreeWidgetItem *destItem = nullptr; QList selectedItems = m_feedListWidget->selectedItems(); - if (!selectedItems.empty()) { + if (!selectedItems.empty()) + { destItem = selectedItems.first(); if (!m_feedListWidget->isFolder(destItem)) destItem = destItem->parent(); @@ -268,7 +276,8 @@ void RSSWidget::on_newFeedButton_clicked() // Determine destination folder for new item QTreeWidgetItem *destItem = nullptr; QList selectedItems = m_feedListWidget->selectedItems(); - if (!selectedItems.empty()) { + if (!selectedItems.empty()) + { destItem = selectedItems.first(); if (!m_feedListWidget->isFolder(destItem)) destItem = destItem->parent(); @@ -313,13 +322,17 @@ void RSSWidget::deleteSelectedItems() void RSSWidget::loadFoldersOpenState() { const QStringList openedFolders = Preferences::instance()->getRssOpenFolders(); - for (const QString &varPath : openedFolders) { + for (const QString &varPath : openedFolders) + { QTreeWidgetItem *parent = nullptr; - for (const QString &name : asConst(varPath.split('\\'))) { + for (const QString &name : asConst(varPath.split('\\'))) + { int nbChildren = (parent ? parent->childCount() : m_feedListWidget->topLevelItemCount()); - for (int i = 0; i < nbChildren; ++i) { + for (int i = 0; i < nbChildren; ++i) + { QTreeWidgetItem *child = (parent ? parent->child(i) : m_feedListWidget->topLevelItem(i)); - if (m_feedListWidget->getRSSItem(child)->name() == name) { + if (m_feedListWidget->getRSSItem(child)->name() == name) + { parent = child; parent->setExpanded(true); break; @@ -344,14 +357,16 @@ void RSSWidget::refreshAllFeeds() void RSSWidget::downloadSelectedTorrents() { - for (QListWidgetItem *item : asConst(m_articleListWidget->selectedItems())) { + for (QListWidgetItem *item : asConst(m_articleListWidget->selectedItems())) + { auto article = reinterpret_cast(item->data(Qt::UserRole).value()); Q_ASSERT(article); // Mark as read article->markAsRead(); - if (!article->torrentUrl().isEmpty()) { + if (!article->torrentUrl().isEmpty()) + { if (AddNewTorrentDialog::isEnabled()) AddNewTorrentDialog::show(article->torrentUrl(), window()); else @@ -363,7 +378,8 @@ void RSSWidget::downloadSelectedTorrents() // open the url of the selected RSS articles in the Web browser void RSSWidget::openSelectedArticlesUrls() { - for (QListWidgetItem *item : asConst(m_articleListWidget->selectedItems())) { + for (QListWidgetItem *item : asConst(m_articleListWidget->selectedItems())) + { auto article = reinterpret_cast(item->data(Qt::UserRole).value()); Q_ASSERT(article); @@ -387,7 +403,8 @@ void RSSWidget::renameSelectedRSSItem() RSS::Item *rssItem = m_feedListWidget->getRSSItem(item); const QString parentPath = RSS::Item::parentPath(rssItem->path()); bool ok = false; - do { + do + { QString newName = AutoExpandableDialog::getText( this, tr("Please choose a new name for this RSS feed"), tr("New feed name:") , QLineEdit::Normal, rssItem->name(), &ok); @@ -395,7 +412,8 @@ void RSSWidget::renameSelectedRSSItem() if (!ok) return; QString error; - if (!RSS::Session::instance()->moveItem(rssItem, RSS::Item::joinPath(parentPath, newName), &error)) { + if (!RSS::Session::instance()->moveItem(rssItem, RSS::Item::joinPath(parentPath, newName), &error)) + { QMessageBox::warning(nullptr, tr("Rename failed"), error); ok = false; } @@ -404,8 +422,10 @@ void RSSWidget::renameSelectedRSSItem() void RSSWidget::refreshSelectedItems() { - for (QTreeWidgetItem *item : asConst(m_feedListWidget->selectedItems())) { - if (item == m_feedListWidget->stickyUnreadItem()) { + for (QTreeWidgetItem *item : asConst(m_feedListWidget->selectedItems())) + { + if (item == m_feedListWidget->stickyUnreadItem()) + { refreshAllFeeds(); return; } @@ -417,7 +437,8 @@ void RSSWidget::refreshSelectedItems() void RSSWidget::copySelectedFeedsURL() { QStringList URLs; - for (QTreeWidgetItem *item : asConst(m_feedListWidget->selectedItems())) { + for (QTreeWidgetItem *item : asConst(m_feedListWidget->selectedItems())) + { if (auto feed = qobject_cast(m_feedListWidget->getRSSItem(item))) URLs << feed->url(); } @@ -432,7 +453,8 @@ void RSSWidget::handleCurrentFeedItemChanged(QTreeWidgetItem *currentItem) void RSSWidget::on_markReadButton_clicked() { - for (QTreeWidgetItem *item : asConst(m_feedListWidget->selectedItems())) { + for (QTreeWidgetItem *item : asConst(m_feedListWidget->selectedItems())) + { m_feedListWidget->getRSSItem(item)->markAsRead(); if (item == m_feedListWidget->stickyUnreadItem()) break; // all items was read @@ -444,7 +466,8 @@ void RSSWidget::handleCurrentArticleItemChanged(QListWidgetItem *currentItem, QL { m_ui->textBrowser->clear(); - if (previousItem) { + if (previousItem) + { auto article = m_articleListWidget->getRSSArticle(previousItem); Q_ASSERT(article); article->markAsRead(); @@ -468,10 +491,12 @@ void RSSWidget::handleCurrentArticleItemChanged(QListWidgetItem *currentItem, QL html += QString::fromLatin1("
    %2%3
    ").arg(alternateBaseColor, tr("Author: "), article->author()); html += "" "
    "; - if (Qt::mightBeRichText(article->description())) { + if (Qt::mightBeRichText(article->description())) + { html += article->description(); } - else { + else + { QString description = article->description(); QRegularExpression rx; // If description is plain text, replace BBCode tags with HTML and wrap everything in
     so it looks nice
    diff --git a/src/gui/scanfoldersdelegate.cpp b/src/gui/scanfoldersdelegate.cpp
    index 01e96d751..ec1a7fe45 100644
    --- a/src/gui/scanfoldersdelegate.cpp
    +++ b/src/gui/scanfoldersdelegate.cpp
    @@ -62,7 +62,8 @@ QWidget *ScanFoldersDelegate::createEditor(QWidget *parent, const QStyleOptionVi
         editor->addItem(ScanFoldersModel::pathTypeDisplayName(ScanFoldersModel::DOWNLOAD_IN_WATCH_FOLDER));
         editor->addItem(ScanFoldersModel::pathTypeDisplayName(ScanFoldersModel::DEFAULT_LOCATION));
         editor->addItem(ScanFoldersModel::pathTypeDisplayName(ScanFoldersModel::CUSTOM_LOCATION));
    -    if (index.data(Qt::UserRole).toInt() == ScanFoldersModel::CUSTOM_LOCATION) {
    +    if (index.data(Qt::UserRole).toInt() == ScanFoldersModel::CUSTOM_LOCATION)
    +    {
             editor->insertSeparator(3);
             editor->addItem(index.data().toString());
         }
    @@ -74,7 +75,8 @@ QWidget *ScanFoldersDelegate::createEditor(QWidget *parent, const QStyleOptionVi
     
     void ScanFoldersDelegate::comboboxIndexChanged(int index)
     {
    -    if (index == ScanFoldersModel::CUSTOM_LOCATION) {
    +    if (index == ScanFoldersModel::CUSTOM_LOCATION)
    +    {
             auto *w = static_cast(sender());
             if (w && w->parentWidget())
                 w->parentWidget()->setFocus();
    @@ -86,7 +88,8 @@ void ScanFoldersDelegate::setModelData(QWidget *editor, QAbstractItemModel *mode
         auto *combobox = static_cast(editor);
         int value = combobox->currentIndex();
     
    -    switch (value) {
    +    switch (value)
    +    {
         case ScanFoldersModel::DOWNLOAD_IN_WATCH_FOLDER:
         case ScanFoldersModel::DEFAULT_LOCATION:
             model->setData(index, value, Qt::UserRole);
    diff --git a/src/gui/search/pluginselectdialog.cpp b/src/gui/search/pluginselectdialog.cpp
    index 4af236c44..966300e6c 100644
    --- a/src/gui/search/pluginselectdialog.cpp
    +++ b/src/gui/search/pluginselectdialog.cpp
    @@ -108,9 +108,12 @@ void PluginSelectDialog::dropEvent(QDropEvent *event)
         event->acceptProposedAction();
     
         QStringList files;
    -    if (event->mimeData()->hasUrls()) {
    -        for (const QUrl &url : asConst(event->mimeData()->urls())) {
    -            if (!url.isEmpty()) {
    +    if (event->mimeData()->hasUrls())
    +    {
    +        for (const QUrl &url : asConst(event->mimeData()->urls()))
    +        {
    +            if (!url.isEmpty())
    +            {
                     if (url.scheme().compare("file", Qt::CaseInsensitive) == 0)
                         files << url.toLocalFile();
                     else
    @@ -118,13 +121,15 @@ void PluginSelectDialog::dropEvent(QDropEvent *event)
                 }
             }
         }
    -    else {
    +    else
    +    {
             files = event->mimeData()->text().split('\n');
         }
     
         if (files.isEmpty()) return;
     
    -    for (const QString &file : asConst(files)) {
    +    for (const QString &file : asConst(files))
    +    {
             qDebug("dropped %s", qUtf8Printable(file));
             startAsyncOp();
             m_pluginManager->installPlugin(file);
    @@ -134,11 +139,13 @@ void PluginSelectDialog::dropEvent(QDropEvent *event)
     // Decode if we accept drag 'n drop or not
     void PluginSelectDialog::dragEnterEvent(QDragEnterEvent *event)
     {
    -    for (const QString &mime : asConst(event->mimeData()->formats())) {
    +    for (const QString &mime : asConst(event->mimeData()->formats()))
    +    {
             qDebug("mimeData: %s", qUtf8Printable(mime));
         }
     
    -    if (event->mimeData()->hasFormat(QLatin1String("text/plain")) || event->mimeData()->hasFormat(QLatin1String("text/uri-list"))) {
    +    if (event->mimeData()->hasFormat(QLatin1String("text/plain")) || event->mimeData()->hasFormat(QLatin1String("text/uri-list")))
    +    {
             event->acceptProposedAction();
         }
     }
    @@ -153,11 +160,13 @@ void PluginSelectDialog::togglePluginState(QTreeWidgetItem *item, int)
     {
         PluginInfo *plugin = m_pluginManager->pluginInfo(item->text(PLUGIN_ID));
         m_pluginManager->enablePlugin(plugin->name, !plugin->enabled);
    -    if (plugin->enabled) {
    +    if (plugin->enabled)
    +    {
             item->setText(PLUGIN_STATE, tr("Yes"));
             setRowColor(m_ui->pluginsTree->indexOfTopLevelItem(item), "green");
         }
    -    else {
    +    else
    +    {
             item->setText(PLUGIN_STATE, tr("No"));
             setRowColor(m_ui->pluginsTree->indexOfTopLevelItem(item), "red");
         }
    @@ -189,14 +198,17 @@ void PluginSelectDialog::on_closeButton_clicked()
     void PluginSelectDialog::on_actionUninstall_triggered()
     {
         bool error = false;
    -    for (QTreeWidgetItem *item : asConst(m_ui->pluginsTree->selectedItems())) {
    +    for (QTreeWidgetItem *item : asConst(m_ui->pluginsTree->selectedItems()))
    +    {
             int index = m_ui->pluginsTree->indexOfTopLevelItem(item);
             Q_ASSERT(index != -1);
             QString id = item->text(PLUGIN_ID);
    -        if (m_pluginManager->uninstallPlugin(id)) {
    +        if (m_pluginManager->uninstallPlugin(id))
    +        {
                 delete item;
             }
    -        else {
    +        else
    +        {
                 error = true;
                 // Disable it instead
                 m_pluginManager->enablePlugin(id, false);
    @@ -213,16 +225,19 @@ void PluginSelectDialog::on_actionUninstall_triggered()
     
     void PluginSelectDialog::enableSelection(bool enable)
     {
    -    for (QTreeWidgetItem *item : asConst(m_ui->pluginsTree->selectedItems())) {
    +    for (QTreeWidgetItem *item : asConst(m_ui->pluginsTree->selectedItems()))
    +    {
             int index = m_ui->pluginsTree->indexOfTopLevelItem(item);
             Q_ASSERT(index != -1);
             QString id = item->text(PLUGIN_ID);
             m_pluginManager->enablePlugin(id, enable);
    -        if (enable) {
    +        if (enable)
    +        {
                 item->setText(PLUGIN_STATE, tr("Yes"));
                 setRowColor(index, "green");
             }
    -        else {
    +        else
    +        {
                 item->setText(PLUGIN_STATE, tr("No"));
                 setRowColor(index, "red");
             }
    @@ -233,7 +248,8 @@ void PluginSelectDialog::enableSelection(bool enable)
     void PluginSelectDialog::setRowColor(const int row, const QString &color)
     {
         QTreeWidgetItem *item = m_ui->pluginsTree->topLevelItem(row);
    -    for (int i = 0; i < m_ui->pluginsTree->columnCount(); ++i) {
    +    for (int i = 0; i < m_ui->pluginsTree->columnCount(); ++i)
    +    {
             item->setData(i, Qt::ForegroundRole, QColor(color));
         }
     }
    @@ -243,7 +259,8 @@ QVector PluginSelectDialog::findItemsWithUrl(const QString &ur
         QVector res;
         res.reserve(m_ui->pluginsTree->topLevelItemCount());
     
    -    for (int i = 0; i < m_ui->pluginsTree->topLevelItemCount(); ++i) {
    +    for (int i = 0; i < m_ui->pluginsTree->topLevelItemCount(); ++i)
    +    {
             QTreeWidgetItem *item = m_ui->pluginsTree->topLevelItem(i);
             if (url.startsWith(item->text(PLUGIN_URL), Qt::CaseInsensitive))
                 res << item;
    @@ -254,7 +271,8 @@ QVector PluginSelectDialog::findItemsWithUrl(const QString &ur
     
     QTreeWidgetItem *PluginSelectDialog::findItemWithID(const QString &id)
     {
    -    for (int i = 0; i < m_ui->pluginsTree->topLevelItemCount(); ++i) {
    +    for (int i = 0; i < m_ui->pluginsTree->topLevelItemCount(); ++i)
    +    {
             QTreeWidgetItem *item = m_ui->pluginsTree->topLevelItem(i);
             if (id == item->text(PLUGIN_ID))
                 return item;
    @@ -278,20 +296,24 @@ void PluginSelectDialog::addNewPlugin(const QString &pluginName)
         item->setText(PLUGIN_NAME, plugin->fullName);
         item->setText(PLUGIN_URL, plugin->url);
         item->setText(PLUGIN_ID, plugin->name);
    -    if (plugin->enabled) {
    +    if (plugin->enabled)
    +    {
             item->setText(PLUGIN_STATE, tr("Yes"));
             setRowColor(m_ui->pluginsTree->indexOfTopLevelItem(item), "green");
         }
    -    else {
    +    else
    +    {
             item->setText(PLUGIN_STATE, tr("No"));
             setRowColor(m_ui->pluginsTree->indexOfTopLevelItem(item), "red");
         }
         // Handle icon
    -    if (QFile::exists(plugin->iconPath)) {
    +    if (QFile::exists(plugin->iconPath))
    +    {
             // Good, we already have the icon
             item->setData(PLUGIN_NAME, Qt::DecorationRole, QIcon(plugin->iconPath));
         }
    -    else {
    +    else
    +    {
             // Icon is missing, we must download it
             using namespace Net;
             DownloadManager::instance()->download(
    @@ -318,7 +340,8 @@ void PluginSelectDialog::finishAsyncOp()
     void PluginSelectDialog::finishPluginUpdate()
     {
         --m_pendingUpdates;
    -    if ((m_pendingUpdates == 0) && !m_updatedPlugins.isEmpty()) {
    +    if ((m_pendingUpdates == 0) && !m_updatedPlugins.isEmpty())
    +    {
             m_updatedPlugins.sort(Qt::CaseInsensitive);
             QMessageBox::information(this, tr("Search plugin update"), tr("Plugins installed or updated: %1").arg(m_updatedPlugins.join(", ")));
             m_updatedPlugins.clear();
    @@ -344,7 +367,8 @@ void PluginSelectDialog::askForPluginUrl()
                     tr("URL:"), QLineEdit::Normal, defaultUrl, &ok
                     );
     
    -    while (ok && !url.isEmpty() && !url.endsWith(".py")) {
    +    while (ok && !url.isEmpty() && !url.endsWith(".py"))
    +    {
             QMessageBox::warning(this, tr("Invalid link"), tr("The link doesn't seem to point to a search engine plugin."));
             url = AutoExpandableDialog::getText(
                         this, tr("New search engine plugin URL"),
    @@ -352,7 +376,8 @@ void PluginSelectDialog::askForPluginUrl()
                         );
         }
     
    -    if (ok && !url.isEmpty()) {
    +    if (ok && !url.isEmpty())
    +    {
             startAsyncOp();
             m_pluginManager->installPlugin(url);
         }
    @@ -364,7 +389,8 @@ void PluginSelectDialog::askForLocalPlugin()
                     nullptr, tr("Select search plugins"), QDir::homePath(),
                     tr("qBittorrent search plugin") + QLatin1String(" (*.py)")
                     );
    -    for (const QString &path : pathsList) {
    +    for (const QString &path : pathsList)
    +    {
             startAsyncOp();
             m_pluginManager->installPlugin(path);
         }
    @@ -372,7 +398,8 @@ void PluginSelectDialog::askForLocalPlugin()
     
     void PluginSelectDialog::iconDownloadFinished(const Net::DownloadResult &result)
     {
    -    if (result.status != Net::DownloadStatus::Success) {
    +    if (result.status != Net::DownloadStatus::Success)
    +    {
             qDebug("Could not download favicon: %s, reason: %s", qUtf8Printable(result.url), qUtf8Printable(result.errorString));
             return;
         }
    @@ -384,8 +411,10 @@ void PluginSelectDialog::iconDownloadFinished(const Net::DownloadResult &result)
         // Detect a non-decodable icon
         QList sizes = icon.availableSizes();
         bool invalid = (sizes.isEmpty() || icon.pixmap(sizes.first()).isNull());
    -    if (!invalid) {
    -        for (QTreeWidgetItem *item : asConst(findItemsWithUrl(result.url))) {
    +    if (!invalid)
    +    {
    +        for (QTreeWidgetItem *item : asConst(findItemsWithUrl(result.url)))
    +        {
                 QString id = item->text(PLUGIN_ID);
                 PluginInfo *plugin = m_pluginManager->pluginInfo(id);
                 if (!plugin) continue;
    @@ -394,14 +423,16 @@ void PluginSelectDialog::iconDownloadFinished(const Net::DownloadResult &result)
                     .arg(SearchPluginManager::pluginsLocation()
                         , id
                         , result.url.endsWith(".ico", Qt::CaseInsensitive) ? "ico" : "png");
    -            if (QFile::copy(filePath, iconPath)) {
    +            if (QFile::copy(filePath, iconPath))
    +            {
                     // This 2nd check is necessary. Some favicons (eg from piratebay)
                     // decode fine without an ext, but fail to do so when appending the ext
                     // from the url. Probably a Qt bug.
                     QIcon iconWithExt(iconPath);
                     QList sizesExt = iconWithExt.availableSizes();
                     bool invalidExt = (sizesExt.isEmpty() || iconWithExt.pixmap(sizesExt.first()).isNull());
    -                if (invalidExt) {
    +                if (invalidExt)
    +                {
                         Utils::Fs::forceRemove(iconPath);
                         continue;
                     }
    @@ -418,12 +449,14 @@ void PluginSelectDialog::iconDownloadFinished(const Net::DownloadResult &result)
     void PluginSelectDialog::checkForUpdatesFinished(const QHash &updateInfo)
     {
         finishAsyncOp();
    -    if (updateInfo.isEmpty()) {
    +    if (updateInfo.isEmpty())
    +    {
             QMessageBox::information(this, tr("Search plugin update"), tr("All your plugins are already up to date."));
             return;
         }
     
    -    for (auto i = updateInfo.cbegin(); i != updateInfo.cend(); ++i) {
    +    for (auto i = updateInfo.cbegin(); i != updateInfo.cend(); ++i)
    +    {
             startAsyncOp();
             ++m_pendingUpdates;
             m_pluginManager->updatePlugin(i.key());
    diff --git a/src/gui/search/searchjobwidget.cpp b/src/gui/search/searchjobwidget.cpp
    index 87808174c..e469dd9a1 100644
    --- a/src/gui/search/searchjobwidget.cpp
    +++ b/src/gui/search/searchjobwidget.cpp
    @@ -101,8 +101,10 @@ SearchJobWidget::SearchJobWidget(SearchHandler *searchHandler, QWidget *parent)
     
         // Ensure that at least one column is visible at all times
         bool atLeastOne = false;
    -    for (int i = 0; i < SearchSortModel::DL_LINK; ++i) {
    -        if (!m_ui->resultsBrowser->isColumnHidden(i)) {
    +    for (int i = 0; i < SearchSortModel::DL_LINK; ++i)
    +    {
    +        if (!m_ui->resultsBrowser->isColumnHidden(i))
    +        {
                 atLeastOne = true;
                 break;
             }
    @@ -218,7 +220,8 @@ void SearchJobWidget::downloadTorrents()
     void SearchJobWidget::openTorrentPages() const
     {
         const QModelIndexList rows {m_ui->resultsBrowser->selectionModel()->selectedRows()};
    -    for (const QModelIndex &rowIndex : rows) {
    +    for (const QModelIndex &rowIndex : rows)
    +    {
             const QString descrLink = m_proxyModel->data(
                         m_proxyModel->index(rowIndex.row(), SearchSortModel::DESC_LINK)).toString();
             if (!descrLink.isEmpty())
    @@ -246,7 +249,8 @@ void SearchJobWidget::copyField(const int column) const
         const QModelIndexList rows {m_ui->resultsBrowser->selectionModel()->selectedRows()};
         QStringList list;
     
    -    for (const QModelIndex &rowIndex : rows) {
    +    for (const QModelIndex &rowIndex : rows)
    +    {
             const QString field = m_proxyModel->data(
                 m_proxyModel->index(rowIndex.row(), column)).toString();
             if (!field.isEmpty())
    @@ -273,10 +277,12 @@ void SearchJobWidget::downloadTorrent(const QModelIndex &rowIndex)
         const QString siteUrl = m_proxyModel->data(
                     m_proxyModel->index(rowIndex.row(), SearchSortModel::ENGINE_URL)).toString();
     
    -    if (torrentUrl.startsWith("magnet:", Qt::CaseInsensitive)) {
    +    if (torrentUrl.startsWith("magnet:", Qt::CaseInsensitive))
    +    {
             addTorrentToSession(torrentUrl);
         }
    -    else {
    +    else
    +    {
             SearchDownloadHandler *downloadHandler = m_searchHandler->manager()->downloadTorrent(siteUrl, torrentUrl);
             connect(downloadHandler, &SearchDownloadHandler::downloadFinished, this, &SearchJobWidget::addTorrentToSession);
             connect(downloadHandler, &SearchDownloadHandler::downloadFinished, downloadHandler, &SearchDownloadHandler::deleteLater);
    @@ -418,7 +424,8 @@ void SearchJobWidget::contextMenuEvent(QContextMenuEvent *event)
     
     QString SearchJobWidget::statusText(SearchJobWidget::Status st)
     {
    -    switch (st) {
    +    switch (st)
    +    {
         case Status::Ongoing:
             return tr("Searching...");
         case Status::Finished:
    @@ -455,7 +462,8 @@ void SearchJobWidget::displayToggleColumnsMenu(const QPoint &)
         menu->setAttribute(Qt::WA_DeleteOnClose);
         menu->setTitle(tr("Column visibility"));
     
    -    for (int i = 0; i < SearchSortModel::DL_LINK; ++i) {
    +    for (int i = 0; i < SearchSortModel::DL_LINK; ++i)
    +    {
             QAction *myAct = menu->addAction(m_searchListModel->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString());
             myAct->setCheckable(true);
             myAct->setChecked(!m_ui->resultsBrowser->isColumnHidden(i));
    @@ -465,7 +473,8 @@ void SearchJobWidget::displayToggleColumnsMenu(const QPoint &)
         connect(menu, &QMenu::triggered, this, [this](const QAction *action)
         {
             int visibleCols = 0;
    -        for (int i = 0; i < SearchSortModel::DL_LINK; ++i) {
    +        for (int i = 0; i < SearchSortModel::DL_LINK; ++i)
    +        {
                 if (!m_ui->resultsBrowser->isColumnHidden(i))
                     ++visibleCols;
     
    @@ -506,7 +515,8 @@ void SearchJobWidget::searchFailed()
     
     void SearchJobWidget::appendSearchResults(const QVector &results)
     {
    -    for (const SearchResult &result : results) {
    +    for (const SearchResult &result : results)
    +    {
             // Add item to search result list
             int row = m_searchListModel->rowCount();
             m_searchListModel->insertRow(row);
    @@ -543,7 +553,8 @@ CachedSettingValue &SearchJobWidget::nameFil
     
     void SearchJobWidget::keyPressEvent(QKeyEvent *event)
     {
    -    switch (event->key()) {
    +    switch (event->key())
    +    {
         case Qt::Key_Enter:
         case Qt::Key_Return:
             downloadTorrents();
    diff --git a/src/gui/search/searchsortmodel.cpp b/src/gui/search/searchsortmodel.cpp
    index 6314d046f..7ca7bb527 100644
    --- a/src/gui/search/searchsortmodel.cpp
    +++ b/src/gui/search/searchsortmodel.cpp
    @@ -54,10 +54,12 @@ void SearchSortModel::setNameFilter(const QString &searchTerm)
     {
         m_searchTerm = searchTerm;
         if ((searchTerm.length() > 2)
    -        && searchTerm.startsWith(QLatin1Char('"')) && searchTerm.endsWith(QLatin1Char('"'))) {
    +        && searchTerm.startsWith(QLatin1Char('"')) && searchTerm.endsWith(QLatin1Char('"')))
    +        {
             m_searchTermWords = QStringList(m_searchTerm.mid(1, m_searchTerm.length() - 2));
         }
    -    else {
    +    else
    +    {
             m_searchTermWords = searchTerm.split(QLatin1Char(' '), QString::SkipEmptyParts);
         }
     }
    @@ -112,9 +114,11 @@ qint64 SearchSortModel::maxSize() const
     
     bool SearchSortModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
     {
    -    switch (sortColumn()) {
    +    switch (sortColumn())
    +    {
         case NAME:
    -    case ENGINE_URL: {
    +    case ENGINE_URL:
    +    {
                 const QString strL = left.data().toString();
                 const QString strR = right.data().toString();
                 const int result = Utils::String::naturalCompare(strL, strR, Qt::CaseInsensitive);
    @@ -130,29 +134,34 @@ bool SearchSortModel::filterAcceptsRow(const int sourceRow, const QModelIndex &s
     {
         const QAbstractItemModel *const sourceModel = this->sourceModel();
     
    -    if (m_isNameFilterEnabled && !m_searchTerm.isEmpty()) {
    +    if (m_isNameFilterEnabled && !m_searchTerm.isEmpty())
    +    {
             const QString name = sourceModel->data(sourceModel->index(sourceRow, NAME, sourceParent), UnderlyingDataRole).toString();
    -        for (const QString &word : asConst(m_searchTermWords)) {
    +        for (const QString &word : asConst(m_searchTermWords))
    +        {
                 if (!name.contains(word, Qt::CaseInsensitive))
                     return false;
             }
         }
     
    -    if ((m_minSize > 0) || (m_maxSize >= 0)) {
    +    if ((m_minSize > 0) || (m_maxSize >= 0))
    +    {
             const qlonglong size = sourceModel->data(sourceModel->index(sourceRow, SIZE, sourceParent), UnderlyingDataRole).toLongLong();
             if (((m_minSize > 0) && (size < m_minSize))
                 || ((m_maxSize > 0) && (size > m_maxSize)))
                 return false;
         }
     
    -    if ((m_minSeeds > 0) || (m_maxSeeds >= 0)) {
    +    if ((m_minSeeds > 0) || (m_maxSeeds >= 0))
    +    {
             const int seeds = sourceModel->data(sourceModel->index(sourceRow, SEEDS, sourceParent), UnderlyingDataRole).toInt();
             if (((m_minSeeds > 0) && (seeds < m_minSeeds))
                 || ((m_maxSeeds > 0) && (seeds > m_maxSeeds)))
                 return false;
         }
     
    -    if ((m_minLeeches > 0) || (m_maxLeeches >= 0)) {
    +    if ((m_minLeeches > 0) || (m_maxLeeches >= 0))
    +    {
             const int leeches = sourceModel->data(sourceModel->index(sourceRow, LEECHES, sourceParent), UnderlyingDataRole).toInt();
             if (((m_minLeeches > 0) && (leeches < m_minLeeches))
                 || ((m_maxLeeches > 0) && (leeches > m_maxLeeches)))
    diff --git a/src/gui/search/searchwidget.cpp b/src/gui/search/searchwidget.cpp
    index c183a8137..a4f9e3148 100644
    --- a/src/gui/search/searchwidget.cpp
    +++ b/src/gui/search/searchwidget.cpp
    @@ -63,7 +63,8 @@ namespace
     {
         QString statusIconName(SearchJobWidget::Status st)
         {
    -        switch (st) {
    +        switch (st)
    +        {
             case SearchJobWidget::Status::Ongoing:
                 return QLatin1String("task-ongoing");
             case SearchJobWidget::Status::Finished:
    @@ -148,14 +149,16 @@ SearchWidget::SearchWidget(MainWindow *mainWindow)
     
     bool SearchWidget::eventFilter(QObject *object, QEvent *event)
     {
    -    if (object == m_ui->tabWidget->tabBar()) {
    +    if (object == m_ui->tabWidget->tabBar())
    +    {
             // Close tabs when middle-clicked
             if (event->type() != QEvent::MouseButtonRelease)
                 return false;
     
             const auto mouseEvent = static_cast(event);
             const int tabIndex = m_ui->tabWidget->tabBar()->tabAt(mouseEvent->pos());
    -        if ((mouseEvent->button() == Qt::MiddleButton) && (tabIndex >= 0)) {
    +        if ((mouseEvent->button() == Qt::MiddleButton) && (tabIndex >= 0))
    +        {
                 closeTab(tabIndex);
                 return true;
             }
    @@ -175,7 +178,8 @@ void SearchWidget::fillCatCombobox()
             tmpList << qMakePair(SearchPluginManager::categoryFullName(cat), cat);
         std::sort(tmpList.begin(), tmpList.end(), [](const QStrPair &l, const QStrPair &r) { return (QString::localeAwareCompare(l.first, r.first) < 0); });
     
    -    for (const QStrPair &p : asConst(tmpList)) {
    +    for (const QStrPair &p : asConst(tmpList))
    +    {
             qDebug("Supported category: %s", qUtf8Printable(p.second));
             m_ui->comboCategory->addItem(p.first, p.second);
         }
    @@ -216,14 +220,16 @@ QString SearchWidget::selectedPlugin() const
     
     void SearchWidget::selectActivePage()
     {
    -    if (SearchPluginManager::instance()->allPlugins().isEmpty()) {
    +    if (SearchPluginManager::instance()->allPlugins().isEmpty())
    +    {
             m_ui->stackedPages->setCurrentWidget(m_ui->emptyPage);
             m_ui->lineEditSearchPattern->setEnabled(false);
             m_ui->comboCategory->setEnabled(false);
             m_ui->selectPlugin->setEnabled(false);
             m_ui->searchButton->setEnabled(false);
         }
    -    else {
    +    else
    +    {
             m_ui->stackedPages->setCurrentWidget(m_ui->searchPage);
             m_ui->lineEditSearchPattern->setEnabled(true);
             m_ui->comboCategory->setEnabled(true);
    @@ -254,11 +260,13 @@ void SearchWidget::selectMultipleBox(int index)
     
     void SearchWidget::toggleFocusBetweenLineEdits()
     {
    -    if (m_ui->lineEditSearchPattern->hasFocus() && m_currentSearchTab) {
    +    if (m_ui->lineEditSearchPattern->hasFocus() && m_currentSearchTab)
    +    {
             m_currentSearchTab->lineEditSearchResultsFilter()->setFocus();
             m_currentSearchTab->lineEditSearchResultsFilter()->selectAll();
         }
    -    else {
    +    else
    +    {
             m_ui->lineEditSearchPattern->setFocus();
             m_ui->lineEditSearchPattern->selectAll();
         }
    @@ -284,14 +292,17 @@ void SearchWidget::giveFocusToSearchInput()
     // Function called when we click on search button
     void SearchWidget::on_searchButton_clicked()
     {
    -    if (!Utils::ForeignApps::pythonInfo().isValid()) {
    +    if (!Utils::ForeignApps::pythonInfo().isValid())
    +    {
             m_mainWindow->showNotificationBaloon(tr("Search Engine"), tr("Please install Python to use the Search Engine."));
             return;
         }
     
    -    if (m_activeSearchTab) {
    +    if (m_activeSearchTab)
    +    {
             m_activeSearchTab->cancelSearch();
    -        if (!m_isNewQueryString) {
    +        if (!m_isNewQueryString)
    +        {
                 m_ui->searchButton->setText(tr("Search"));
                 return;
             }
    @@ -301,7 +312,8 @@ void SearchWidget::on_searchButton_clicked()
     
         const QString pattern = m_ui->lineEditSearchPattern->text().trimmed();
         // No search pattern entered
    -    if (pattern.isEmpty()) {
    +    if (pattern.isEmpty())
    +    {
             QMessageBox::critical(this, tr("Empty search pattern"), tr("Please type a search pattern first"));
             return;
         }
    @@ -344,10 +356,12 @@ void SearchWidget::tabStatusChanged(QWidget *tab)
         m_ui->tabWidget->setTabIcon(tabIndex, UIThemeManager::instance()->getIcon(
                                      statusIconName(static_cast(tab)->status())));
     
    -    if ((tab == m_activeSearchTab) && (m_activeSearchTab->status() != SearchJobWidget::Status::Ongoing)) {
    +    if ((tab == m_activeSearchTab) && (m_activeSearchTab->status() != SearchJobWidget::Status::Ongoing))
    +    {
             Q_ASSERT(m_activeSearchTab->status() != SearchJobWidget::Status::Ongoing);
     
    -        if (m_mainWindow->isNotificationsEnabled() && (m_mainWindow->currentTabWidget() != this)) {
    +        if (m_mainWindow->isNotificationsEnabled() && (m_mainWindow->currentTabWidget() != this))
    +        {
                 if (m_activeSearchTab->status() == SearchJobWidget::Status::Error)
                     m_mainWindow->showNotificationBaloon(tr("Search Engine"), tr("Search has failed"));
                 else
    diff --git a/src/gui/shutdownconfirmdialog.cpp b/src/gui/shutdownconfirmdialog.cpp
    index 82de9afaa..0a2e28676 100644
    --- a/src/gui/shutdownconfirmdialog.cpp
    +++ b/src/gui/shutdownconfirmdialog.cpp
    @@ -91,7 +91,8 @@ void ShutdownConfirmDialog::updateSeconds()
     {
         --m_timeout;
         updateText();
    -    if (m_timeout == 0) {
    +    if (m_timeout == 0)
    +    {
             m_timer.stop();
             accept();
         }
    @@ -107,7 +108,8 @@ void ShutdownConfirmDialog::initText()
     {
         QPushButton *okButton = m_ui->buttonBox->button(QDialogButtonBox::Ok);
     
    -    switch (m_action) {
    +    switch (m_action)
    +    {
         case ShutdownDialogAction::Exit:
             m_msg = tr("qBittorrent will now exit.");
             okButton->setText(tr("E&xit Now"));
    diff --git a/src/gui/speedlimitdialog.cpp b/src/gui/speedlimitdialog.cpp
    index 6ca1cf5b8..59058eca9 100644
    --- a/src/gui/speedlimitdialog.cpp
    +++ b/src/gui/speedlimitdialog.cpp
    @@ -59,7 +59,8 @@ long SpeedLimitDialog::askSpeedLimit(QWidget *parent, bool *ok, const QString &t
         dlg.setWindowTitle(title);
         dlg.setupDialog((maxVal / 1024.), (defaultVal / 1024.));
     
    -    if (dlg.exec() == QDialog::Accepted) {
    +    if (dlg.exec() == QDialog::Accepted)
    +    {
             if (ok) *ok = true;
     
             const int val = dlg.getSpeedLimit();
    diff --git a/src/gui/statusbar.cpp b/src/gui/statusbar.cpp
    index 3dbbf14f6..2554608b4 100644
    --- a/src/gui/statusbar.cpp
    +++ b/src/gui/statusbar.cpp
    @@ -173,17 +173,21 @@ void StatusBar::updateConnectionStatus()
     {
         const BitTorrent::SessionStatus &sessionStatus = BitTorrent::Session::instance()->status();
     
    -    if (!BitTorrent::Session::instance()->isListening()) {
    +    if (!BitTorrent::Session::instance()->isListening())
    +    {
             m_connecStatusLblIcon->setIcon(UIThemeManager::instance()->getIcon(QLatin1String("disconnected")));
             m_connecStatusLblIcon->setToolTip(QLatin1String("") + tr("Connection Status:") + QLatin1String("
    ") + tr("Offline. This usually means that qBittorrent failed to listen on the selected port for incoming connections.")); } - else { - if (sessionStatus.hasIncomingConnections) { + else + { + if (sessionStatus.hasIncomingConnections) + { // Connection OK m_connecStatusLblIcon->setIcon(UIThemeManager::instance()->getIcon(QLatin1String("connected"))); m_connecStatusLblIcon->setToolTip(QLatin1String("") + tr("Connection Status:") + QLatin1String("
    ") + tr("Online")); } - else { + else + { m_connecStatusLblIcon->setIcon(UIThemeManager::instance()->getIcon(QLatin1String("firewalled"))); m_connecStatusLblIcon->setToolTip(QLatin1String("") + tr("Connection status:") + QLatin1String("
    ") + QLatin1String("") + tr("No direct connections. This may indicate network configuration problems.") + QLatin1String("")); } @@ -192,12 +196,14 @@ void StatusBar::updateConnectionStatus() void StatusBar::updateDHTNodesNumber() { - if (BitTorrent::Session::instance()->isDHTEnabled()) { + if (BitTorrent::Session::instance()->isDHTEnabled()) + { m_DHTLbl->setVisible(true); m_DHTLbl->setText(tr("DHT: %1 nodes") .arg(BitTorrent::Session::instance()->status().dhtNodes)); } - else { + else + { m_DHTLbl->setVisible(false); } } @@ -230,12 +236,14 @@ void StatusBar::refresh() void StatusBar::updateAltSpeedsBtn(bool alternative) { - if (alternative) { + if (alternative) + { m_altSpeedsBtn->setIcon(UIThemeManager::instance()->getIcon(QLatin1String("slow"))); m_altSpeedsBtn->setToolTip(tr("Click to switch to regular speed limits")); m_altSpeedsBtn->setDown(true); } - else { + else + { m_altSpeedsBtn->setIcon(UIThemeManager::instance()->getIcon(QLatin1String("slow_off"))); m_altSpeedsBtn->setToolTip(tr("Click to switch to alternative speed limits")); m_altSpeedsBtn->setDown(false); @@ -250,7 +258,8 @@ void StatusBar::capDownloadSpeed() bool ok = false; const long newLimit = SpeedLimitDialog::askSpeedLimit( parentWidget(), &ok, tr("Global Download Speed Limit"), session->downloadSpeedLimit()); - if (ok) { + if (ok) + { qDebug("Setting global download rate limit to %.1fKb/s", newLimit / 1024.); session->setDownloadSpeedLimit(newLimit); refresh(); @@ -264,7 +273,8 @@ void StatusBar::capUploadSpeed() bool ok = false; const long newLimit = SpeedLimitDialog::askSpeedLimit( parentWidget(), &ok, tr("Global Upload Speed Limit"), session->uploadSpeedLimit()); - if (ok) { + if (ok) + { qDebug("Setting global upload rate limit to %.1fKb/s", newLimit / 1024.); session->setUploadSpeedLimit(newLimit); refresh(); diff --git a/src/gui/tagfiltermodel.cpp b/src/gui/tagfiltermodel.cpp index 41985d18b..a5d538da7 100644 --- a/src/gui/tagfiltermodel.cpp +++ b/src/gui/tagfiltermodel.cpp @@ -120,7 +120,8 @@ QVariant TagFilterModel::data(const QModelIndex &index, int role) const Q_ASSERT(isValidRow(row)); const TagModelItem &item = m_tagItems[row]; - switch (role) { + switch (role) + { case Qt::DecorationRole: return UIThemeManager::instance()->getIcon("inode-directory"); case Qt::DisplayRole: @@ -275,7 +276,8 @@ void TagFilterModel::populate() [](Torrent *torrent) { return torrent->tags().isEmpty(); }); addToModel(getSpecialUntaggedTag(), untaggedCount); - for (const QString &tag : asConst(session->tags())) { + for (const QString &tag : asConst(session->tags())) + { const int count = std::count_if(torrents.cbegin(), torrents.cend(), [tag](Torrent *torrent) { return torrent->hasTag(tag); }); addToModel(tag, count); @@ -295,7 +297,8 @@ void TagFilterModel::removeFromModel(int row) int TagFilterModel::findRow(const QString &tag) const { - for (int i = 0; i < m_tagItems.size(); ++i) { + for (int i = 0; i < m_tagItems.size(); ++i) + { if (m_tagItems[i].tag() == tag) return i; } @@ -314,7 +317,8 @@ QVector TagFilterModel::findItems(const QSet &tags) { QVector items; items.reserve(tags.size()); - for (const QString &tag : tags) { + for (const QString &tag : tags) + { TagModelItem *item = findItem(tag); if (item) items.push_back(item); diff --git a/src/gui/tagfilterwidget.cpp b/src/gui/tagfilterwidget.cpp index 3c83b2c05..72c344bee 100644 --- a/src/gui/tagfilterwidget.cpp +++ b/src/gui/tagfilterwidget.cpp @@ -45,7 +45,8 @@ namespace QString getTagFilter(const TagFilterProxyModel *const model, const QModelIndex &index) { QString tagFilter; // Defaults to All - if (index.isValid()) { + if (index.isValid()) + { if (index.row() == 1) tagFilter = ""; // Untagged else if (index.row() > 1) @@ -113,7 +114,8 @@ void TagFilterWidget::showMenu(QPoint) connect(addAct, &QAction::triggered, this, &TagFilterWidget::addTag); const auto selectedRows = selectionModel()->selectedRows(); - if (!selectedRows.empty() && !TagFilterModel::isSpecialItem(selectedRows.first())) { + if (!selectedRows.empty() && !TagFilterModel::isSpecialItem(selectedRows.first())) + { const QAction *removeAct = menu->addAction( UIThemeManager::instance()->getIcon("list-remove") , tr("Remove tag")); @@ -155,7 +157,8 @@ void TagFilterWidget::callUpdateGeometry() QSize TagFilterWidget::sizeHint() const { - return { + return + { // Width should be exactly the width of the content sizeHintForColumn(0), // Height should be exactly the height of the content @@ -181,12 +184,15 @@ QString TagFilterWidget::askTagName() bool ok = false; QString tag = ""; bool invalid = true; - while (invalid) { + while (invalid) + { invalid = false; tag = AutoExpandableDialog::getText( this, tr("New Tag"), tr("Tag:"), QLineEdit::Normal, tag, &ok).trimmed(); - if (ok && !tag.isEmpty()) { - if (!BitTorrent::Session::isValidTag(tag)) { + if (ok && !tag.isEmpty()) + { + if (!BitTorrent::Session::isValidTag(tag)) + { QMessageBox::warning( this, tr("Invalid tag name") , tr("Tag name '%1' is invalid").arg(tag)); @@ -212,7 +218,8 @@ void TagFilterWidget::addTag() void TagFilterWidget::removeTag() { const auto selectedRows = selectionModel()->selectedRows(); - if (!selectedRows.empty() && !TagFilterModel::isSpecialItem(selectedRows.first())) { + if (!selectedRows.empty() && !TagFilterModel::isSpecialItem(selectedRows.first())) + { BitTorrent::Session::instance()->removeTag( static_cast(model())->tag(selectedRows.first())); updateGeometry(); diff --git a/src/gui/torrentcategorydialog.cpp b/src/gui/torrentcategorydialog.cpp index 5a8a52d2f..d3ce24519 100644 --- a/src/gui/torrentcategorydialog.cpp +++ b/src/gui/torrentcategorydialog.cpp @@ -58,23 +58,27 @@ QString TorrentCategoryDialog::createCategory(QWidget *parent, const QString &pa TorrentCategoryDialog dialog(parent); dialog.setCategoryName(newCategoryName); - while (dialog.exec() == TorrentCategoryDialog::Accepted) { + while (dialog.exec() == TorrentCategoryDialog::Accepted) + { newCategoryName = dialog.categoryName(); - if (!BitTorrent::Session::isValidCategoryName(newCategoryName)) { + if (!BitTorrent::Session::isValidCategoryName(newCategoryName)) + { QMessageBox::critical( parent, tr("Invalid category name") , tr("Category name cannot contain '\\'.\n" "Category name cannot start/end with '/'.\n" "Category name cannot contain '//' sequence.")); } - else if (BitTorrent::Session::instance()->categories().contains(newCategoryName)) { + else if (BitTorrent::Session::instance()->categories().contains(newCategoryName)) + { QMessageBox::critical( parent, tr("Category creation error") , tr("Category with the given name already exists.\n" "Please choose a different name and try again.")); } - else { + else + { Session::instance()->addCategory(newCategoryName, dialog.savePath()); return newCategoryName; } diff --git a/src/gui/torrentcontentfiltermodel.cpp b/src/gui/torrentcontentfiltermodel.cpp index f28b3a1fa..d774168d2 100644 --- a/src/gui/torrentcontentfiltermodel.cpp +++ b/src/gui/torrentcontentfiltermodel.cpp @@ -71,7 +71,8 @@ QModelIndex TorrentContentFilterModel::parent(const QModelIndex &child) const bool TorrentContentFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { - if (m_model->itemType(m_model->index(sourceRow, 0, sourceParent)) == TorrentContentModelItem::FolderType) { + if (m_model->itemType(m_model->index(sourceRow, 0, sourceParent)) == TorrentContentModelItem::FolderType) + { // accept folders if they have at least one filtered item return hasFiltered(m_model->index(sourceRow, 0, sourceParent)); } @@ -81,17 +82,21 @@ bool TorrentContentFilterModel::filterAcceptsRow(int sourceRow, const QModelInde bool TorrentContentFilterModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - switch (sortColumn()) { - case TorrentContentModelItem::COL_NAME: { + switch (sortColumn()) + { + case TorrentContentModelItem::COL_NAME: + { const TorrentContentModelItem::ItemType leftType = m_model->itemType(m_model->index(left.row(), 0, left.parent())); const TorrentContentModelItem::ItemType rightType = m_model->itemType(m_model->index(right.row(), 0, right.parent())); - if (leftType == rightType) { + if (leftType == rightType) + { const QString strL = left.data().toString(); const QString strR = right.data().toString(); return Utils::String::naturalLessThan(strL, strR); } - if ((leftType == TorrentContentModelItem::FolderType) && (sortOrder() == Qt::AscendingOrder)) { + if ((leftType == TorrentContentModelItem::FolderType) && (sortOrder() == Qt::AscendingOrder)) + { return true; } @@ -125,9 +130,11 @@ bool TorrentContentFilterModel::hasFiltered(const QModelIndex &folder) const QString name = folder.data().toString(); if (name.contains(filterRegExp())) return true; - for (int child = 0; child < m_model->rowCount(folder); ++child) { + for (int child = 0; child < m_model->rowCount(folder); ++child) + { QModelIndex childIndex = m_model->index(child, 0, folder); - if (m_model->hasChildren(childIndex)) { + if (m_model->hasChildren(childIndex)) + { if (hasFiltered(childIndex)) return true; continue; diff --git a/src/gui/torrentcontentmodel.cpp b/src/gui/torrentcontentmodel.cpp index 01c54b48a..1c07f4ee2 100644 --- a/src/gui/torrentcontentmodel.cpp +++ b/src/gui/torrentcontentmodel.cpp @@ -85,12 +85,14 @@ namespace QIcon icon(const QFileInfo &info) const final { const QString ext = info.suffix(); - if (!ext.isEmpty()) { + if (!ext.isEmpty()) + { QPixmap cached; if (QPixmapCache::find(ext, &cached)) return {cached}; const QPixmap pixmap = pixmapForExtension(ext); - if (!pixmap.isNull()) { + if (!pixmap.isNull()) + { QPixmapCache::insert(ext, pixmap); return {pixmap}; } @@ -160,12 +162,14 @@ namespace { const QMimeType mimeType = m_db.mimeTypeForFile(info, QMimeDatabase::MatchExtension); QIcon res = QIcon::fromTheme(mimeType.iconName()); - if (!res.isNull()) { + if (!res.isNull()) + { return res; } res = QIcon::fromTheme(mimeType.genericIconName()); - if (!res.isNull()) { + if (!res.isNull()) + { return res; } @@ -270,10 +274,12 @@ bool TorrentContentModel::setData(const QModelIndex &index, const QVariant &valu if (!index.isValid()) return false; - if ((index.column() == TorrentContentModelItem::COL_NAME) && (role == Qt::CheckStateRole)) { + if ((index.column() == TorrentContentModelItem::COL_NAME) && (role == Qt::CheckStateRole)) + { auto *item = static_cast(index.internalPointer()); qDebug("setData(%s, %d", qUtf8Printable(item->name()), value.toInt()); - if (static_cast(item->priority()) != value.toInt()) { + if (static_cast(item->priority()) != value.toInt()) + { BitTorrent::DownloadPriority prio = BitTorrent::DownloadPriority::Normal; if (value.toInt() == Qt::PartiallyChecked) prio = BitTorrent::DownloadPriority::Mixed; @@ -290,10 +296,12 @@ bool TorrentContentModel::setData(const QModelIndex &index, const QVariant &valu return true; } - if (role == Qt::EditRole) { + if (role == Qt::EditRole) + { Q_ASSERT(index.isValid()); auto *item = static_cast(index.internalPointer()); - switch (index.column()) { + switch (index.column()) + { case TorrentContentModelItem::COL_NAME: item->setName(value.toString()); break; @@ -332,8 +340,10 @@ QVariant TorrentContentModel::data(const QModelIndex &index, int role) const auto *item = static_cast(index.internalPointer()); - switch (role) { - case Qt::DecorationRole: { + switch (role) + { + case Qt::DecorationRole: + { if (index.column() != TorrentContentModelItem::COL_NAME) return {}; @@ -341,7 +351,8 @@ QVariant TorrentContentModel::data(const QModelIndex &index, int role) const return m_fileIconProvider->icon(QFileIconProvider::Folder); return m_fileIconProvider->icon(QFileInfo(item->name())); } - case Qt::CheckStateRole: { + case Qt::CheckStateRole: + { if (index.column() != TorrentContentModelItem::COL_NAME) return {}; @@ -384,7 +395,8 @@ QVariant TorrentContentModel::headerData(int section, Qt::Orientation orientatio if (orientation != Qt::Horizontal) return {}; - switch (role) { + switch (role) + { case Qt::DisplayRole: return m_rootItem->displayData(section); @@ -476,7 +488,8 @@ void TorrentContentModel::setupModelData(const BitTorrent::TorrentInfo &info) TorrentContentModelFolder *currentParent; // Iterate over files - for (int i = 0; i < filesCount; ++i) { + for (int i = 0; i < filesCount; ++i) + { currentParent = m_rootItem; const QString path = Utils::Fs::toUniformPath(info.filePath(i)); @@ -484,10 +497,12 @@ void TorrentContentModel::setupModelData(const BitTorrent::TorrentInfo &info) QVector pathFolders = path.splitRef('/', QString::SkipEmptyParts); pathFolders.removeLast(); - for (const QStringRef &pathPartRef : asConst(pathFolders)) { + for (const QStringRef &pathPartRef : asConst(pathFolders)) + { const QString pathPart = pathPartRef.toString(); TorrentContentModelFolder *newParent = currentParent->childFolderWithName(pathPart); - if (!newParent) { + if (!newParent) + { newParent = new TorrentContentModelFolder(pathPart, currentParent); currentParent->appendChild(newParent); } @@ -503,7 +518,8 @@ void TorrentContentModel::setupModelData(const BitTorrent::TorrentInfo &info) void TorrentContentModel::selectAll() { - for (int i = 0; i < m_rootItem->childCount(); ++i) { + for (int i = 0; i < m_rootItem->childCount(); ++i) + { TorrentContentModelItem* child = m_rootItem->child(i); if (child->priority() == BitTorrent::DownloadPriority::Ignored) child->setPriority(BitTorrent::DownloadPriority::Normal); diff --git a/src/gui/torrentcontentmodelfolder.cpp b/src/gui/torrentcontentmodelfolder.cpp index d20fa86d8..f0b073301 100644 --- a/src/gui/torrentcontentmodelfolder.cpp +++ b/src/gui/torrentcontentmodelfolder.cpp @@ -88,7 +88,8 @@ TorrentContentModelItem *TorrentContentModelFolder::child(int row) const TorrentContentModelFolder *TorrentContentModelFolder::childFolderWithName(const QString &name) const { - for (TorrentContentModelItem *child : asConst(m_childItems)) { + for (TorrentContentModelItem *child : asConst(m_childItems)) + { if ((child->itemType() == FolderType) && (child->name() == name)) return static_cast(child); } @@ -112,8 +113,10 @@ void TorrentContentModelFolder::updatePriority() // then the folder should have the same // priority const BitTorrent::DownloadPriority prio = m_childItems.first()->priority(); - for (int i = 1; i < m_childItems.size(); ++i) { - if (m_childItems.at(i)->priority() != prio) { + for (int i = 1; i < m_childItems.size(); ++i) + { + if (m_childItems.at(i)->priority() != prio) + { setPriority(BitTorrent::DownloadPriority::Mixed); return; } @@ -145,7 +148,8 @@ void TorrentContentModelFolder::recalculateProgress() qreal tProgress = 0; qulonglong tSize = 0; qulonglong tRemaining = 0; - for (TorrentContentModelItem *child : asConst(m_childItems)) { + for (TorrentContentModelItem *child : asConst(m_childItems)) + { if (child->priority() == BitTorrent::DownloadPriority::Ignored) continue; @@ -156,7 +160,8 @@ void TorrentContentModelFolder::recalculateProgress() tRemaining += child->remaining(); } - if (!isRootItem() && (tSize > 0)) { + if (!isRootItem() && (tSize > 0)) + { m_progress = tProgress / tSize; m_remaining = tRemaining; Q_ASSERT(m_progress <= 1.); @@ -168,25 +173,29 @@ void TorrentContentModelFolder::recalculateAvailability() qreal tAvailability = 0; qulonglong tSize = 0; bool foundAnyData = false; - for (TorrentContentModelItem *child : asConst(m_childItems)) { + for (TorrentContentModelItem *child : asConst(m_childItems)) + { if (child->priority() == BitTorrent::DownloadPriority::Ignored) continue; if (child->itemType() == FolderType) static_cast(child)->recalculateAvailability(); const qreal childAvailability = child->availability(); - if (childAvailability >= 0) { // -1 means "no data" + if (childAvailability >= 0) + { // -1 means "no data" tAvailability += childAvailability * child->size(); foundAnyData = true; } tSize += child->size(); } - if (!isRootItem() && (tSize > 0) && foundAnyData) { + if (!isRootItem() && (tSize > 0) && foundAnyData) + { m_availability = tAvailability / tSize; Q_ASSERT(m_availability <= 1.); } - else { + else + { m_availability = -1.; } } diff --git a/src/gui/torrentcontentmodelitem.cpp b/src/gui/torrentcontentmodelitem.cpp index ba5216f8e..e7f4ac247 100644 --- a/src/gui/torrentcontentmodelitem.cpp +++ b/src/gui/torrentcontentmodelitem.cpp @@ -107,11 +107,14 @@ QString TorrentContentModelItem::displayData(const int column) const if (isRootItem()) return m_itemData.value(column); - switch (column) { + switch (column) + { case COL_NAME: return m_name; - case COL_PRIO: { - switch (m_priority) { + case COL_PRIO: + { + switch (m_priority) + { case BitTorrent::DownloadPriority::Mixed: return tr("Mixed", "Mixed (priorities"); case BitTorrent::DownloadPriority::Ignored: @@ -124,7 +127,8 @@ QString TorrentContentModelItem::displayData(const int column) const return tr("Normal", "Normal (priority)"); } } - case COL_PROGRESS: { + case COL_PROGRESS: + { const qreal progress = m_progress * 100; return (static_cast(progress) == 100) ? QString::fromLatin1("100%") @@ -134,7 +138,8 @@ QString TorrentContentModelItem::displayData(const int column) const return Utils::Misc::friendlyUnit(m_size); case COL_REMAINING: return Utils::Misc::friendlyUnit(remaining()); - case COL_AVAILABILITY: { + case COL_AVAILABILITY: + { const int avail = availability(); if (avail < 0) return tr("N/A"); @@ -155,7 +160,8 @@ QVariant TorrentContentModelItem::underlyingData(const int column) const if (isRootItem()) return m_itemData.value(column); - switch (column) { + switch (column) + { case COL_NAME: return m_name; case COL_PRIO: diff --git a/src/gui/torrentcontenttreeview.cpp b/src/gui/torrentcontenttreeview.cpp index adf22046e..c6341c003 100644 --- a/src/gui/torrentcontenttreeview.cpp +++ b/src/gui/torrentcontenttreeview.cpp @@ -62,7 +62,8 @@ TorrentContentTreeView::TorrentContentTreeView(QWidget *parent) void TorrentContentTreeView::keyPressEvent(QKeyEvent *event) { - if ((event->key() != Qt::Key_Space) && (event->key() != Qt::Key_Select)) { + if ((event->key() != Qt::Key_Space) && (event->key() != Qt::Key_Select)) + { QTreeView::keyPressEvent(event); return; } @@ -72,7 +73,8 @@ void TorrentContentTreeView::keyPressEvent(QKeyEvent *event) QModelIndex current = currentNameCell(); QVariant value = current.data(Qt::CheckStateRole); - if (!value.isValid()) { + if (!value.isValid()) + { Q_ASSERT(false); return; } @@ -82,7 +84,8 @@ void TorrentContentTreeView::keyPressEvent(QKeyEvent *event) const QModelIndexList selection = selectionModel()->selectedRows(TorrentContentModelItem::COL_NAME); - for (const QModelIndex &index : selection) { + for (const QModelIndex &index : selection) + { Q_ASSERT(index.column() == TorrentContentModelItem::COL_NAME); model()->setData(index, state, Qt::CheckStateRole); } @@ -109,14 +112,16 @@ void TorrentContentTreeView::renameSelectedFile(BitTorrent::TorrentHandle *torre , modelIndex.data().toString(), &ok, isFile).trimmed(); if (!ok || !modelIndex.isValid()) return; - if (!Utils::Fs::isValidFileSystemName(newName)) { + if (!Utils::Fs::isValidFileSystemName(newName)) + { RaisedMessageBox::warning(this, tr("Rename error"), tr("The name is empty or contains forbidden characters, please choose a different one."), QMessageBox::Ok); return; } - if (isFile) { + if (isFile) + { const int fileIndex = model->getFileIndex(modelIndex); if (newName.endsWith(QB_EXT)) @@ -129,15 +134,18 @@ void TorrentContentTreeView::renameSelectedFile(BitTorrent::TorrentHandle *torre const QString newFileName = newName + (useFilenameExt ? QB_EXT : QString()); const QString newFilePath = oldFilePath.leftRef(oldFilePath.size() - oldFileName.size()) + newFileName; - if (oldFileName == newFileName) { + if (oldFileName == newFileName) + { qDebug("Name did not change: %s", qUtf8Printable(oldFileName)); return; } // check if that name is already used - for (int i = 0; i < torrent->filesCount(); ++i) { + for (int i = 0; i < torrent->filesCount(); ++i) + { if (i == fileIndex) continue; - if (Utils::Fs::sameFileNames(torrent->filePath(i), newFilePath)) { + if (Utils::Fs::sameFileNames(torrent->filePath(i), newFilePath)) + { RaisedMessageBox::warning(this, tr("Rename error"), tr("This name is already in use in this folder. Please use a different name."), QMessageBox::Ok); @@ -150,7 +158,8 @@ void TorrentContentTreeView::renameSelectedFile(BitTorrent::TorrentHandle *torre model->setData(modelIndex, newName); } - else { + else + { // renaming a folder const QString oldName = modelIndex.data().toString(); @@ -171,13 +180,15 @@ void TorrentContentTreeView::renameSelectedFile(BitTorrent::TorrentHandle *torre const Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive; #endif - for (int i = 0; i < torrent->filesCount(); ++i) { + for (int i = 0; i < torrent->filesCount(); ++i) + { const QString currentPath = torrent->filePath(i); if (currentPath.startsWith(oldPath)) continue; - if (currentPath.startsWith(newPath, caseSensitivity)) { + if (currentPath.startsWith(newPath, caseSensitivity)) + { RaisedMessageBox::warning(this, tr("The folder could not be renamed"), tr("This name is already in use. Please use a different name."), QMessageBox::Ok); @@ -188,10 +199,12 @@ void TorrentContentTreeView::renameSelectedFile(BitTorrent::TorrentHandle *torre // Replace path in all files bool needForceRecheck = false; - for (int i = 0; i < torrent->filesCount(); ++i) { + for (int i = 0; i < torrent->filesCount(); ++i) + { const QString currentPath = torrent->filePath(i); - if (currentPath.startsWith(oldPath)) { + if (currentPath.startsWith(oldPath)) + { const QString path {newPath + currentPath.mid(oldPath.length())}; if (!needForceRecheck && QFile::exists(path)) @@ -228,14 +241,16 @@ void TorrentContentTreeView::renameSelectedFile(BitTorrent::TorrentInfo &torrent , modelIndex.data().toString(), &ok, isFile).trimmed(); if (!ok || !modelIndex.isValid()) return; - if (!Utils::Fs::isValidFileSystemName(newName)) { + if (!Utils::Fs::isValidFileSystemName(newName)) + { RaisedMessageBox::warning(this, tr("Rename error"), tr("The name is empty or contains forbidden characters, please choose a different one."), QMessageBox::Ok); return; } - if (isFile) { + if (isFile) + { const int fileIndex = model->getFileIndex(modelIndex); if (newName.endsWith(QB_EXT)) @@ -244,15 +259,18 @@ void TorrentContentTreeView::renameSelectedFile(BitTorrent::TorrentInfo &torrent const QString oldFilePath = torrent.filePath(fileIndex); const QString newFilePath = oldFilePath.leftRef(oldFilePath.size() - oldFileName.size()) + newName; - if (oldFileName == newName) { + if (oldFileName == newName) + { qDebug("Name did not change: %s", qUtf8Printable(oldFileName)); return; } // check if that name is already used - for (int i = 0; i < torrent.filesCount(); ++i) { + for (int i = 0; i < torrent.filesCount(); ++i) + { if (i == fileIndex) continue; - if (Utils::Fs::sameFileNames(torrent.filePath(i), newFilePath)) { + if (Utils::Fs::sameFileNames(torrent.filePath(i), newFilePath)) + { RaisedMessageBox::warning(this, tr("Rename error"), tr("This name is already in use in this folder. Please use a different name."), QMessageBox::Ok); @@ -265,7 +283,8 @@ void TorrentContentTreeView::renameSelectedFile(BitTorrent::TorrentInfo &torrent model->setData(modelIndex, newName); } - else { + else + { // renaming a folder const QString oldName = modelIndex.data().toString(); @@ -286,13 +305,15 @@ void TorrentContentTreeView::renameSelectedFile(BitTorrent::TorrentInfo &torrent const Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive; #endif - for (int i = 0; i < torrent.filesCount(); ++i) { + for (int i = 0; i < torrent.filesCount(); ++i) + { const QString currentPath = torrent.filePath(i); if (currentPath.startsWith(oldPath)) continue; - if (currentPath.startsWith(newPath, caseSensitivity)) { + if (currentPath.startsWith(newPath, caseSensitivity)) + { RaisedMessageBox::warning(this, tr("The folder could not be renamed"), tr("This name is already in use. Please use a different name."), QMessageBox::Ok); @@ -301,10 +322,12 @@ void TorrentContentTreeView::renameSelectedFile(BitTorrent::TorrentInfo &torrent } // Replace path in all files - for (int i = 0; i < torrent.filesCount(); ++i) { + for (int i = 0; i < torrent.filesCount(); ++i) + { const QString currentPath = torrent.filePath(i); - if (currentPath.startsWith(oldPath)) { + if (currentPath.startsWith(oldPath)) + { const QString path {newPath + currentPath.mid(oldPath.length())}; torrent.renameFile(i, path); } @@ -317,7 +340,8 @@ void TorrentContentTreeView::renameSelectedFile(BitTorrent::TorrentInfo &torrent QModelIndex TorrentContentTreeView::currentNameCell() { QModelIndex current = currentIndex(); - if (!current.isValid()) { + if (!current.isValid()) + { Q_ASSERT(false); return {}; } diff --git a/src/gui/torrentcreatordialog.cpp b/src/gui/torrentcreatordialog.cpp index 53a9a07fb..e7d67ceb0 100644 --- a/src/gui/torrentcreatordialog.cpp +++ b/src/gui/torrentcreatordialog.cpp @@ -130,7 +130,8 @@ int TorrentCreatorDialog::getPieceSize() const #if (LIBTORRENT_VERSION_NUM >= 20000) BitTorrent::TorrentFormat TorrentCreatorDialog::getTorrentFormat() const { - switch (m_ui->comboTorrentFormat->currentIndex()) { + switch (m_ui->comboTorrentFormat->currentIndex()) + { case 0: return BitTorrent::TorrentFormat::V2; case 1: @@ -152,7 +153,8 @@ void TorrentCreatorDialog::dropEvent(QDropEvent *event) { event->acceptProposedAction(); - if (event->mimeData()->hasUrls()) { + if (event->mimeData()->hasUrls()) + { // only take the first one QUrl firstItem = event->mimeData()->urls().first(); QString path = (firstItem.scheme().compare("file", Qt::CaseInsensitive) == 0) @@ -174,7 +176,8 @@ void TorrentCreatorDialog::onCreateButtonClicked() // test if readable const QFileInfo fi(input); - if (!fi.isReadable()) { + if (!fi.isReadable()) + { QMessageBox::critical(this, tr("Torrent creation failed"), tr("Reason: Path to file/folder is not readable.")); return; } @@ -195,7 +198,8 @@ void TorrentCreatorDialog::onCreateButtonClicked() const QStringList trackers = m_ui->trackersList->toPlainText().trimmed() .replace(QRegularExpression("\n\n[\n]+"), "\n\n").split('\n'); - const BitTorrent::TorrentCreatorParams params { + const BitTorrent::TorrentCreatorParams params + { m_ui->checkPrivate->isChecked() #if (LIBTORRENT_VERSION_NUM >= 20000) , getTorrentFormat() @@ -227,10 +231,12 @@ void TorrentCreatorDialog::handleCreationSuccess(const QString &path, const QStr { // Remove busy cursor setCursor(QCursor(Qt::ArrowCursor)); - if (m_ui->checkStartSeeding->isChecked()) { + if (m_ui->checkStartSeeding->isChecked()) + { // Create save path temp data const BitTorrent::TorrentInfo info = BitTorrent::TorrentInfo::loadFromFile(Utils::Fs::toNativePath(path)); - if (!info.isValid()) { + if (!info.isValid()) + { QMessageBox::critical(this, tr("Torrent creation failed"), tr("Reason: Created torrent is invalid. It won't be added to download list.")); return; } @@ -238,7 +244,8 @@ void TorrentCreatorDialog::handleCreationSuccess(const QString &path, const QStr BitTorrent::AddTorrentParams params; params.savePath = branchPath; params.skipChecking = true; - if (m_ui->checkIgnoreShareLimits->isChecked()) { + if (m_ui->checkIgnoreShareLimits->isChecked()) + { params.ratioLimit = BitTorrent::TorrentHandle::NO_RATIO_LIMIT; params.seedingTimeLimit = BitTorrent::TorrentHandle::NO_SEEDING_TIME_LIMIT; } diff --git a/src/gui/trackerentriesdialog.cpp b/src/gui/trackerentriesdialog.cpp index f1dd8b33d..42be37240 100644 --- a/src/gui/trackerentriesdialog.cpp +++ b/src/gui/trackerentriesdialog.cpp @@ -63,7 +63,8 @@ void TrackerEntriesDialog::setTrackers(const QVector & int maxTier = -1; QHash tiers; // - for (const BitTorrent::TrackerEntry &entry : trackers) { + for (const BitTorrent::TrackerEntry &entry : trackers) + { tiers[entry.tier()] += (entry.url() + '\n'); maxTier = std::max(maxTier, entry.tier()); } @@ -85,10 +86,12 @@ QVector TrackerEntriesDialog::trackers() const entries.reserve(lines.size()); int tier = 0; - for (QStringRef line : lines) { + for (QStringRef line : lines) + { line = line.trimmed(); - if (line.isEmpty()) { + if (line.isEmpty()) + { ++tier; continue; } diff --git a/src/gui/transferlistdelegate.cpp b/src/gui/transferlistdelegate.cpp index eddbef7b8..318ef6f11 100644 --- a/src/gui/transferlistdelegate.cpp +++ b/src/gui/transferlistdelegate.cpp @@ -51,7 +51,8 @@ QSize TransferListDelegate::sizeHint(const QStyleOptionViewItem &option, const Q // This happens because icon from the 'name' column is no longer drawn. static int nameColHeight = -1; - if (nameColHeight == -1) { + if (nameColHeight == -1) + { const QModelIndex nameColumn = index.sibling(index.row(), TransferListModel::TR_NAME); nameColHeight = QStyledItemDelegate::sizeHint(option, nameColumn).height(); } diff --git a/src/gui/transferlistfilterswidget.cpp b/src/gui/transferlistfilterswidget.cpp index a69f63fb8..ed79b251e 100644 --- a/src/gui/transferlistfilterswidget.cpp +++ b/src/gui/transferlistfilterswidget.cpp @@ -128,7 +128,8 @@ BaseFilterWidget::BaseFilterWidget(QWidget *parent, TransferListWidget *transfer QSize BaseFilterWidget::sizeHint() const { - return { + return + { // Width should be exactly the width of the content sizeHintForColumn(0), // Height should be exactly the height of the content @@ -225,7 +226,8 @@ void StatusFilterWidget::updateTorrentNumbers() int nbErrored = 0; const QVector torrents = BitTorrent::Session::instance()->torrents(); - for (const BitTorrent::TorrentHandle *torrent : torrents) { + for (const BitTorrent::TorrentHandle *torrent : torrents) + { if (torrent->isDownloading()) ++nbDownloading; if (torrent->isUploading()) @@ -311,19 +313,23 @@ void TrackerFiltersList::addItem(const QString &tracker, const QString &hash) QString host = getHost(tracker); bool exists = m_trackers.contains(host); - if (exists) { + if (exists) + { tmp = m_trackers.value(host); if (tmp.contains(hash)) return; - if (host != "") { + if (host != "") + { trackerItem = item(rowFromTracker(host)); } - else { + else + { trackerItem = item(TRACKERLESS_ROW); } } - else { + else + { trackerItem = new QListWidgetItem(); trackerItem->setData(Qt::DecorationRole, UIThemeManager::instance()->getIcon("network-server")); @@ -334,7 +340,8 @@ void TrackerFiltersList::addItem(const QString &tracker, const QString &hash) tmp.append(hash); m_trackers.insert(host, tmp); - if (host == "") { + if (host == "") + { trackerItem->setText(tr("Trackerless (%1)").arg(tmp.size())); if (currentRow() == TRACKERLESS_ROW) applyFilter(TRACKERLESS_ROW); @@ -342,7 +349,8 @@ void TrackerFiltersList::addItem(const QString &tracker, const QString &hash) } trackerItem->setText(QString::fromLatin1("%1 (%2)").arg(host, QString::number(tmp.size()))); - if (exists) { + if (exists) + { if (currentRow() == rowFromTracker(host)) applyFilter(currentRow()); return; @@ -350,8 +358,10 @@ void TrackerFiltersList::addItem(const QString &tracker, const QString &hash) Q_ASSERT(count() >= 4); int insPos = count(); - for (int i = 4; i < count(); ++i) { - if (Utils::String::naturalLessThan(host, item(i)->text())) { + for (int i = 4; i < count(); ++i) + { + if (Utils::String::naturalLessThan(host, item(i)->text())) + { insPos = i; break; } @@ -371,12 +381,14 @@ void TrackerFiltersList::removeItem(const QString &tracker, const QString &hash) return; tmp.removeAll(hash); - if (!host.isEmpty()) { + if (!host.isEmpty()) + { // Remove from 'Error' and 'Warning' view trackerSuccess(hash, tracker); row = rowFromTracker(host); trackerItem = item(row); - if (tmp.empty()) { + if (tmp.empty()) + { if (currentRow() == row) setCurrentRow(0, QItemSelectionModel::SelectCurrent); delete trackerItem; @@ -387,7 +399,8 @@ void TrackerFiltersList::removeItem(const QString &tracker, const QString &hash) if (trackerItem) trackerItem->setText(QString::fromLatin1("%1 (%2)").arg(host, QString::number(tmp.size()))); } - else { + else + { row = 1; trackerItem = item(TRACKERLESS_ROW); trackerItem->setText(tr("Trackerless (%1)").arg(tmp.size())); @@ -411,10 +424,13 @@ void TrackerFiltersList::setDownloadTrackerFavicon(bool value) if (value == m_downloadTrackerFavicon) return; m_downloadTrackerFavicon = value; - if (m_downloadTrackerFavicon) { - for (auto i = m_trackers.cbegin(); i != m_trackers.cend(); ++i) { + if (m_downloadTrackerFavicon) + { + for (auto i = m_trackers.cbegin(); i != m_trackers.cend(); ++i) + { const QString &tracker = i.key(); - if (!tracker.isEmpty()) { + if (!tracker.isEmpty()) + { const QString scheme = getScheme(tracker); downloadFavicon(QString("%1://%2/favicon.ico") .arg((scheme.startsWith("http") ? scheme : "http"), getHost(tracker))); @@ -428,28 +444,34 @@ void TrackerFiltersList::trackerSuccess(const QString &hash, const QString &trac QStringList errored = m_errors.value(hash); QStringList warned = m_warnings.value(hash); - if (errored.contains(tracker)) { + if (errored.contains(tracker)) + { errored.removeAll(tracker); - if (errored.empty()) { + if (errored.empty()) + { m_errors.remove(hash); item(ERROR_ROW)->setText(tr("Error (%1)").arg(m_errors.size())); if (currentRow() == ERROR_ROW) applyFilter(ERROR_ROW); } - else { + else + { m_errors.insert(hash, errored); } } - if (warned.contains(tracker)) { + if (warned.contains(tracker)) + { warned.removeAll(tracker); - if (warned.empty()) { + if (warned.empty()) + { m_warnings.remove(hash); item(WARNING_ROW)->setText(tr("Warning (%1)").arg(m_warnings.size())); if (currentRow() == WARNING_ROW) applyFilter(WARNING_ROW); } - else { + else + { m_warnings.insert(hash, warned); } } @@ -495,7 +517,8 @@ void TrackerFiltersList::downloadFavicon(const QString &url) void TrackerFiltersList::handleFavicoDownloadFinished(const Net::DownloadResult &result) { - if (result.status != Net::DownloadStatus::Success) { + if (result.status != Net::DownloadStatus::Success) + { if (result.url.endsWith(".ico", Qt::CaseInsensitive)) downloadFavicon(result.url.left(result.url.size() - 4) + ".png"); return; @@ -503,7 +526,8 @@ void TrackerFiltersList::handleFavicoDownloadFinished(const Net::DownloadResult const QString host = getHost(result.url); - if (!m_trackers.contains(host)) { + if (!m_trackers.contains(host)) + { Utils::Fs::forceRemove(result.filePath); return; } @@ -515,12 +539,14 @@ void TrackerFiltersList::handleFavicoDownloadFinished(const Net::DownloadResult //Detect a non-decodable icon QList sizes = icon.availableSizes(); bool invalid = (sizes.isEmpty() || icon.pixmap(sizes.first()).isNull()); - if (invalid) { + if (invalid) + { if (result.url.endsWith(".ico", Qt::CaseInsensitive)) downloadFavicon(result.url.left(result.url.size() - 4) + ".png"); Utils::Fs::forceRemove(result.filePath); } - else { + else + { trackerItem->setData(Qt::DecorationRole, QIcon(result.filePath)); m_iconPaths.append(result.filePath); } @@ -612,7 +638,8 @@ QString TrackerFiltersList::getHost(const QString &tracker) const QStringList TrackerFiltersList::getHashes(const int row) const { - switch (row) { + switch (row) + { case TRACKERLESS_ROW: return m_trackers.value(""); case ERROR_ROW: diff --git a/src/gui/transferlistmodel.cpp b/src/gui/transferlistmodel.cpp index 8c871b8b8..f4992b8ea 100644 --- a/src/gui/transferlistmodel.cpp +++ b/src/gui/transferlistmodel.cpp @@ -92,7 +92,8 @@ namespace }; QHash colors; - for (const TorrentStateColorDescriptor &colorDescriptor : colorDescriptors) { + for (const TorrentStateColorDescriptor &colorDescriptor : colorDescriptors) + { const QColor themeColor = UIThemeManager::instance()->getColor(colorDescriptor.id, QColor()); if (themeColor.isValid()) colors.insert(colorDescriptor.state, themeColor); @@ -105,7 +106,8 @@ namespace TransferListModel::TransferListModel(QObject *parent) : QAbstractListModel {parent} - , m_statusStrings { + , m_statusStrings + { {BitTorrent::TorrentState::Downloading, tr("Downloading")}, {BitTorrent::TorrentState::StalledDownloading, tr("Stalled", "Torrent is waiting for download to begin")}, {BitTorrent::TorrentState::DownloadingMetadata, tr("Downloading metadata", "Used when loading a magnet link")}, @@ -158,9 +160,12 @@ int TransferListModel::columnCount(const QModelIndex &) const QVariant TransferListModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (orientation == Qt::Horizontal) { - if (role == Qt::DisplayRole) { - switch (section) { + if (orientation == Qt::Horizontal) + { + if (role == Qt::DisplayRole) + { + switch (section) + { case TR_QUEUE_POSITION: return QChar('#'); case TR_NAME: return tr("Name", "i.e: torrent name"); case TR_SIZE: return tr("Size", "i.e: torrent size"); @@ -195,8 +200,10 @@ QVariant TransferListModel::headerData(int section, Qt::Orientation orientation, default: return {}; } } - else if (role == Qt::TextAlignmentRole) { - switch (section) { + else if (role == Qt::TextAlignmentRole) + { + switch (section) + { case TR_AMOUNT_DOWNLOADED: case TR_AMOUNT_UPLOADED: case TR_AMOUNT_DOWNLOADED_SESSION: @@ -324,7 +331,8 @@ QString TransferListModel::displayValue(const BitTorrent::TorrentHandle *torrent : m_statusStrings[state]; }; - switch (column) { + switch (column) + { case TR_NAME: return torrent->name(); case TR_QUEUE_POSITION: @@ -394,7 +402,8 @@ QString TransferListModel::displayValue(const BitTorrent::TorrentHandle *torrent QVariant TransferListModel::internalValue(const BitTorrent::TorrentHandle *torrent, const int column, const bool alt) const { - switch (column) { + switch (column) + { case TR_NAME: return torrent->name(); case TR_QUEUE_POSITION: @@ -469,7 +478,8 @@ QVariant TransferListModel::data(const QModelIndex &index, const int role) const const BitTorrent::TorrentHandle *torrent = m_torrentList.value(index.row()); if (!torrent) return {}; - switch (role) { + switch (role) + { case Qt::ForegroundRole: return m_stateThemeColors.value(torrent->state(), getDefaultColorByState(torrent->state())); case Qt::DisplayRole: @@ -483,7 +493,8 @@ QVariant TransferListModel::data(const QModelIndex &index, const int role) const return getIconByState(torrent->state()); break; case Qt::ToolTipRole: - switch (index.column()) { + switch (index.column()) + { case TR_NAME: case TR_STATUS: case TR_CATEGORY: @@ -494,7 +505,8 @@ QVariant TransferListModel::data(const QModelIndex &index, const int role) const } break; case Qt::TextAlignmentRole: - switch (index.column()) { + switch (index.column()) + { case TR_AMOUNT_DOWNLOADED: case TR_AMOUNT_UPLOADED: case TR_AMOUNT_DOWNLOADED_SESSION: @@ -530,7 +542,8 @@ bool TransferListModel::setData(const QModelIndex &index, const QVariant &value, if (!torrent) return false; // Category and Name columns can be edited - switch (index.column()) { + switch (index.column()) + { case TR_NAME: torrent->setName(value.toString()); break; @@ -579,7 +592,8 @@ void TransferListModel::handleTorrentAboutToBeRemoved(BitTorrent::TorrentHandle beginRemoveRows({}, row, row); m_torrentList.removeAt(row); m_torrentMap.remove(torrent); - for (int &value : m_torrentMap) { + for (int &value : m_torrentMap) + { if (value > row) --value; } @@ -598,15 +612,18 @@ void TransferListModel::handleTorrentsUpdated(const QVector= 0); emit dataChanged(index(row, 0), index(row, columns)); } } - else { + else + { // save the overhead when more than half of the torrent list needs update emit dataChanged(index(0, 0), index((rowCount() - 1), columns)); } @@ -617,14 +634,16 @@ void TransferListModel::configure() const Preferences *pref = Preferences::instance(); HideZeroValuesMode hideZeroValuesMode = HideZeroValuesMode::Never; - if (pref->getHideZeroValues()) { + if (pref->getHideZeroValues()) + { if (pref->getHideZeroComboValues() == 1) hideZeroValuesMode = HideZeroValuesMode::Paused; else hideZeroValuesMode = HideZeroValuesMode::Always; } - if (m_hideZeroValuesMode != hideZeroValuesMode) { + if (m_hideZeroValuesMode != hideZeroValuesMode) + { m_hideZeroValuesMode = hideZeroValuesMode; emit dataChanged(index(0, 0), index((rowCount() - 1), (columnCount() - 1))); } @@ -634,7 +653,8 @@ void TransferListModel::configure() QIcon getIconByState(const BitTorrent::TorrentState state) { - switch (state) { + switch (state) + { case BitTorrent::TorrentState::Downloading: case BitTorrent::TorrentState::ForcedDownloading: case BitTorrent::TorrentState::DownloadingMetadata: @@ -673,7 +693,8 @@ QColor getDefaultColorByState(const BitTorrent::TorrentState state) // Color names taken from http://cloford.com/resources/colours/500col.htm bool dark = isDarkTheme(); - switch (state) { + switch (state) + { case BitTorrent::TorrentState::Downloading: case BitTorrent::TorrentState::ForcedDownloading: case BitTorrent::TorrentState::DownloadingMetadata: diff --git a/src/gui/transferlistsortmodel.cpp b/src/gui/transferlistsortmodel.cpp index c253d9b1b..9c72ce40e 100644 --- a/src/gui/transferlistsortmodel.cpp +++ b/src/gui/transferlistsortmodel.cpp @@ -112,7 +112,8 @@ bool TransferListSortModel::lessThan_impl(const QModelIndex &left, const QModelI const QVariant leftValue = left.data(TransferListModel::UnderlyingDataRole); const QVariant rightValue = right.data(TransferListModel::UnderlyingDataRole); - switch (sortColumn) { + switch (sortColumn) + { case TransferListModel::TR_CATEGORY: case TransferListModel::TR_TAGS: case TransferListModel::TR_NAME: @@ -132,27 +133,33 @@ bool TransferListSortModel::lessThan_impl(const QModelIndex &left, const QModelI case TransferListModel::TR_ADD_DATE: case TransferListModel::TR_SEED_DATE: - case TransferListModel::TR_SEEN_COMPLETE_DATE: { + case TransferListModel::TR_SEEN_COMPLETE_DATE: + { const QDateTime dateL = leftValue.toDateTime(); const QDateTime dateR = rightValue.toDateTime(); - if (dateL.isValid() && dateR.isValid()) { + if (dateL.isValid() && dateR.isValid()) + { if (dateL != dateR) return dateL < dateR; } - else if (dateL.isValid()) { + else if (dateL.isValid()) + { return true; } - else if (dateR.isValid()) { + else if (dateR.isValid()) + { return false; } return hashLessThan(); } - case TransferListModel::TR_QUEUE_POSITION: { + case TransferListModel::TR_QUEUE_POSITION: + { // QVariant has comparators for all basic types - if ((leftValue > 0) || (rightValue > 0)) { + if ((leftValue > 0) || (rightValue > 0)) + { if ((leftValue > 0) && (rightValue > 0)) return leftValue < rightValue; @@ -165,14 +172,17 @@ bool TransferListSortModel::lessThan_impl(const QModelIndex &left, const QModelI const QDateTime dateR = right.sibling(right.row(), TransferListModel::TR_SEED_DATE) .data(TransferListModel::UnderlyingDataRole).toDateTime(); - if (dateL.isValid() && dateR.isValid()) { + if (dateL.isValid() && dateR.isValid()) + { if (dateL != dateR) return dateL < dateR; } - else if (dateL.isValid()) { + else if (dateL.isValid()) + { return false; } - else if (dateR.isValid()) { + else if (dateR.isValid()) + { return true; } @@ -180,7 +190,8 @@ bool TransferListSortModel::lessThan_impl(const QModelIndex &left, const QModelI } case TransferListModel::TR_SEEDS: - case TransferListModel::TR_PEERS: { + case TransferListModel::TR_PEERS: + { // QVariant has comparators for all basic types // Active peers/seeds take precedence over total peers/seeds. if (leftValue != rightValue) @@ -194,7 +205,8 @@ bool TransferListSortModel::lessThan_impl(const QModelIndex &left, const QModelI return invokeLessThanForColumn(TransferListModel::TR_QUEUE_POSITION); } - case TransferListModel::TR_ETA: { + case TransferListModel::TR_ETA: + { // Sorting rules prioritized. // 1. Active torrents at the top // 2. Seeding torrents at the bottom @@ -215,7 +227,8 @@ bool TransferListSortModel::lessThan_impl(const QModelIndex &left, const QModelI .data(TransferListModel::UnderlyingDataRole).toInt(); const bool isSeedingL = (queuePosL < 0); const bool isSeedingR = (queuePosR < 0); - if (isSeedingL != isSeedingR) { + if (isSeedingL != isSeedingR) + { const bool isAscendingOrder = (sortOrder() == Qt::AscendingOrder); if (isSeedingL) return !isAscendingOrder; @@ -227,7 +240,8 @@ bool TransferListSortModel::lessThan_impl(const QModelIndex &left, const QModelI const qlonglong etaR = rightValue.toLongLong(); const bool isInvalidL = ((etaL < 0) || (etaL >= MAX_ETA)); const bool isInvalidR = ((etaR < 0) || (etaR >= MAX_ETA)); - if (isInvalidL && isInvalidR) { + if (isInvalidL && isInvalidR) + { if (isSeedingL) // Both seeding return invokeLessThanForColumn(TransferListModel::TR_SEED_DATE); diff --git a/src/gui/transferlistwidget.cpp b/src/gui/transferlistwidget.cpp index cb1e40521..91892600f 100644 --- a/src/gui/transferlistwidget.cpp +++ b/src/gui/transferlistwidget.cpp @@ -90,7 +90,8 @@ namespace if (!torrent->hasMetadata()) return false; - for (int i = 0; i < torrent->filesCount(); ++i) { + for (int i = 0; i < torrent->filesCount(); ++i) + { if (Utils::Misc::isPreviewable(Utils::Fs::fileExtension(torrent->fileName(i)))) return true; } @@ -159,7 +160,8 @@ TransferListWidget::TransferListWidget(QWidget *parent, MainWindow *mainWindow) header()->setStretchLastSection(false); // Default hidden columns - if (!columnLoaded) { + if (!columnLoaded) + { setColumnHidden(TransferListModel::TR_ADD_DATE, true); setColumnHidden(TransferListModel::TR_SEED_DATE, true); setColumnHidden(TransferListModel::TR_UPLIMIT, true); @@ -181,8 +183,10 @@ TransferListWidget::TransferListWidget(QWidget *parent, MainWindow *mainWindow) //Ensure that at least one column is visible at all times bool atLeastOne = false; - for (int i = 0; i < TransferListModel::NB_COLUMNS; ++i) { - if (!isColumnHidden(i)) { + for (int i = 0; i < TransferListModel::NB_COLUMNS; ++i) + { + if (!isColumnHidden(i)) + { atLeastOne = true; break; } @@ -275,7 +279,8 @@ void TransferListWidget::torrentDoubleClicked() else action = Preferences::instance()->getActionOnDblClOnTorrentDl(); - switch (action) { + switch (action) + { case TOGGLE_PAUSE: if (torrent->isPaused()) torrent->resume(); @@ -283,13 +288,15 @@ void TransferListWidget::torrentDoubleClicked() torrent->pause(); break; case PREVIEW_FILE: - if (torrentContainsPreviewableFiles(torrent)) { + if (torrentContainsPreviewableFiles(torrent)) + { auto *dialog = new PreviewSelectDialog(this, torrent); dialog->setAttribute(Qt::WA_DeleteOnClose); connect(dialog, &PreviewSelectDialog::readyToPreviewFile, this, &TransferListWidget::previewFile); dialog->show(); } - else { + else + { openDestinationFolder(torrent); } break; @@ -395,7 +402,8 @@ void TransferListWidget::deleteSelectedTorrents(const bool deleteLocalFiles) const QVector torrents = getSelectedTorrents(); if (torrents.empty()) return; - if (Preferences::instance()->confirmTorrentDeletion()) { + if (Preferences::instance()->confirmTorrentDeletion()) + { auto *dialog = new DeletionConfirmationDialog(this, torrents.size(), torrents[0]->name(), deleteLocalFiles); dialog->setAttribute(Qt::WA_DeleteOnClose); connect(dialog, &DeletionConfirmationDialog::accepted, this, [this, dialog]() @@ -406,7 +414,8 @@ void TransferListWidget::deleteSelectedTorrents(const bool deleteLocalFiles) }); dialog->open(); } - else { + else + { removeTorrents(torrents, deleteLocalFiles); } } @@ -416,7 +425,8 @@ void TransferListWidget::deleteVisibleTorrents() const QVector torrents = getVisibleTorrents(); if (torrents.empty()) return; - if (Preferences::instance()->confirmTorrentDeletion()) { + if (Preferences::instance()->confirmTorrentDeletion()) + { auto *dialog = new DeletionConfirmationDialog(this, torrents.size(), torrents[0]->name(), false); dialog->setAttribute(Qt::WA_DeleteOnClose); connect(dialog, &DeletionConfirmationDialog::accepted, this, [this, dialog]() @@ -427,7 +437,8 @@ void TransferListWidget::deleteVisibleTorrents() }); dialog->open(); } - else { + else + { removeTorrents(torrents, false); } } @@ -498,15 +509,18 @@ void TransferListWidget::openSelectedTorrentsFolder() const #ifdef Q_OS_MACOS // On macOS you expect both the files and folders to be opened in their parent // folders prehilighted for opening, so we use a custom method. - for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) { + for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) + { QString path = torrent->contentPath(true); pathsList.insert(path); } MacUtils::openFiles(pathsList); #else - for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) { + for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) + { QString path = torrent->contentPath(true); - if (!pathsList.contains(path)) { + if (!pathsList.contains(path)) + { if (torrent->filesCount() == 1) Utils::Gui::openFolderSelect(path); else @@ -519,14 +533,17 @@ void TransferListWidget::openSelectedTorrentsFolder() const void TransferListWidget::previewSelectedTorrents() { - for (const BitTorrent::TorrentHandle *torrent : asConst(getSelectedTorrents())) { - if (torrentContainsPreviewableFiles(torrent)) { + for (const BitTorrent::TorrentHandle *torrent : asConst(getSelectedTorrents())) + { + if (torrentContainsPreviewableFiles(torrent)) + { auto *dialog = new PreviewSelectDialog(this, torrent); dialog->setAttribute(Qt::WA_DeleteOnClose); connect(dialog, &PreviewSelectDialog::readyToPreviewFile, this, &TransferListWidget::previewFile); dialog->show(); } - else { + else + { QMessageBox::critical(this, tr("Unable to preview"), tr("The selected torrent \"%1\" does not contain previewable files") .arg(torrent->name())); } @@ -536,7 +553,8 @@ void TransferListWidget::previewSelectedTorrents() void TransferListWidget::setDlLimitSelectedTorrents() { QVector torrentsList; - for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) { + for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) + { if (torrent->isSeed()) continue; torrentsList += torrent; @@ -544,8 +562,10 @@ void TransferListWidget::setDlLimitSelectedTorrents() if (torrentsList.empty()) return; int oldLimit = torrentsList.first()->downloadLimit(); - for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) { - if (torrent->downloadLimit() != oldLimit) { + for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) + { + if (torrent->downloadLimit() != oldLimit) + { oldLimit = -1; break; } @@ -557,7 +577,8 @@ void TransferListWidget::setDlLimitSelectedTorrents() , BitTorrent::Session::instance()->globalDownloadSpeedLimit()); if (!ok) return; - for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) { + for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) + { qDebug("Applying download speed limit of %ld Kb/s to torrent %s", (newLimit / 1024l), qUtf8Printable(torrent->hash())); torrent->setDownloadLimit(newLimit); } @@ -569,8 +590,10 @@ void TransferListWidget::setUpLimitSelectedTorrents() if (torrentsList.empty()) return; int oldLimit = torrentsList.first()->uploadLimit(); - for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) { - if (torrent->uploadLimit() != oldLimit) { + for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) + { + if (torrent->uploadLimit() != oldLimit) + { oldLimit = -1; break; } @@ -582,7 +605,8 @@ void TransferListWidget::setUpLimitSelectedTorrents() , BitTorrent::Session::instance()->globalUploadSpeedLimit()); if (!ok) return; - for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) { + for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) + { qDebug("Applying upload speed limit of %ld Kb/s to torrent %s", (newLimit / 1024l), qUtf8Printable(torrent->hash())); torrent->setUploadLimit(newLimit); } @@ -611,7 +635,8 @@ void TransferListWidget::setMaxRatioSelectedTorrents() dialog->setAttribute(Qt::WA_DeleteOnClose); connect(dialog, &QDialog::accepted, this, [dialog, torrents]() { - for (BitTorrent::TorrentHandle *const torrent : torrents) { + for (BitTorrent::TorrentHandle *const torrent : torrents) + { const qreal ratio = (dialog->useDefault() ? BitTorrent::TorrentHandle::USE_GLOBAL_RATIO : dialog->ratio()); torrent->setRatioLimit(ratio); @@ -626,7 +651,8 @@ void TransferListWidget::setMaxRatioSelectedTorrents() void TransferListWidget::recheckSelectedTorrents() { - if (Preferences::instance()->confirmTorrentRecheck()) { + if (Preferences::instance()->confirmTorrentRecheck()) + { QMessageBox::StandardButton ret = QMessageBox::question(this, tr("Recheck confirmation"), tr("Are you sure you want to recheck the selected torrent(s)?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if (ret != QMessageBox::Yes) return; } @@ -648,7 +674,8 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&) menu->setAttribute(Qt::WA_DeleteOnClose); menu->setTitle(tr("Column visibility")); - for (int i = 0; i < m_listModel->columnCount(); ++i) { + for (int i = 0; i < m_listModel->columnCount(); ++i) + { if (!BitTorrent::Session::instance()->isQueueingSystemEnabled() && (i == TransferListModel::TR_QUEUE_POSITION)) continue; @@ -661,7 +688,8 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&) connect(menu, &QMenu::triggered, this, [this](const QAction *action) { int visibleCols = 0; - for (int i = 0; i < TransferListModel::NB_COLUMNS; ++i) { + for (int i = 0; i < TransferListModel::NB_COLUMNS; ++i) + { if (!isColumnHidden(i)) ++visibleCols; @@ -687,7 +715,8 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&) void TransferListWidget::setSelectedTorrentsSuperSeeding(const bool enabled) const { - for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) { + for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) + { if (torrent->hasMetadata()) torrent->setSuperSeeding(enabled); } @@ -730,10 +759,12 @@ void TransferListWidget::editTorrentTrackers() const QVector torrents = getSelectedTorrents(); QVector commonTrackers; - if (!torrents.empty()) { + if (!torrents.empty()) + { commonTrackers = torrents[0]->trackers(); - for (const BitTorrent::TorrentHandle *torrent : torrents) { + for (const BitTorrent::TorrentHandle *torrent : torrents) + { QSet trackerSet; for (const BitTorrent::TrackerEntry &entry : asConst(torrent->trackers())) @@ -771,7 +802,8 @@ QStringList TransferListWidget::askTagsForSelection(const QString &dialogTitle) { QStringList tags; bool invalid = true; - while (invalid) { + while (invalid) + { bool ok = false; invalid = false; const QString tagsInput = AutoExpandableDialog::getText( @@ -779,9 +811,11 @@ QStringList TransferListWidget::askTagsForSelection(const QString &dialogTitle) if (!ok || tagsInput.isEmpty()) return {}; tags = tagsInput.split(',', QString::SkipEmptyParts); - for (QString &tag : tags) { + for (QString &tag : tags) + { tag = tag.trimmed(); - if (!BitTorrent::Session::isValidTag(tag)) { + if (!BitTorrent::Session::isValidTag(tag)) + { QMessageBox::warning(this, tr("Invalid tag") , tr("Tag name: '%1' is invalid").arg(tag)); invalid = true; @@ -793,7 +827,8 @@ QStringList TransferListWidget::askTagsForSelection(const QString &dialogTitle) void TransferListWidget::applyToSelectedTorrents(const std::function &fn) { - for (const QModelIndex &index : asConst(selectionModel()->selectedRows())) { + for (const QModelIndex &index : asConst(selectionModel()->selectedRows())) + { BitTorrent::TorrentHandle *const torrent = m_listModel->torrentHandle(mapToSource(index)); Q_ASSERT(torrent); fn(torrent); @@ -812,7 +847,8 @@ void TransferListWidget::renameSelectedTorrent() // Ask for a new Name bool ok = false; QString name = AutoExpandableDialog::getText(this, tr("Rename"), tr("New name:"), QLineEdit::Normal, torrent->name(), &ok); - if (ok && !name.isEmpty()) { + if (ok && !name.isEmpty()) + { name.replace(QRegularExpression("\r?\n|\r"), " "); // Rename the torrent m_listModel->setData(mi, name, Qt::DisplayRole); @@ -918,7 +954,8 @@ void TransferListWidget::displayListMenu(const QPoint &) QSet tagsInAny; QSet tagsInAll; - for (const QModelIndex &index : selectedIndexes) { + for (const QModelIndex &index : selectedIndexes) + { // Get the file name // Get handle and pause the torrent const BitTorrent::TorrentHandle *torrent = m_listModel->torrentHandle(mapToSource(index)); @@ -931,11 +968,13 @@ void TransferListWidget::displayListMenu(const QPoint &) tagsInAny.unite(torrent->tags()); - if (first) { + if (first) + { firstAutoTMM = torrent->isAutoTMMEnabled(); tagsInAll = torrent->tags(); } - else { + else + { tagsInAll.intersect(torrent->tags()); } @@ -944,21 +983,26 @@ void TransferListWidget::displayListMenu(const QPoint &) if (torrent->hasMetadata()) oneHasMetadata = true; - if (!torrent->isSeed()) { + if (!torrent->isSeed()) + { oneNotSeed = true; - if (first) { + if (first) + { sequentialDownloadMode = torrent->isSequentialDownload(); prioritizeFirstLast = torrent->hasFirstLastPiecePriority(); } - else { + else + { if (sequentialDownloadMode != torrent->isSequentialDownload()) allSameSequentialDownloadMode = false; if (prioritizeFirstLast != torrent->hasFirstLastPiecePriority()) allSamePrioFirstlast = false; } } - else { - if (!oneNotSeed && allSameSuperSeeding && torrent->hasMetadata()) { + else + { + if (!oneNotSeed && allSameSuperSeeding && torrent->hasMetadata()) + { if (first) superSeedingMode = torrent->superSeeding(); else if (superSeedingMode != torrent->superSeeding()) @@ -976,7 +1020,8 @@ void TransferListWidget::displayListMenu(const QPoint &) else needsPause = true; - if (torrent->isErrored() || torrent->hasMissingFiles()) { + if (torrent->isErrored() || torrent->hasMissingFiles()) + { // If torrent is in "errored" or "missing files" state // it cannot keep further processing until you restart it. needsStart = true; @@ -990,7 +1035,8 @@ void TransferListWidget::displayListMenu(const QPoint &) if (oneHasMetadata && oneNotSeed && !allSameSequentialDownloadMode && !allSamePrioFirstlast && !allSameSuperSeeding && !allSameCategory - && needsStart && needsForce && needsPause && needsPreview && !allSameAutoTMM) { + && needsStart && needsForce && needsPause && needsPreview && !allSameAutoTMM) + { break; } } @@ -1023,11 +1069,13 @@ void TransferListWidget::displayListMenu(const QPoint &) categoryMenu->addSeparator(); - for (const QString &category : asConst(categories)) { + for (const QString &category : asConst(categories)) + { const QString escapedCategory = QString(category).replace('&', "&&"); // avoid '&' becomes accelerator key QAction *cat = new QAction(UIThemeManager::instance()->getIcon("inode-directory"), escapedCategory, categoryMenu); - if (allSameCategory && (category == firstCategory)) { + if (allSameCategory && (category == firstCategory)) + { cat->setCheckable(true); cat->setChecked(true); } @@ -1056,7 +1104,8 @@ void TransferListWidget::displayListMenu(const QPoint &) tagsMenu->addSeparator(); - for (const QString &tag : asConst(tags)) { + for (const QString &tag : asConst(tags)) + { auto *action = new TriStateAction(tag, tagsMenu); action->setCloseOnTriggered(false); @@ -1086,7 +1135,8 @@ void TransferListWidget::displayListMenu(const QPoint &) listMenu->addAction(actionSetDownloadLimit); listMenu->addAction(actionSetUploadLimit); listMenu->addAction(actionSetMaxRatio); - if (!oneNotSeed && oneHasMetadata) { + if (!oneNotSeed && oneHasMetadata) + { actionSuperSeedingMode->setCheckState(allSameSuperSeeding ? (superSeedingMode ? Qt::Checked : Qt::Unchecked) : Qt::PartiallyChecked); @@ -1094,11 +1144,13 @@ void TransferListWidget::displayListMenu(const QPoint &) } listMenu->addSeparator(); bool addedPreviewAction = false; - if (needsPreview) { + if (needsPreview) + { listMenu->addAction(actionPreviewFile); addedPreviewAction = true; } - if (oneNotSeed) { + if (oneNotSeed) + { actionSequentialDownload->setCheckState(allSameSequentialDownloadMode ? (sequentialDownloadMode ? Qt::Checked : Qt::Unchecked) : Qt::PartiallyChecked); @@ -1114,13 +1166,15 @@ void TransferListWidget::displayListMenu(const QPoint &) if (addedPreviewAction) listMenu->addSeparator(); - if (oneHasMetadata) { + if (oneHasMetadata) + { listMenu->addAction(actionForceRecheck); listMenu->addAction(actionForceReannounce); listMenu->addSeparator(); } listMenu->addAction(actionOpenDestinationFolder); - if (BitTorrent::Session::instance()->isQueueingSystemEnabled() && oneNotSeed) { + if (BitTorrent::Session::instance()->isQueueingSystemEnabled() && oneNotSeed) + { listMenu->addSeparator(); QMenu *queueMenu = listMenu->addMenu(tr("Queue")); queueMenu->addAction(actionTopQueuePos); @@ -1142,7 +1196,8 @@ void TransferListWidget::currentChanged(const QModelIndex ¤t, const QModel { qDebug("CURRENT CHANGED"); BitTorrent::TorrentHandle *torrent = nullptr; - if (current.isValid()) { + if (current.isValid()) + { torrent = m_listModel->torrentHandle(mapToSource(current)); // Scroll Fix scrollTo(current); @@ -1187,7 +1242,8 @@ void TransferListWidget::applyStatusFilter(int f) { m_sortFilterModel->setStatusFilter(static_cast(f)); // Select first item if nothing is selected - if (selectionModel()->selectedRows(0).empty() && (m_sortFilterModel->rowCount() > 0)) { + if (selectionModel()->selectedRows(0).empty() && (m_sortFilterModel->rowCount() > 0)) + { qDebug("Nothing is selected, selecting first row: %s", qUtf8Printable(m_sortFilterModel->index(0, TransferListModel::TR_NAME).data().toString())); selectionModel()->setCurrentIndex(m_sortFilterModel->index(0, TransferListModel::TR_NAME), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); } @@ -1205,7 +1261,8 @@ bool TransferListWidget::loadSettings() void TransferListWidget::wheelEvent(QWheelEvent *event) { - if (event->modifiers() & Qt::ShiftModifier) { + if (event->modifiers() & Qt::ShiftModifier) + { // Shift + scroll = horizontal scroll event->accept(); diff --git a/src/gui/tristatewidget.cpp b/src/gui/tristatewidget.cpp index ee5f92776..a4b8d7f25 100644 --- a/src/gui/tristatewidget.cpp +++ b/src/gui/tristatewidget.cpp @@ -74,7 +74,8 @@ void TriStateWidget::paintEvent(QPaintEvent *) opt.menuHasCheckableItems = true; opt.text = m_text; - switch (m_checkState) { + switch (m_checkState) + { case Qt::PartiallyChecked: opt.state |= QStyle::State_NoChange; break; @@ -87,7 +88,8 @@ void TriStateWidget::paintEvent(QPaintEvent *) }; if ((opt.state & QStyle::State_HasFocus) - || rect().contains(mapFromGlobal(QCursor::pos()))) { + || rect().contains(mapFromGlobal(QCursor::pos()))) + { opt.state |= QStyle::State_Selected; if (QApplication::mouseButtons() != Qt::NoButton) @@ -102,11 +104,13 @@ void TriStateWidget::mouseReleaseEvent(QMouseEvent *event) { toggleCheckState(); - if (m_closeOnTriggered) { + if (m_closeOnTriggered) + { // parent `triggered` signal will be emitted QWidget::mouseReleaseEvent(event); } - else { + else + { update(); // need to emit parent `triggered` signal manually emit triggered(m_checkState == Qt::Checked); @@ -116,10 +120,12 @@ void TriStateWidget::mouseReleaseEvent(QMouseEvent *event) void TriStateWidget::keyPressEvent(QKeyEvent *event) { if ((event->key() == Qt::Key_Return) - || (event->key() == Qt::Key_Enter)) { + || (event->key() == Qt::Key_Enter)) + { toggleCheckState(); - if (!m_closeOnTriggered) { + if (!m_closeOnTriggered) + { update(); // need to emit parent `triggered` signal manually emit triggered(m_checkState == Qt::Checked); @@ -132,7 +138,8 @@ void TriStateWidget::keyPressEvent(QKeyEvent *event) void TriStateWidget::toggleCheckState() { - switch (m_checkState) { + switch (m_checkState) + { case Qt::Unchecked: case Qt::PartiallyChecked: m_checkState = Qt::Checked; diff --git a/src/gui/uithememanager.cpp b/src/gui/uithememanager.cpp index 92fd26ba2..fa5017777 100644 --- a/src/gui/uithememanager.cpp +++ b/src/gui/uithememanager.cpp @@ -81,11 +81,14 @@ UIThemeManager::UIThemeManager() #endif { const Preferences *const pref = Preferences::instance(); - if (m_useCustomTheme) { - if (!QResource::registerResource(pref->customUIThemePath(), "/uitheme")) { + if (m_useCustomTheme) + { + if (!QResource::registerResource(pref->customUIThemePath(), "/uitheme")) + { LogMsg(tr("Failed to load UI theme from file: \"%1\"").arg(pref->customUIThemePath()), Log::WARNING); } - else { + else + { loadColorsFromJSONConfig(); applyPalette(); applyStyleSheet(); @@ -101,7 +104,8 @@ UIThemeManager *UIThemeManager::instance() void UIThemeManager::applyStyleSheet() const { QFile qssFile(":uitheme/stylesheet.qss"); - if (!qssFile.open(QIODevice::ReadOnly | QIODevice::Text)) { + if (!qssFile.open(QIODevice::ReadOnly | QIODevice::Text)) + { qApp->setStyleSheet({}); LogMsg(tr("Couldn't apply theme stylesheet. stylesheet.qss couldn't be opened. Reason: %1").arg(qssFile.errorString()) , Log::WARNING); @@ -114,7 +118,8 @@ void UIThemeManager::applyStyleSheet() const QIcon UIThemeManager::getIcon(const QString &iconId, const QString &fallback) const { #if (defined(Q_OS_UNIX) && !defined(Q_OS_MACOS)) - if (m_useSystemTheme) { + if (m_useSystemTheme) + { QIcon icon = QIcon::fromTheme(iconId); if (icon.name() != iconId) icon = QIcon::fromTheme(fallback, QIcon(getIconPathFromResources(iconId, fallback))); @@ -155,9 +160,11 @@ QColor UIThemeManager::getColor(const QString &id, const QColor &defaultColor) c QString UIThemeManager::getIconPath(const QString &iconId) const { #if (defined(Q_OS_UNIX) && !defined(Q_OS_MACOS)) - if (m_useSystemTheme) { + if (m_useSystemTheme) + { QString path = Utils::Fs::tempPath() + iconId + QLatin1String(".png"); - if (!QFile::exists(path)) { + if (!QFile::exists(path)) + { const QIcon icon = QIcon::fromTheme(iconId); if (!icon.isNull()) icon.pixmap(32).save(path); @@ -173,12 +180,14 @@ QString UIThemeManager::getIconPath(const QString &iconId) const QString UIThemeManager::getIconPathFromResources(const QString &iconId, const QString &fallback) const { - if (m_useCustomTheme) { + if (m_useCustomTheme) + { const QString customIcon = findIcon(iconId, THEME_ICONS_DIR); if (!customIcon.isEmpty()) return customIcon; - if (!fallback.isEmpty()) { + if (!fallback.isEmpty()) + { const QString fallbackIcon = findIcon(fallback, THEME_ICONS_DIR); if (!fallbackIcon.isEmpty()) return fallbackIcon; @@ -191,26 +200,31 @@ QString UIThemeManager::getIconPathFromResources(const QString &iconId, const QS void UIThemeManager::loadColorsFromJSONConfig() { QFile configFile(CONFIG_FILE_NAME); - if (!configFile.open(QIODevice::ReadOnly)) { + if (!configFile.open(QIODevice::ReadOnly)) + { LogMsg(tr("Failed to open \"%1\". Reason: %2").arg(CONFIG_FILE_NAME, configFile.errorString()), Log::WARNING); return; } QJsonParseError jsonError; const QJsonDocument configJsonDoc = QJsonDocument::fromJson(configFile.readAll(), &jsonError); - if (jsonError.error != QJsonParseError::NoError) { + if (jsonError.error != QJsonParseError::NoError) + { LogMsg(tr("\"%1\" has invalid format. Reason: %2").arg(CONFIG_FILE_NAME, jsonError.errorString()), Log::WARNING); return; } - if (!configJsonDoc.isObject()) { + if (!configJsonDoc.isObject()) + { LogMsg(tr("\"%1\" has invalid format. Reason: %2").arg(CONFIG_FILE_NAME, tr("Root JSON value is not an object")), Log::WARNING); return; } const QJsonObject colors = configJsonDoc.object().value("colors").toObject(); - for (auto color = colors.constBegin(); color != colors.constEnd(); ++color) { + for (auto color = colors.constBegin(); color != colors.constEnd(); ++color) + { const QColor providedColor(color.value().toString()); - if (!providedColor.isValid()) { + if (!providedColor.isValid()) + { LogMsg(tr("Invalid color for ID \"%1\" is provided by theme").arg(color.key()), Log::WARNING); continue; } @@ -257,7 +271,8 @@ void UIThemeManager::applyPalette() const }; QPalette palette = qApp->palette(); - for (const ColorDescriptor &colorDescriptor : paletteColorDescriptors) { + for (const ColorDescriptor &colorDescriptor : paletteColorDescriptors) + { const QColor defaultColor = palette.color(colorDescriptor.colorGroup, colorDescriptor.colorRole); const QColor newColor = getColor(colorDescriptor.id, defaultColor); palette.setColor(colorDescriptor.colorGroup, colorDescriptor.colorRole, newColor); diff --git a/src/gui/updownratiodialog.cpp b/src/gui/updownratiodialog.cpp index fad1f4fcc..fe75dbdb0 100644 --- a/src/gui/updownratiodialog.cpp +++ b/src/gui/updownratiodialog.cpp @@ -43,15 +43,18 @@ UpDownRatioDialog::UpDownRatioDialog(bool useDefault, qreal initialRatioValue, { m_ui->setupUi(this); - if (useDefault) { + if (useDefault) + { m_ui->useDefaultButton->setChecked(true); } - else if ((initialRatioValue == -1.) && (initialTimeValue == -1)) { + else if ((initialRatioValue == -1.) && (initialTimeValue == -1)) + { m_ui->noLimitButton->setChecked(true); initialRatioValue = BitTorrent::Session::instance()->globalMaxRatio(); initialTimeValue = BitTorrent::Session::instance()->globalMaxSeedingMinutes(); } - else { + else + { m_ui->torrentLimitButton->setChecked(true); if (initialRatioValue >= 0) diff --git a/src/gui/utils.cpp b/src/gui/utils.cpp index 53ec44f36..7bd1f5713 100644 --- a/src/gui/utils.cpp +++ b/src/gui/utils.cpp @@ -105,7 +105,8 @@ QPixmap Utils::Gui::scaledPixmapSvg(const QString &path, const QWidget *widget, QPixmap pm; QPixmapCache cache; - if (!cache.find(normalizedKey, &pm)) { + if (!cache.find(normalizedKey, &pm)) + { pm = QIcon(path).pixmap(scaledHeight); cache.insert(normalizedKey, pm); } @@ -178,7 +179,8 @@ void Utils::Gui::openFolderSelect(const QString &absolutePath) QString path {Utils::Fs::toUniformPath(absolutePath)}; const QFileInfo pathInfo {path}; // If the item to select doesn't exist, try to open its parent - if (!pathInfo.exists(path)) { + if (!pathInfo.exists(path)) + { openPath(path.left(path.lastIndexOf('/'))); return; } @@ -186,7 +188,8 @@ void Utils::Gui::openFolderSelect(const QString &absolutePath) #ifdef Q_OS_WIN HRESULT hresult = ::CoInitializeEx(nullptr, COINIT_MULTITHREADED); PIDLIST_ABSOLUTE pidl = ::ILCreateFromPathW(reinterpret_cast(Utils::Fs::toNativePath(path).utf16())); - if (pidl) { + if (pidl) + { ::SHOpenFolderAndSelectItems(pidl, 0, nullptr, 0); ::ILFree(pidl); } @@ -197,11 +200,13 @@ void Utils::Gui::openFolderSelect(const QString &absolutePath) proc.start("xdg-mime", {"query", "default", "inode/directory"}); proc.waitForFinished(); const QString output = proc.readLine().simplified(); - if ((output == "dolphin.desktop") || (output == "org.kde.dolphin.desktop")) { + if ((output == "dolphin.desktop") || (output == "org.kde.dolphin.desktop")) + { proc.startDetached("dolphin", {"--select", Utils::Fs::toNativePath(path)}); } else if ((output == "nautilus.desktop") || (output == "org.gnome.Nautilus.desktop") - || (output == "nautilus-folder-handler.desktop")) { + || (output == "nautilus-folder-handler.desktop")) + { if (pathInfo.isDir()) path = path.left(path.lastIndexOf('/')); proc.start("nautilus", {"--version"}); @@ -213,15 +218,18 @@ void Utils::Gui::openFolderSelect(const QString &absolutePath) else proc.startDetached("nautilus", {"--no-desktop", Utils::Fs::toNativePath(path)}); } - else if (output == "nemo.desktop") { + else if (output == "nemo.desktop") + { if (pathInfo.isDir()) path = path.left(path.lastIndexOf('/')); proc.startDetached("nemo", {"--no-desktop", Utils::Fs::toNativePath(path)}); } - else if ((output == "konqueror.desktop") || (output == "kfmclient_dir.desktop")) { + else if ((output == "konqueror.desktop") || (output == "kfmclient_dir.desktop")) + { proc.startDetached("konqueror", {"--select", Utils::Fs::toNativePath(path)}); } - else { + else + { // "caja" manager can't pinpoint the file, see: https://github.com/qbittorrent/qBittorrent/issues/5003 openPath(path.left(path.lastIndexOf('/'))); } diff --git a/src/webui/api/appcontroller.cpp b/src/webui/api/appcontroller.cpp index a750337c7..c50d7ce22 100644 --- a/src/webui/api/appcontroller.cpp +++ b/src/webui/api/appcontroller.cpp @@ -70,7 +70,8 @@ void AppController::versionAction() void AppController::buildInfoAction() { - const QJsonObject versions = { + const QJsonObject versions = + { {"qt", QT_VERSION_STR}, {"libtorrent", Utils::Misc::libtorrentVersionString()}, {"boost", Utils::Misc::boostVersionString()}, @@ -117,7 +118,8 @@ void AppController::preferencesAction() // Automatically add torrents from const QVariantHash dirs = pref->getScanDirs(); QJsonObject nativeDirs; - for (auto i = dirs.cbegin(); i != dirs.cend(); ++i) { + for (auto i = dirs.cbegin(); i != dirs.cend(); ++i) + { if (i.value().type() == QVariant::Int) nativeDirs.insert(Utils::Fs::toNativePath(i.key()), i.value().toInt()); else @@ -383,21 +385,25 @@ void AppController::setPreferencesAction() if (hasKey("export_dir_fin")) session->setFinishedTorrentExportDirectory(it.value().toString()); // Automatically add torrents from - if (hasKey("scan_dirs")) { + if (hasKey("scan_dirs")) + { const QVariantHash nativeDirs = it.value().toHash(); QVariantHash oldScanDirs = pref->getScanDirs(); QVariantHash scanDirs; ScanFoldersModel *model = ScanFoldersModel::instance(); - for (auto i = nativeDirs.cbegin(); i != nativeDirs.cend(); ++i) { + for (auto i = nativeDirs.cbegin(); i != nativeDirs.cend(); ++i) + { QString folder = Utils::Fs::toUniformPath(i.key()); int downloadType; QString downloadPath; ScanFoldersModel::PathStatus ec; - if (i.value().type() == QVariant::String) { + if (i.value().type() == QVariant::String) + { downloadType = ScanFoldersModel::CUSTOM_LOCATION; downloadPath = Utils::Fs::toUniformPath(i.value().toString()); } - else { + else + { downloadType = i.value().toInt(); downloadPath = (downloadType == ScanFoldersModel::DEFAULT_LOCATION) ? "Default folder" : "Watch folder"; } @@ -407,19 +413,23 @@ void AppController::setPreferencesAction() else ec = model->updatePath(folder, static_cast(downloadType), downloadPath); - if (ec == ScanFoldersModel::Ok) { + if (ec == ScanFoldersModel::Ok) + { scanDirs.insert(folder, (downloadType == ScanFoldersModel::CUSTOM_LOCATION) ? QVariant(downloadPath) : QVariant(downloadType)); qDebug("New watched folder: %s to %s", qUtf8Printable(folder), qUtf8Printable(downloadPath)); } - else { + else + { qDebug("Watched folder %s failed with error %d", qUtf8Printable(folder), ec); } } // Update deleted folders - for (auto i = oldScanDirs.cbegin(); i != oldScanDirs.cend(); ++i) { + for (auto i = oldScanDirs.cbegin(); i != oldScanDirs.cend(); ++i) + { const QString &folder = i.key(); - if (!scanDirs.contains(folder)) { + if (!scanDirs.contains(folder)) + { model->removePath(folder); qDebug("Removed watched folder %s", qUtf8Printable(folder)); } @@ -555,13 +565,15 @@ void AppController::setPreferencesAction() if (hasKey("slow_torrent_inactive_timer")) session->setSlowTorrentsInactivityTimer(it.value().toInt()); // Share Ratio Limiting - if (hasKey("max_ratio_enabled")) { + if (hasKey("max_ratio_enabled")) + { if (it.value().toBool()) session->setGlobalMaxRatio(m["max_ratio"].toReal()); else session->setGlobalMaxRatio(-1); } - if (hasKey("max_seeding_time_enabled")) { + if (hasKey("max_seeding_time_enabled")) + { if (it.value().toBool()) session->setGlobalMaxSeedingMinutes(m["max_seeding_time"].toInt()); else @@ -577,14 +589,18 @@ void AppController::setPreferencesAction() // Web UI // Language - if (hasKey("locale")) { + if (hasKey("locale")) + { QString locale = it.value().toString(); - if (pref->getLocale() != locale) { + if (pref->getLocale() != locale) + { auto *translator = new QTranslator; - if (translator->load(QLatin1String(":/lang/qbittorrent_") + locale)) { + if (translator->load(QLatin1String(":/lang/qbittorrent_") + locale)) + { qDebug("%s locale recognized, using translation.", qUtf8Printable(locale)); } - else { + else + { qDebug("%s locale unrecognized, using default (en).", qUtf8Printable(locale)); } qApp->installTranslator(translator); @@ -616,7 +632,8 @@ void AppController::setPreferencesAction() pref->setWebUiLocalAuthEnabled(!it.value().toBool()); if (hasKey("bypass_auth_subnet_whitelist_enabled")) pref->setWebUiAuthSubnetWhitelistEnabled(it.value().toBool()); - if (hasKey("bypass_auth_subnet_whitelist")) { + if (hasKey("bypass_auth_subnet_whitelist")) + { // recognize new lines and commas as delimiters pref->setWebUiAuthSubnetWhitelist(it.value().toString().split(QRegularExpression("\n|,"), QString::SkipEmptyParts)); } @@ -673,7 +690,8 @@ void AppController::setPreferencesAction() // Advanced settings // qBittorrent preferences // Current network interface - if (hasKey("current_network_interface")) { + if (hasKey("current_network_interface")) + { const QString ifaceValue {it.value().toString()}; const QList ifaces = QNetworkInterface::allInterfaces(); @@ -687,7 +705,8 @@ void AppController::setPreferencesAction() session->setNetworkInterfaceName(ifaceName); } // Current network interface address - if (hasKey("current_interface_address")) { + if (hasKey("current_interface_address")) + { const QHostAddress ifaceAddress {it.value().toString().trimmed()}; session->setNetworkInterfaceAddress(ifaceAddress.isNull() ? QString {} : ifaceAddress.toString()); } @@ -777,7 +796,8 @@ void AppController::setPreferencesAction() session->setAnnounceToAllTrackers(it.value().toBool()); if (hasKey("announce_to_all_tiers")) session->setAnnounceToAllTiers(it.value().toBool()); - if (hasKey("announce_ip")) { + if (hasKey("announce_ip")) + { const QHostAddress announceAddr {it.value().toString().trimmed()}; session->setAnnounceIP(announceAddr.isNull() ? QString {} : announceAddr.toString()); } @@ -805,9 +825,12 @@ void AppController::defaultSavePathAction() void AppController::networkInterfaceListAction() { QJsonArray ifaceList; - for (const QNetworkInterface &iface : asConst(QNetworkInterface::allInterfaces())) { - if (!iface.addressEntries().isEmpty()) { - ifaceList.append(QJsonObject { + for (const QNetworkInterface &iface : asConst(QNetworkInterface::allInterfaces())) + { + if (!iface.addressEntries().isEmpty()) + { + ifaceList.append(QJsonObject + { {"name", iface.humanReadableName()}, {"value", iface.name()} }); @@ -832,11 +855,13 @@ void AppController::networkInterfaceAddressListAction() addressList.append(addr.toString()); }; - if (ifaceName.isEmpty()) { + if (ifaceName.isEmpty()) + { for (const QHostAddress &addr : asConst(QNetworkInterface::allAddresses())) appendAddress(addr); } - else { + else + { const QNetworkInterface iface = QNetworkInterface::interfaceFromName(ifaceName); for (const QNetworkAddressEntry &entry : asConst(iface.addressEntries())) appendAddress(entry.ip()); diff --git a/src/webui/api/authcontroller.cpp b/src/webui/api/authcontroller.cpp index f8446145d..5dd63f8dd 100644 --- a/src/webui/api/authcontroller.cpp +++ b/src/webui/api/authcontroller.cpp @@ -38,7 +38,8 @@ void AuthController::loginAction() { - if (sessionManager()->session()) { + if (sessionManager()->session()) + { setResult(QLatin1String("Ok.")); return; } @@ -47,7 +48,8 @@ void AuthController::loginAction() const QString usernameFromWeb {params()["username"]}; const QString passwordFromWeb {params()["password"]}; - if (isBanned()) { + if (isBanned()) + { LogMsg(tr("WebAPI login failure. Reason: IP has been banned, IP: %1, username: %2") .arg(clientAddr, usernameFromWeb) , Log::WARNING); @@ -62,14 +64,16 @@ void AuthController::loginAction() const bool usernameEqual = Utils::Password::slowEquals(usernameFromWeb.toUtf8(), username.toUtf8()); const bool passwordEqual = Utils::Password::PBKDF2::verify(secret, passwordFromWeb); - if (usernameEqual && passwordEqual) { + if (usernameEqual && passwordEqual) + { m_clientFailedLogins.remove(clientAddr); sessionManager()->sessionStart(); setResult(QLatin1String("Ok.")); LogMsg(tr("WebAPI login success. IP: %1").arg(clientAddr)); } - else { + else + { if (Preferences::instance()->getWebUIMaxAuthFailCount() > 0) increaseFailedAttempts(); setResult(QLatin1String("Fails.")); @@ -91,7 +95,8 @@ bool AuthController::isBanned() const return false; bool isBanned = (failedLoginIter->banTimer.remainingTime() >= 0); - if (isBanned && failedLoginIter->banTimer.hasExpired()) { + if (isBanned && failedLoginIter->banTimer.hasExpired()) + { m_clientFailedLogins.erase(failedLoginIter); isBanned = false; } @@ -111,7 +116,8 @@ void AuthController::increaseFailedAttempts() FailedLogin &failedLogin = m_clientFailedLogins[sessionManager()->clientId()]; ++failedLogin.failedAttemptsCount; - if (failedLogin.failedAttemptsCount >= Preferences::instance()->getWebUIMaxAuthFailCount()) { + if (failedLogin.failedAttemptsCount >= Preferences::instance()->getWebUIMaxAuthFailCount()) + { // Max number of failed attempts reached // Start ban period failedLogin.banTimer.setRemainingTime(Preferences::instance()->getWebUIBanDuration()); diff --git a/src/webui/api/isessionmanager.h b/src/webui/api/isessionmanager.h index 1917f803d..389d86865 100644 --- a/src/webui/api/isessionmanager.h +++ b/src/webui/api/isessionmanager.h @@ -40,7 +40,8 @@ struct ISession virtual void setData(const QString &id, const QVariant &data) = 0; template - T getData(const QString &id) const { + T getData(const QString &id) const + { return this->getData(id).value(); } }; diff --git a/src/webui/api/logcontroller.cpp b/src/webui/api/logcontroller.cpp index 2ef0c3e3c..9941cd5c9 100644 --- a/src/webui/api/logcontroller.cpp +++ b/src/webui/api/logcontroller.cpp @@ -73,14 +73,16 @@ void LogController::mainAction() Logger *const logger = Logger::instance(); QJsonArray msgList; - for (const Log::Msg &msg : asConst(logger->getMessages(lastKnownId))) { + for (const Log::Msg &msg : asConst(logger->getMessages(lastKnownId))) + { if (!((msg.type == Log::NORMAL && isNormal) || (msg.type == Log::INFO && isInfo) || (msg.type == Log::WARNING && isWarning) || (msg.type == Log::CRITICAL && isCritical))) continue; - msgList.append(QJsonObject { + msgList.append(QJsonObject + { {KEY_LOG_ID, msg.id}, {KEY_LOG_TIMESTAMP, msg.timestamp}, {KEY_LOG_MSG_TYPE, msg.type}, @@ -113,8 +115,10 @@ void LogController::peersAction() Logger *const logger = Logger::instance(); QJsonArray peerList; - for (const Log::Peer &peer : asConst(logger->getPeers(lastKnownId))) { - peerList.append(QJsonObject { + for (const Log::Peer &peer : asConst(logger->getPeers(lastKnownId))) + { + peerList.append(QJsonObject + { {KEY_LOG_ID, peer.id}, {KEY_LOG_TIMESTAMP, peer.timestamp}, {KEY_LOG_PEER_IP, peer.ip}, diff --git a/src/webui/api/rsscontroller.cpp b/src/webui/api/rsscontroller.cpp index 862a19414..457cd7e6a 100644 --- a/src/webui/api/rsscontroller.cpp +++ b/src/webui/api/rsscontroller.cpp @@ -104,15 +104,18 @@ void RSSController::markAsReadAction() RSS::Item *item = RSS::Session::instance()->itemByPath(itemPath); if (!item) return; - if (!articleId.isNull()) { + if (!articleId.isNull()) + { RSS::Feed *feed = qobject_cast(item); - if (feed) { + if (feed) + { RSS::Article *article = feed->articleByGUID(articleId); if (article) article->markAsRead(); } } - else { + else + { item->markAsRead(); } } @@ -174,12 +177,14 @@ void RSSController::matchingArticlesAction() const RSS::AutoDownloadRule rule = RSS::AutoDownloader::instance()->ruleByName(ruleName); QJsonObject jsonObj; - for (const QString &feedURL : rule.feedURLs()) { + for (const QString &feedURL : rule.feedURLs()) + { const RSS::Feed *feed = RSS::Session::instance()->feedByURL(feedURL); if (!feed) continue; // feed doesn't exist QJsonArray matchingArticles; - for (const RSS::Article *article : feed->articles()) { + for (const RSS::Article *article : feed->articles()) + { if (rule.matches(article->data())) matchingArticles << article->title(); } diff --git a/src/webui/api/searchcontroller.cpp b/src/webui/api/searchcontroller.cpp index 6f8c9a7c6..b48c64ee0 100644 --- a/src/webui/api/searchcontroller.cpp +++ b/src/webui/api/searchcontroller.cpp @@ -68,14 +68,17 @@ namespace */ QJsonArray getPluginCategories(QStringList categories) { - QJsonArray categoriesInfo {QJsonObject { + QJsonArray categoriesInfo + {QJsonObject { {QLatin1String("id"), "all"}, {QLatin1String("name"), SearchPluginManager::categoryFullName("all")} }}; categories.sort(Qt::CaseInsensitive); - for (const QString &category : categories) { - categoriesInfo << QJsonObject { + for (const QString &category : categories) + { + categoriesInfo << QJsonObject + { {QLatin1String("id"), category}, {QLatin1String("name"), SearchPluginManager::categoryFullName(category)} }; @@ -97,7 +100,8 @@ void SearchController::startAction() const QStringList plugins = params()["plugins"].split('|'); QStringList pluginsToUse; - if (plugins.size() == 1) { + if (plugins.size() == 1) + { const QString pluginsLower = plugins[0].toLower(); if (pluginsLower == "all") pluginsToUse = SearchPluginManager::instance()->allPlugins(); @@ -106,7 +110,8 @@ void SearchController::startAction() else pluginsToUse << plugins; } - else { + else + { pluginsToUse << plugins; } @@ -144,7 +149,8 @@ void SearchController::stopAction() const SearchHandlerPtr searchHandler = searchHandlers[id]; - if (searchHandler->isActive()) { + if (searchHandler->isActive()) + { searchHandler->cancelSearch(); removeActiveSearch(session, id); } @@ -161,9 +167,11 @@ void SearchController::statusAction() QJsonArray statusArray; const QList searchIds {(id == 0) ? searchHandlers.keys() : QList {id}}; - for (const int searchId : searchIds) { + for (const int searchId : searchIds) + { const SearchHandlerPtr searchHandler = searchHandlers[searchId]; - statusArray << QJsonObject { + statusArray << QJsonObject + { {"id", searchId}, {"status", searchHandler->isActive() ? "Running" : "Stopped"}, {"total", searchHandler->results().size()} @@ -271,7 +279,8 @@ void SearchController::updatePluginsAction() void SearchController::checkForUpdatesFinished(const QHash &updateInfo) { - if (updateInfo.isEmpty()) { + if (updateInfo.isEmpty()) + { LogMsg(tr("All plugins are already up to date."), Log::INFO); return; } @@ -279,7 +288,8 @@ void SearchController::checkForUpdatesFinished(const QHashupdatePlugin(pluginName); } @@ -328,8 +338,10 @@ int SearchController::generateSearchId() const QJsonObject SearchController::getResults(const QList &searchResults, const bool isSearchActive, const int totalResults) const { QJsonArray searchResultsArray; - for (const SearchResult &searchResult : searchResults) { - searchResultsArray << QJsonObject { + for (const SearchResult &searchResult : searchResults) + { + searchResultsArray << QJsonObject + { {"fileName", searchResult.fileName}, {"fileUrl", searchResult.fileUrl}, {"fileSize", searchResult.fileSize}, @@ -340,7 +352,8 @@ QJsonObject SearchController::getResults(const QList &searchResult }; } - const QJsonObject result = { + const QJsonObject result = + { {"status", isSearchActive ? "Running" : "Stopped"}, {"results", searchResultsArray}, {"total", totalResults} @@ -366,10 +379,12 @@ QJsonArray SearchController::getPluginsInfo(const QStringList &plugins) const { QJsonArray pluginsArray; - for (const QString &plugin : plugins) { + for (const QString &plugin : plugins) + { const PluginInfo *const pluginInfo = SearchPluginManager::instance()->pluginInfo(plugin); - pluginsArray << QJsonObject { + pluginsArray << QJsonObject + { {"name", pluginInfo->name}, {"version", QString(pluginInfo->version)}, {"fullName", pluginInfo->fullName}, diff --git a/src/webui/api/serialize/serialize_torrent.cpp b/src/webui/api/serialize/serialize_torrent.cpp index d4e992d87..2bae34570 100644 --- a/src/webui/api/serialize/serialize_torrent.cpp +++ b/src/webui/api/serialize/serialize_torrent.cpp @@ -39,7 +39,8 @@ namespace { QString torrentStateToString(const BitTorrent::TorrentState state) { - switch (state) { + switch (state) + { case BitTorrent::TorrentState::Error: return QLatin1String("error"); case BitTorrent::TorrentState::MissingFiles: @@ -82,7 +83,8 @@ namespace QVariantMap serialize(const BitTorrent::TorrentHandle &torrent) { - QVariantMap ret = { + QVariantMap ret = + { {KEY_TORRENT_HASH, QString(torrent.hash())}, {KEY_TORRENT_NAME, torrent.name()}, {KEY_TORRENT_MAGNET_URI, torrent.createMagnetURI()}, @@ -134,10 +136,12 @@ QVariantMap serialize(const BitTorrent::TorrentHandle &torrent) const qreal ratio = torrent.realRatio(); ret[KEY_TORRENT_RATIO] = (ratio > BitTorrent::TorrentHandle::MAX_RATIO) ? -1 : ratio; - if (torrent.isPaused() || torrent.isChecking()) { + if (torrent.isPaused() || torrent.isChecking()) + { ret[KEY_TORRENT_LAST_ACTIVITY_TIME] = 0; } - else { + else + { const qint64 dt = (QDateTime::currentDateTime().toSecsSinceEpoch() - torrent.timeSinceActivity()); ret[KEY_TORRENT_LAST_ACTIVITY_TIME] = dt; diff --git a/src/webui/api/synccontroller.cpp b/src/webui/api/synccontroller.cpp index e5b30785e..b333b7db7 100644 --- a/src/webui/api/synccontroller.cpp +++ b/src/webui/api/synccontroller.cpp @@ -164,20 +164,24 @@ namespace // initialize output variable syncData.clear(); - for (auto i = data.cbegin(); i != data.cend(); ++i) { + for (auto i = data.cbegin(); i != data.cend(); ++i) + { const QString &key = i.key(); const QVariant &value = i.value(); QVariantList removedItems; - switch (static_cast(value.type())) { - case QMetaType::QVariantMap: { + switch (static_cast(value.type())) + { + case QMetaType::QVariantMap: + { QVariantMap map; processMap(prevData[key].toMap(), value.toMap(), map); if (!map.isEmpty()) syncData[key] = map; } break; - case QMetaType::QVariantHash: { + case QMetaType::QVariantHash: + { QVariantMap map; processHash(prevData[key].toHash(), value.toHash(), map, removedItems); if (!map.isEmpty()) @@ -186,7 +190,8 @@ namespace syncData[key + KEY_SUFFIX_REMOVED] = removedItems; } break; - case QMetaType::QVariantList: { + case QMetaType::QVariantList: + { QVariantList list; processList(prevData[key].toList(), value.toList(), list, removedItems); if (!list.isEmpty()) @@ -225,42 +230,52 @@ namespace syncData.clear(); removedItems.clear(); - if (prevData.isEmpty()) { + if (prevData.isEmpty()) + { // If list was empty before, then difference is a whole new list. for (auto i = data.cbegin(); i != data.cend(); ++i) syncData[i.key()] = i.value(); } - else { - for (auto i = data.cbegin(); i != data.cend(); ++i) { - switch (i.value().type()) { + else + { + for (auto i = data.cbegin(); i != data.cend(); ++i) + { + switch (i.value().type()) + { case QVariant::Map: - if (!prevData.contains(i.key())) { + if (!prevData.contains(i.key())) + { // new list item found - append it to syncData syncData[i.key()] = i.value(); } - else { + else + { QVariantMap map; processMap(prevData[i.key()].toMap(), i.value().toMap(), map); // existing list item found - remove it from prevData prevData.remove(i.key()); - if (!map.isEmpty()) { + if (!map.isEmpty()) + { // changed list item found - append its changes to syncData syncData[i.key()] = map; } } break; case QVariant::StringList: - if (!prevData.contains(i.key())) { + if (!prevData.contains(i.key())) + { // new list item found - append it to syncData syncData[i.key()] = i.value(); } - else { + else + { QVariantList list; QVariantList removedList; processList(prevData[i.key()].toList(), i.value().toList(), list, removedList); // existing list item found - remove it from prevData prevData.remove(i.key()); - if (!list.isEmpty() || !removedList.isEmpty()) { + if (!list.isEmpty() || !removedList.isEmpty()) + { // changed list item found - append entire list to syncData syncData[i.key()] = i.value(); } @@ -271,7 +286,8 @@ namespace } } - if (!prevData.isEmpty()) { + if (!prevData.isEmpty()) + { // prevData contains only items that are missing now - // put them in removedItems for (auto i = prevData.cbegin(); i != prevData.cend(); ++i) @@ -287,12 +303,15 @@ namespace syncData.clear(); removedItems.clear(); - if (prevData.isEmpty()) { + if (prevData.isEmpty()) + { // If list was empty before, then difference is a whole new list. syncData = data; } - else { - for (const QVariant &item : data) { + else + { + for (const QVariant &item : data) + { if (!prevData.contains(item)) // new list item found - append it to syncData syncData.append(item); @@ -313,7 +332,8 @@ namespace QVariantMap syncData; bool fullUpdate = true; int lastResponseId = 0; - if (acceptedResponseId > 0) { + if (acceptedResponseId > 0) + { lastResponseId = lastData[KEY_RESPONSE_ID].toInt(); if (lastResponseId == acceptedResponseId) @@ -321,13 +341,15 @@ namespace int lastAcceptedResponseId = lastAcceptedData[KEY_RESPONSE_ID].toInt(); - if (lastAcceptedResponseId == acceptedResponseId) { + if (lastAcceptedResponseId == acceptedResponseId) + { processMap(lastAcceptedData, data, syncData); fullUpdate = false; } } - if (fullUpdate) { + if (fullUpdate) + { lastAcceptedData.clear(); syncData = data; syncData[KEY_FULL_UPDATE] = true; @@ -436,7 +458,8 @@ void SyncController::maindataAction() QVariantHash torrents; QHash trackers; - for (const BitTorrent::TorrentHandle *torrent : asConst(session->torrents())) { + for (const BitTorrent::TorrentHandle *torrent : asConst(session->torrents())) + { const BitTorrent::InfoHash torrentHash = torrent->hash(); QVariantMap map = serialize(*torrent); @@ -445,15 +468,18 @@ void SyncController::maindataAction() // Calculated last activity time can differ from actual value by up to 10 seconds (this is a libtorrent issue). // So we don't need unnecessary updates of last activity time in response. const auto iterTorrents = lastResponse.find("torrents"); - if (iterTorrents != lastResponse.end()) { + if (iterTorrents != lastResponse.end()) + { const QVariantHash lastResponseTorrents = iterTorrents->toHash(); const auto iterHash = lastResponseTorrents.find(torrentHash); - if (iterHash != lastResponseTorrents.end()) { + if (iterHash != lastResponseTorrents.end()) + { const QVariantMap torrentData = iterHash->toMap(); const auto iterLastActivity = torrentData.find(KEY_TORRENT_LAST_ACTIVITY_TIME); - if (iterLastActivity != torrentData.end()) { + if (iterLastActivity != torrentData.end()) + { const int lastValue = iterLastActivity->toInt(); if (qAbs(lastValue - map[KEY_TORRENT_LAST_ACTIVITY_TIME].toInt()) < 15) map[KEY_TORRENT_LAST_ACTIVITY_TIME] = lastValue; @@ -470,9 +496,11 @@ void SyncController::maindataAction() QVariantHash categories; const QStringMap categoriesList = session->categories(); - for (auto it = categoriesList.cbegin(); it != categoriesList.cend(); ++it) { + for (auto it = categoriesList.cbegin(); it != categoriesList.cend(); ++it) + { const QString &key = it.key(); - categories[key] = QVariantMap { + categories[key] = QVariantMap + { {"name", key}, {"savePath", it.value()} }; @@ -485,7 +513,8 @@ void SyncController::maindataAction() data["tags"] = tags; QVariantHash trackersHash; - for (auto i = trackers.constBegin(); i != trackers.constEnd(); ++i) { + for (auto i = trackers.constBegin(); i != trackers.constEnd(); ++i) + { trackersHash[i.key()] = i.value(); } data["trackers"] = trackersHash; @@ -526,10 +555,12 @@ void SyncController::torrentPeersAction() data[KEY_SYNC_TORRENT_PEERS_SHOW_FLAGS] = resolvePeerCountries; - for (const BitTorrent::PeerInfo &pi : peersList) { + for (const BitTorrent::PeerInfo &pi : peersList) + { if (pi.address().ip.isNull()) continue; - QVariantMap peer = { + QVariantMap peer = + { {KEY_PEER_IP, pi.address().ip.toString()}, {KEY_PEER_PORT, pi.address().port}, {KEY_PEER_CLIENT, pi.client()}, @@ -545,7 +576,8 @@ void SyncController::torrentPeersAction() {KEY_PEER_FILES, torrent->info().filesForPiece(pi.downloadingPieceIndex()).join('\n')} }; - if (resolvePeerCountries) { + if (resolvePeerCountries) + { peer[KEY_PEER_COUNTRY_CODE] = pi.country().toLower(); peer[KEY_PEER_COUNTRY] = Net::GeoIPManager::CountryName(pi.country()); } @@ -563,7 +595,8 @@ void SyncController::torrentPeersAction() qint64 SyncController::getFreeDiskSpace() { - if (m_freeDiskSpaceElapsedTimer.hasExpired(FREEDISKSPACE_CHECK_TIMEOUT)) { + if (m_freeDiskSpaceElapsedTimer.hasExpired(FREEDISKSPACE_CHECK_TIMEOUT)) + { invokeChecker(); m_freeDiskSpaceElapsedTimer.restart(); } diff --git a/src/webui/api/torrentscontroller.cpp b/src/webui/api/torrentscontroller.cpp index 5082fd73f..0ca427db3 100644 --- a/src/webui/api/torrentscontroller.cpp +++ b/src/webui/api/torrentscontroller.cpp @@ -121,12 +121,15 @@ namespace void applyToTorrents(const QStringList &hashes, const std::function &func) { - if ((hashes.size() == 1) && (hashes[0] == QLatin1String("all"))) { + if ((hashes.size() == 1) && (hashes[0] == QLatin1String("all"))) + { for (BitTorrent::TorrentHandle *const torrent : asConst(BitTorrent::Session::instance()->torrents())) func(torrent); } - else { - for (const QString &hash : hashes) { + else + { + for (const QString &hash : hashes) + { BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(hash); if (torrent) func(torrent); @@ -137,10 +140,12 @@ namespace QJsonArray getStickyTrackers(const BitTorrent::TorrentHandle *const torrent) { int seedsDHT = 0, seedsPeX = 0, seedsLSD = 0, leechesDHT = 0, leechesPeX = 0, leechesLSD = 0; - for (const BitTorrent::PeerInfo &peer : asConst(torrent->peers())) { + for (const BitTorrent::PeerInfo &peer : asConst(torrent->peers())) + { if (peer.isConnecting()) continue; - if (peer.isSeed()) { + if (peer.isSeed()) + { if (peer.fromDHT()) ++seedsDHT; if (peer.fromPeX()) @@ -148,7 +153,8 @@ namespace if (peer.fromLSD()) ++seedsLSD; } - else { + else + { if (peer.fromDHT()) ++leechesDHT; if (peer.fromPeX()) @@ -164,7 +170,8 @@ namespace const QString privateMsg {QCoreApplication::translate("TrackerListWidget", "This torrent is private")}; const bool isTorrentPrivate = torrent->isPrivate(); - const QJsonObject dht { + const QJsonObject dht + { {KEY_TRACKER_URL, "** [DHT] **"}, {KEY_TRACKER_TIER, ""}, {KEY_TRACKER_MSG, (isTorrentPrivate ? privateMsg : "")}, @@ -175,7 +182,8 @@ namespace {KEY_TRACKER_LEECHES_COUNT, leechesDHT} }; - const QJsonObject pex { + const QJsonObject pex + { {KEY_TRACKER_URL, "** [PeX] **"}, {KEY_TRACKER_TIER, ""}, {KEY_TRACKER_MSG, (isTorrentPrivate ? privateMsg : "")}, @@ -186,7 +194,8 @@ namespace {KEY_TRACKER_LEECHES_COUNT, leechesPeX} }; - const QJsonObject lsd { + const QJsonObject lsd + { {KEY_TRACKER_URL, "** [LSD] **"}, {KEY_TRACKER_TIER, ""}, {KEY_TRACKER_MSG, (isTorrentPrivate ? privateMsg : "")}, @@ -251,7 +260,8 @@ void TorrentsController::infoAction() QVariantList torrentList; TorrentFilter torrentFilter(filter, (hashSet.isEmpty() ? TorrentFilter::AnyHash : hashSet), category); - for (BitTorrent::TorrentHandle *const torrent : asConst(BitTorrent::Session::instance()->torrents())) { + for (BitTorrent::TorrentHandle *const torrent : asConst(BitTorrent::Session::instance()->torrents())) + { if (torrentFilter.match(torrent)) torrentList.append(serialize(*torrent)); } @@ -358,12 +368,14 @@ void TorrentsController::propertiesAction() dataDict[KEY_PROP_PIECES_HAVE] = torrent->piecesHave(); dataDict[KEY_PROP_CREATED_BY] = torrent->creator(); dataDict[KEY_PROP_ADDITION_DATE] = static_cast(torrent->addedTime().toSecsSinceEpoch()); - if (torrent->hasMetadata()) { + if (torrent->hasMetadata()) + { dataDict[KEY_PROP_LAST_SEEN] = torrent->lastSeenComplete().isValid() ? torrent->lastSeenComplete().toSecsSinceEpoch() : -1; dataDict[KEY_PROP_COMPLETION_DATE] = torrent->completedTime().isValid() ? torrent->completedTime().toSecsSinceEpoch() : -1; dataDict[KEY_PROP_CREATION_DATE] = static_cast(torrent->creationDate().toSecsSinceEpoch()); } - else { + else + { dataDict[KEY_PROP_LAST_SEEN] = -1; dataDict[KEY_PROP_COMPLETION_DATE] = -1; dataDict[KEY_PROP_CREATION_DATE] = -1; @@ -397,10 +409,12 @@ void TorrentsController::trackersAction() QJsonArray trackerList = getStickyTrackers(torrent); QHash trackersData = torrent->trackerInfos(); - for (const BitTorrent::TrackerEntry &tracker : asConst(torrent->trackers())) { + for (const BitTorrent::TrackerEntry &tracker : asConst(torrent->trackers())) + { const BitTorrent::TrackerInfo data = trackersData.value(tracker.url()); - trackerList << QJsonObject { + trackerList << QJsonObject + { {KEY_TRACKER_URL, tracker.url()}, {KEY_TRACKER_TIER, tracker.tier()}, {KEY_TRACKER_STATUS, static_cast(tracker.status())}, @@ -429,8 +443,10 @@ void TorrentsController::webseedsAction() throw APIError(APIErrorType::NotFound); QJsonArray webSeedList; - for (const QUrl &webseed : asConst(torrent->urlSeeds())) { - webSeedList.append(QJsonObject { + for (const QUrl &webseed : asConst(torrent->urlSeeds())) + { + webSeedList.append(QJsonObject + { {KEY_WEBSEED_URL, webseed.toString()} }); } @@ -458,13 +474,16 @@ void TorrentsController::filesAction() throw APIError(APIErrorType::NotFound); QJsonArray fileList; - if (torrent->hasMetadata()) { + if (torrent->hasMetadata()) + { const QVector priorities = torrent->filePriorities(); const QVector fp = torrent->filesProgress(); const QVector fileAvailability = torrent->availableFileFractions(); const BitTorrent::TorrentInfo info = torrent->info(); - for (int i = 0; i < torrent->filesCount(); ++i) { - QJsonObject fileDict = { + for (int i = 0; i < torrent->filesCount(); ++i) + { + QJsonObject fileDict = + { {KEY_FILE_PROGRESS, fp[i]}, {KEY_FILE_PRIORITY, static_cast(priorities[i])}, {KEY_FILE_SIZE, torrent->fileSize(i)}, @@ -528,7 +547,8 @@ void TorrentsController::pieceStatesAction() pieceStates.append(static_cast(states[i]) * 2); const QBitArray dlstates = torrent->downloadingPieces(); - for (int i = 0; i < states.size(); ++i) { + for (int i = 0; i < states.size(); ++i) + { if (dlstates[i]) pieceStates[i] = 1; } @@ -554,12 +574,15 @@ void TorrentsController::addAction() const TriStateBool autoTMM = parseTriStateBool(params()["autoTMM"]); QList cookies; - if (!cookie.isEmpty()) { + if (!cookie.isEmpty()) + { const QStringList cookiesStr = cookie.split("; "); - for (QString cookieStr : cookiesStr) { + for (QString cookieStr : cookiesStr) + { cookieStr = cookieStr.trimmed(); int index = cookieStr.indexOf('='); - if (index > 1) { + if (index > 1) + { QByteArray name = cookieStr.left(index).toLatin1(); QByteArray value = cookieStr.right(cookieStr.length() - index - 1).toLatin1(); cookies += QNetworkCookie(name, value); @@ -582,17 +605,21 @@ void TorrentsController::addAction() params.useAutoTMM = autoTMM; bool partialSuccess = false; - for (QString url : asConst(urls.split('\n'))) { + for (QString url : asConst(urls.split('\n'))) + { url = url.trimmed(); - if (!url.isEmpty()) { + if (!url.isEmpty()) + { Net::DownloadManager::instance()->setCookiesFromUrl(cookies, QUrl::fromEncoded(url.toUtf8())); partialSuccess |= BitTorrent::Session::instance()->addTorrent(url, params); } } - for (auto it = data().constBegin(); it != data().constEnd(); ++it) { + for (auto it = data().constBegin(); it != data().constEnd(); ++it) + { const BitTorrent::TorrentInfo torrentInfo = BitTorrent::TorrentInfo::load(it.value()); - if (!torrentInfo.isValid()) { + if (!torrentInfo.isValid()) + { throw APIError(APIErrorType::BadData , tr("Error: '%1' is not a valid torrent file.").arg(it.key())); } @@ -616,7 +643,8 @@ void TorrentsController::addTrackersAction() throw APIError(APIErrorType::NotFound); QVector trackers; - for (const QString &urlStr : asConst(params()["urls"].split('\n'))) { + for (const QString &urlStr : asConst(params()["urls"].split('\n'))) + { const QUrl url {urlStr.trimmed()}; if (url.isValid()) trackers << url.toString(); @@ -645,11 +673,13 @@ void TorrentsController::editTrackerAction() QVector trackers = torrent->trackers(); bool match = false; - for (BitTorrent::TrackerEntry &tracker : trackers) { + for (BitTorrent::TrackerEntry &tracker : trackers) + { const QUrl trackerUrl(tracker.url()); if (trackerUrl == newTrackerUrl) throw APIError(APIErrorType::Conflict, "New tracker URL already exists"); - if (trackerUrl == origTrackerUrl) { + if (trackerUrl == origTrackerUrl) + { match = true; BitTorrent::TrackerEntry newTracker(newTrackerUrl.toString()); newTracker.setTier(tracker.tier()); @@ -679,7 +709,8 @@ void TorrentsController::removeTrackersAction() const QVector trackers = torrent->trackers(); QVector remainingTrackers; remainingTrackers.reserve(trackers.size()); - for (const BitTorrent::TrackerEntry &entry : trackers) { + for (const BitTorrent::TrackerEntry &entry : trackers) + { if (!urls.contains(entry.url())) remainingTrackers.push_back(entry); } @@ -702,7 +733,8 @@ void TorrentsController::addPeersAction() QVector peerList; peerList.reserve(peers.size()); - for (const QString &peer : peers) { + for (const QString &peer : peers) + { const BitTorrent::PeerAddress addr = BitTorrent::PeerAddress::parse(peer.trimmed()); if (!addr.ip.isNull()) peerList.append(addr); @@ -720,7 +752,8 @@ void TorrentsController::addPeersAction() return torrent->connectPeer(peer); }); - results[torrent->hash()] = QJsonObject { + results[torrent->hash()] = QJsonObject + { {"added", peersAdded}, {"failed", (peers.size() - peersAdded)} }; @@ -767,14 +800,16 @@ void TorrentsController::filePrioAction() const int filesCount = torrent->filesCount(); QVector priorities = torrent->filePriorities(); bool priorityChanged = false; - for (const QString &fileID : params()["id"].split('|')) { + for (const QString &fileID : params()["id"].split('|')) + { const int id = fileID.toInt(&ok); if (!ok) throw APIError(APIErrorType::BadParams, tr("File IDs must be integers")); if ((id < 0) || (id >= filesCount)) throw APIError(APIErrorType::Conflict, tr("File ID is not valid")); - if (priorities[id] != priority) { + if (priorities[id] != priority) + { priorities[id] = priority; priorityChanged = true; } @@ -790,7 +825,8 @@ void TorrentsController::uploadLimitAction() const QStringList hashes {params()["hashes"].split('|')}; QJsonObject map; - for (const QString &hash : hashes) { + for (const QString &hash : hashes) + { int limit = -1; const BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(hash); if (torrent) @@ -807,7 +843,8 @@ void TorrentsController::downloadLimitAction() const QStringList hashes {params()["hashes"].split('|')}; QJsonObject map; - for (const QString &hash : hashes) { + for (const QString &hash : hashes) + { int limit = -1; const BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(hash); if (torrent) @@ -1082,9 +1119,11 @@ void TorrentsController::categoriesAction() { QJsonObject categories; const QStringMap categoriesMap = BitTorrent::Session::instance()->categories(); - for (auto it = categoriesMap.cbegin(); it != categoriesMap.cend(); ++it) { + for (auto it = categoriesMap.cbegin(); it != categoriesMap.cend(); ++it) + { const auto &key = it.key(); - categories[key] = QJsonObject { + categories[key] = QJsonObject + { {"name", key}, {"savePath", it.value()} }; @@ -1100,7 +1139,8 @@ void TorrentsController::addTagsAction() const QStringList hashes {params()["hashes"].split('|')}; const QStringList tags {params()["tags"].split(',', QString::SkipEmptyParts)}; - for (const QString &tag : tags) { + for (const QString &tag : tags) + { const QString tagTrimmed {tag.trimmed()}; applyToTorrents(hashes, [&tagTrimmed](BitTorrent::TorrentHandle *const torrent) { @@ -1116,7 +1156,8 @@ void TorrentsController::removeTagsAction() const QStringList hashes {params()["hashes"].split('|')}; const QStringList tags {params()["tags"].split(',', QString::SkipEmptyParts)}; - for (const QString &tag : tags) { + for (const QString &tag : tags) + { const QString tagTrimmed {tag.trimmed()}; applyToTorrents(hashes, [&tagTrimmed](BitTorrent::TorrentHandle *const torrent) { @@ -1124,7 +1165,8 @@ void TorrentsController::removeTagsAction() }); } - if (tags.isEmpty()) { + if (tags.isEmpty()) + { applyToTorrents(hashes, [](BitTorrent::TorrentHandle *const torrent) { torrent->removeAllTags(); @@ -1193,7 +1235,8 @@ void TorrentsController::renameFileAction() return; // check if new name is already used - for (int i = 0; i < torrent->filesCount(); ++i) { + for (int i = 0; i < torrent->filesCount(); ++i) + { if (i == fileIndex) continue; if (Utils::Fs::sameFileNames(torrent->filePath(i), newFilePath)) throw APIError(APIErrorType::Conflict, tr("Name is already in use")); diff --git a/src/webui/api/transfercontroller.cpp b/src/webui/api/transfercontroller.cpp index 1e70e8eed..852baa437 100644 --- a/src/webui/api/transfercontroller.cpp +++ b/src/webui/api/transfercontroller.cpp @@ -122,7 +122,8 @@ void TransferController::banPeersAction() requireParams({"peers"}); const QStringList peers = params()["peers"].split('|'); - for (const QString &peer : peers) { + for (const QString &peer : peers) + { const BitTorrent::PeerAddress addr = BitTorrent::PeerAddress::parse(peer.trimmed()); if (!addr.ip.isNull()) BitTorrent::Session::instance()->banIP(addr.ip.toString()); diff --git a/src/webui/webapplication.cpp b/src/webui/webapplication.cpp index 87784fad7..372229c13 100644 --- a/src/webui/webapplication.cpp +++ b/src/webui/webapplication.cpp @@ -77,7 +77,8 @@ namespace QStringMap ret; const QVector cookies = cookieStr.splitRef(';', QString::SkipEmptyParts); - for (const auto &cookie : cookies) { + for (const auto &cookie : cookies) + { const int idx = cookie.indexOf('='); if (idx < 0) continue; @@ -104,7 +105,8 @@ namespace return QLatin1String("private, max-age=604800"); // 1 week if ((contentType == Http::CONTENT_TYPE_CSS) - || (contentType == Http::CONTENT_TYPE_JS)) { + || (contentType == Http::CONTENT_TYPE_JS)) + { // short interval in case of program update return QLatin1String("private, max-age=43200"); // 12 hrs } @@ -144,21 +146,25 @@ void WebApplication::sendWebUIFile() if (pathItems.contains(".") || pathItems.contains("..")) throw InternalServerErrorHTTPError(); - if (!m_isAltUIUsed) { - if (request().path.startsWith(PATH_PREFIX_ICONS)) { + if (!m_isAltUIUsed) + { + if (request().path.startsWith(PATH_PREFIX_ICONS)) + { const QString imageFilename {request().path.mid(PATH_PREFIX_ICONS.size())}; sendFile(QLatin1String(":/icons/") + imageFilename); return; } } - const QString path { + const QString path + { (request().path != QLatin1String("/") ? request().path : QLatin1String("/index.html")) }; - QString localPath { + QString localPath + { m_rootFolder + (session() ? PRIVATE_FOLDER : PUBLIC_FOLDER) + path @@ -166,22 +172,26 @@ void WebApplication::sendWebUIFile() QFileInfo fileInfo {localPath}; - if (!fileInfo.exists() && session()) { + if (!fileInfo.exists() && session()) + { // try to send public file if there is no private one localPath = m_rootFolder + PUBLIC_FOLDER + path; fileInfo.setFile(localPath); } - if (m_isAltUIUsed) { + if (m_isAltUIUsed) + { #ifdef Q_OS_UNIX - if (!Utils::Fs::isRegularFile(localPath)) { + if (!Utils::Fs::isRegularFile(localPath)) + { status(500, "Internal Server Error"); print(tr("Unacceptable file type, only regular file is allowed."), Http::CONTENT_TYPE_TXT); return; } #endif - while (fileInfo.filePath() != m_rootFolder) { + while (fileInfo.filePath() != m_rootFolder) + { if (fileInfo.isSymLink()) throw InternalServerErrorHTTPError(tr("Symlinks inside alternative UI folder are forbidden.")); @@ -198,10 +208,12 @@ void WebApplication::translateDocument(QString &data) const int i = 0; bool found = true; - while (i < data.size() && found) { + while (i < data.size() && found) + { QRegularExpressionMatch regexMatch; i = data.indexOf(regex, i, ®exMatch); - if (i >= 0) { + if (i >= 0) + { const QString sourceText = regexMatch.captured(1); const QString context = regexMatch.captured(3); @@ -219,7 +231,8 @@ void WebApplication::translateDocument(QString &data) const data.replace(i, regexMatch.capturedLength(), translation); i += translation.length(); } - else { + else + { found = false; // no more translatable strings } @@ -246,7 +259,8 @@ const Http::Environment &WebApplication::env() const void WebApplication::doProcessRequest() { const QRegularExpressionMatch match = m_apiPathPattern.match(request().path); - if (!match.hasMatch()) { + if (!match.hasMatch()) + { sendWebUIFile(); return; } @@ -265,9 +279,11 @@ void WebApplication::doProcessRequest() for (const Http::UploadedFile &torrent : request().files) data[torrent.filename] = torrent.data; - try { + try + { const QVariant result = controller->run(action, m_params, data); - switch (result.userType()) { + switch (result.userType()) + { case QMetaType::QJsonDocument: print(result.toJsonDocument().toJson(QJsonDocument::Compact), Http::CONTENT_TYPE_JSON); break; @@ -277,9 +293,11 @@ void WebApplication::doProcessRequest() break; } } - catch (const APIError &error) { + catch (const APIError &error) + { // re-throw as HTTPError - switch (error.type()) { + switch (error.type()) + { case APIErrorType::AccessDenied: throw ForbiddenHTTPError(error.message()); case APIErrorType::BadData: @@ -303,7 +321,8 @@ void WebApplication::configure() const bool isAltUIUsed = pref->isAltWebUiEnabled(); const QString rootFolder = Utils::Fs::expandPathAbs( !isAltUIUsed ? WWW_FOLDER : pref->getWebUiRootFolder()); - if ((isAltUIUsed != m_isAltUIUsed) || (rootFolder != m_rootFolder)) { + if ((isAltUIUsed != m_isAltUIUsed) || (rootFolder != m_rootFolder)) + { m_isAltUIUsed = isAltUIUsed; m_rootFolder = rootFolder; m_translatedFiles.clear(); @@ -314,16 +333,19 @@ void WebApplication::configure() } const QString newLocale = pref->getLocale(); - if (m_currentLocale != newLocale) { + if (m_currentLocale != newLocale) + { m_currentLocale = newLocale; m_translatedFiles.clear(); m_translationFileLoaded = m_translator.load(m_rootFolder + QLatin1String("/translations/webui_") + newLocale); - if (m_translationFileLoaded) { + if (m_translationFileLoaded) + { LogMsg(tr("Web UI translation for selected locale (%1) has been successfully loaded.") .arg(newLocale)); } - else { + else + { LogMsg(tr("Couldn't load Web UI translation for selected locale (%1).").arg(newLocale), Log::WARNING); } } @@ -361,13 +383,16 @@ void WebApplication::configure() if (!contentSecurityPolicy.isEmpty()) m_prebuiltHeaders.push_back({QLatin1String(Http::HEADER_CONTENT_SECURITY_POLICY), contentSecurityPolicy}); - if (pref->isWebUICustomHTTPHeadersEnabled()) { + if (pref->isWebUICustomHTTPHeadersEnabled()) + { const QString customHeaders = pref->getWebUICustomHTTPHeaders().trimmed(); const QVector customHeaderLines = customHeaders.splitRef('\n', QString::SkipEmptyParts); - for (const QStringRef &line : customHeaderLines) { + for (const QStringRef &line : customHeaderLines) + { const int idx = line.indexOf(':'); - if (idx < 0) { + if (idx < 0) + { // require separator `:` to be present even if `value` field can be empty LogMsg(tr("Missing ':' separator in WebUI custom HTTP header: \"%1\"").arg(line.toString()), Log::WARNING); continue; @@ -399,19 +424,22 @@ void WebApplication::sendFile(const QString &path) // find translated file in cache const auto it = m_translatedFiles.constFind(path); - if ((it != m_translatedFiles.constEnd()) && (lastModified <= it->lastModified)) { + if ((it != m_translatedFiles.constEnd()) && (lastModified <= it->lastModified)) + { print(it->data, it->mimeType); setHeader({Http::HEADER_CACHE_CONTROL, getCachingInterval(it->mimeType)}); return; } QFile file {path}; - if (!file.open(QIODevice::ReadOnly)) { + if (!file.open(QIODevice::ReadOnly)) + { qDebug("File %s was not found!", qUtf8Printable(path)); throw NotFoundHTTPError(); } - if (file.size() > MAX_ALLOWED_FILESIZE) { + if (file.size() > MAX_ALLOWED_FILESIZE) + { qWarning("%s: exceeded the maximum allowed file size!", qUtf8Printable(path)); throw InternalServerErrorHTTPError(tr("Exceeded the maximum allowed file size (%1)!") .arg(Utils::Misc::friendlyUnit(MAX_ALLOWED_FILESIZE))); @@ -424,7 +452,8 @@ void WebApplication::sendFile(const QString &path) const bool isTranslatable {mimeType.inherits(QLatin1String("text/plain"))}; // Translate the file - if (isTranslatable) { + if (isTranslatable) + { QString dataStr {data}; translateDocument(dataStr); data = dataStr.toUtf8(); @@ -443,28 +472,33 @@ Http::Response WebApplication::processRequest(const Http::Request &request, cons m_env = env; m_params.clear(); - if (m_request.method == Http::METHOD_GET) { + if (m_request.method == Http::METHOD_GET) + { for (auto iter = m_request.query.cbegin(); iter != m_request.query.cend(); ++iter) m_params[iter.key()] = QString::fromUtf8(iter.value()); } - else { + else + { m_params = m_request.posts; } // clear response clear(); - try { + try + { // block suspicious requests if ((m_isCSRFProtectionEnabled && isCrossSiteRequest(m_request)) - || (m_isHostHeaderValidationEnabled && !validateHostHeader(m_domainList))) { + || (m_isHostHeaderValidationEnabled && !validateHostHeader(m_domainList))) + { throw UnauthorizedHTTPError(); } sessionInitialize(); doProcessRequest(); } - catch (const HTTPError &error) { + catch (const HTTPError &error) + { status(error.statusCode(), error.statusText()); print((!error.message().isEmpty() ? error.message() : error.statusText()), Http::CONTENT_TYPE_TXT); } @@ -488,19 +522,24 @@ void WebApplication::sessionInitialize() // TODO: Additional session check - if (!sessionId.isEmpty()) { + if (!sessionId.isEmpty()) + { m_currentSession = m_sessions.value(sessionId); - if (m_currentSession) { - if (m_currentSession->hasExpired(m_sessionTimeout)) { + if (m_currentSession) + { + if (m_currentSession->hasExpired(m_sessionTimeout)) + { // session is outdated - removing it delete m_sessions.take(sessionId); m_currentSession = nullptr; } - else { + else + { m_currentSession->updateTimestamp(); } } - else { + else + { qDebug() << Q_FUNC_INFO << "session does not exist!"; } } @@ -513,8 +552,10 @@ QString WebApplication::generateSid() const { QString sid; - do { - const quint32 tmp[] = {Utils::Random::rand(), Utils::Random::rand(), Utils::Random::rand() + do + { + const quint32 tmp[] = + {Utils::Random::rand(), Utils::Random::rand(), Utils::Random::rand() , Utils::Random::rand(), Utils::Random::rand(), Utils::Random::rand()}; sid = QByteArray::fromRawData(reinterpret_cast(tmp), sizeof(tmp)).toBase64(); } @@ -544,7 +585,8 @@ void WebApplication::sessionStart() // remove outdated sessions Algorithm::removeIf(m_sessions, [this](const QString &, const WebSession *session) { - if (session->hasExpired(m_sessionTimeout)) { + if (session->hasExpired(m_sessionTimeout)) + { delete session; return true; } @@ -595,14 +637,16 @@ bool WebApplication::isCrossSiteRequest(const Http::Request &request) const const QString originValue = request.headers.value(Http::HEADER_ORIGIN); const QString refererValue = request.headers.value(Http::HEADER_REFERER); - if (originValue.isEmpty() && refererValue.isEmpty()) { + if (originValue.isEmpty() && refererValue.isEmpty()) + { // owasp.org recommends to block this request, but doing so will inevitably lead Web API users to spoof headers // so lets be permissive here return false; } // sent with CORS requests, as well as with POST requests - if (!originValue.isEmpty()) { + if (!originValue.isEmpty()) + { const bool isInvalid = !isSameOrigin(urlFromHostHeader(targetOrigin), originValue); if (isInvalid) LogMsg(tr("WebUI: Origin header & Target origin mismatch! Source IP: '%1'. Origin header: '%2'. Target origin: '%3'") @@ -611,7 +655,8 @@ bool WebApplication::isCrossSiteRequest(const Http::Request &request) const return isInvalid; } - if (!refererValue.isEmpty()) { + if (!refererValue.isEmpty()) + { const bool isInvalid = !isSameOrigin(urlFromHostHeader(targetOrigin), refererValue); if (isInvalid) LogMsg(tr("WebUI: Referer header & Target origin mismatch! Source IP: '%1'. Referer header: '%2'. Target origin: '%3'") @@ -630,7 +675,8 @@ bool WebApplication::validateHostHeader(const QStringList &domains) const // (if present) try matching host header's port with local port const int requestPort = hostHeader.port(); - if ((requestPort != -1) && (m_env.localPort != requestPort)) { + if ((requestPort != -1) && (m_env.localPort != requestPort)) + { LogMsg(tr("WebUI: Invalid Host header, port mismatch. Request source IP: '%1'. Server port: '%2'. Received Host header: '%3'") .arg(m_env.clientAddress.toString()).arg(m_env.localPort) .arg(m_request.headers[Http::HEADER_HOST]) @@ -645,7 +691,8 @@ bool WebApplication::validateHostHeader(const QStringList &domains) const return true; // try matching host header with domain list - for (const auto &domain : domains) { + for (const auto &domain : domains) + { QRegExp domainRegex(domain, Qt::CaseInsensitive, QRegExp::Wildcard); if (requestHost.contains(domainRegex)) return true; diff --git a/src/webui/webui.cpp b/src/webui/webui.cpp index 06e8a479d..3b86596e1 100644 --- a/src/webui/webui.cpp +++ b/src/webui/webui.cpp @@ -56,31 +56,38 @@ void WebUI::configure() const quint16 oldPort = m_port; m_port = pref->getWebUiPort(); - if (pref->isWebUiEnabled()) { + if (pref->isWebUiEnabled()) + { // UPnP/NAT-PMP - if (pref->useUPnPForWebUIPort()) { - if (m_port != oldPort) { + if (pref->useUPnPForWebUIPort()) + { + if (m_port != oldPort) + { Net::PortForwarder::instance()->deletePort(oldPort); Net::PortForwarder::instance()->addPort(m_port); } } - else { + else + { Net::PortForwarder::instance()->deletePort(oldPort); } // http server const QString serverAddressString = pref->getWebUiAddress(); - if (!m_httpServer) { + if (!m_httpServer) + { m_webapp = new WebApplication(this); m_httpServer = new Http::Server(m_webapp, this); } - else { + else + { if ((m_httpServer->serverAddress().toString() != serverAddressString) || (m_httpServer->serverPort() != m_port)) m_httpServer->close(); } - if (pref->isWebUiHttpsEnabled()) { + if (pref->isWebUiHttpsEnabled()) + { const auto readData = [](const QString &path) -> QByteArray { QFile file(path); @@ -97,18 +104,22 @@ void WebUI::configure() else logger->addMessage(tr("Web UI: HTTPS setup failed, fallback to HTTP"), Log::CRITICAL); } - else { + else + { m_httpServer->disableHttps(); } - if (!m_httpServer->isListening()) { + if (!m_httpServer->isListening()) + { const auto address = (serverAddressString == "*" || serverAddressString.isEmpty()) ? QHostAddress::Any : QHostAddress(serverAddressString); bool success = m_httpServer->listen(address, m_port); - if (success) { + if (success) + { logger->addMessage(tr("Web UI: Now listening on IP: %1, port: %2").arg(serverAddressString).arg(m_port)); } - else { + else + { const QString errorMsg = tr("Web UI: Unable to bind to IP: %1, port: %2. Reason: %3") .arg(serverAddressString).arg(m_port).arg(m_httpServer->errorString()); logger->addMessage(errorMsg, Log::CRITICAL); @@ -120,17 +131,20 @@ void WebUI::configure() } // DynDNS - if (pref->isDynDNSEnabled()) { + if (pref->isDynDNSEnabled()) + { if (!m_dnsUpdater) m_dnsUpdater = new Net::DNSUpdater(this); else m_dnsUpdater->updateCredentials(); } - else { + else + { delete m_dnsUpdater; } } - else { + else + { Net::PortForwarder::instance()->deletePort(oldPort); delete m_httpServer;