From 51573a3c1eb63d944f87ce16a9ae8c26a183ebfe Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Fri, 5 Jun 2020 14:02:11 -0500 Subject: [PATCH] chore: clang-tidy cleanups (#1287) * chore: fix syntax error in clang-tidy config file --- qt/.clang-tidy | 56 +++++++++++--- qt/AboutDialog.h | 2 +- qt/Application.cc | 47 ++++++------ qt/ColumnResizer.cc | 5 +- qt/ComInteropHelper.cc | 8 +- qt/DBusInteropHelper.cc | 16 ++-- qt/DBusInteropHelper.h | 3 + qt/DetailsDialog.cc | 135 +++++++++++++++++---------------- qt/DetailsDialog.h | 6 +- qt/FaviconCache.cc | 6 +- qt/FileTreeDelegate.cc | 6 +- qt/FileTreeItem.cc | 9 ++- qt/FileTreeModel.cc | 39 ++++------ qt/FileTreeModel.h | 3 +- qt/FileTreeView.cc | 10 ++- qt/FilterBar.cc | 43 ++++++----- qt/Filters.cc | 8 +- qt/Filters.h | 10 ++- qt/Formatter.cc | 119 ++++++++++++----------------- qt/Formatter.h | 15 ++-- qt/FreeSpaceLabel.cc | 5 +- qt/InteropHelper.cc | 14 ++-- qt/InteropHelper.h | 4 +- qt/InteropObject.cc | 2 + qt/LicenseDialog.h | 2 +- qt/MainWindow.cc | 158 ++++++++++++++++++++++----------------- qt/MainWindow.h | 2 +- qt/MakeDialog.cc | 2 +- qt/MakeDialog.h | 2 +- qt/OptionsDialog.cc | 14 ++-- qt/OptionsDialog.h | 6 +- qt/Prefs.cc | 30 ++++---- qt/Prefs.h | 14 ++-- qt/PrefsDialog.cc | 69 +++++++++-------- qt/PrefsDialog.h | 2 +- qt/RelocateDialog.cc | 12 +-- qt/RelocateDialog.h | 6 +- qt/RpcQueue.cc | 4 +- qt/Session.cc | 26 +++---- qt/Session.h | 6 +- qt/SessionDialog.h | 2 +- qt/Speed.h | 38 +++++----- qt/SqueezeLabel.cc | 8 +- qt/StatsDialog.h | 2 +- qt/Torrent.cc | 30 ++++---- qt/Torrent.h | 10 +-- qt/TorrentDelegate.cc | 75 +++++++++---------- qt/TorrentDelegate.h | 12 +-- qt/TorrentDelegateMin.cc | 38 +++++----- qt/TorrentFilter.cc | 16 ++-- qt/TorrentFilter.h | 16 ++-- qt/TorrentModel.cc | 4 +- qt/TorrentView.cc | 8 +- qt/TrackerDelegate.cc | 21 +++--- qt/TrackerModelFilter.cc | 4 +- qt/Utils.cc | 8 +- 56 files changed, 634 insertions(+), 584 deletions(-) diff --git a/qt/.clang-tidy b/qt/.clang-tidy index a36ed4845..f2535132b 100644 --- a/qt/.clang-tidy +++ b/qt/.clang-tidy @@ -1,5 +1,7 @@ --- -Checks: "-*,\ +# Many of these checks are disabled only because the code hasn't been +# cleaned up yet. Pull requests welcomed. +Checks: > bugprone-*, -bugprone-branch-clone, -bugprone-narrowing-conversions, @@ -7,24 +9,56 @@ Checks: "-*,\ -cert-err58-cpp, clang-analyzer-optin*, cppcoreguidelines-*, + -cppcoreguidelines-avoid-magic-numbers, + -cppcoreguidelines-init-variables, + -cppcoreguidelines-macro-usage, + -cppcoreguidelines-narrowing-conversions, + -cppcoreguidelines-non-private-member-variables-in-classes, + -cppcoreguidelines-owning-memory, + -cppcoreguidelines-pro-bounds-array-to-pointer-decay, + -cppcoreguidelines-pro-bounds-constant-array-index, + -cppcoreguidelines-pro-bounds-pointer-arithmetic, + -cppcoreguidelines-pro-type-const-cast, + -cppcoreguidelines-pro-type-cstyle-cast, + -cppcoreguidelines-pro-type-reinterpret-cast, + -cppcoreguidelines-pro-type-static-cast-downcast, + -cppcoreguidelines-special-member-functions, + google-readability-*, + google-runtime-operator, hicpp-*, + -hicpp-multiway-paths-covered, + -hicpp-no-array-decay, + -hicpp-signed-bitwise, + -hicpp-special-member-functions, misc-*, + -misc-no-recursion, -misc-non-private-member-variables-in-classes, modernize-*, - -modernize-avoid-c-arrays, - -modernize-loop-convert, - -modernize-pass-by-value, - -modernize-raw-string-literal, - -modernize-use-nodiscard, - -modernize-use-trailing-return-type, + -modernize-use-trailing-return-type, # keep + performance-*, readability-*, -readability-convert-member-functions-to-static, -readability-implicit-bool-conversion, -readability-inconsistent-declaration-parameter-name, - -readability-isolate-declaration, -readability-magic-numbers, -readability-redundant-access-specifiers, - -readability-static-accessed-through-instance, -WarningsAsErrors: "*" -... + -readability-static-accessed-through-instance +WarningsAsErrors: > + * + +CheckOptions: + - { key: readability-identifier-naming.ClassCase, value: CamelCase } + - { key: readability-identifier-naming.ClassMethodCase, value: camelBack } + - { key: readability-identifier-naming.ConstexprVariableCase, value: CamelCase } + - { key: readability-identifier-naming.EnumConstantCase, value: UPPER_CASE } + - { key: readability-identifier-naming.FunctionCase, value: camelBack } + - { key: readability-identifier-naming.GlobalConstantCase, value: CamelCase } + - { key: readability-identifier-naming.MemberConstantCase, value: CamelCase } + - { key: readability-identifier-naming.NamespaceCase, value: lower_case } + - { key: readability-identifier-naming.PrivateMemberSuffix, value: _ } + - { key: readability-identifier-naming.ProtectedMemberSuffix, value: _ } + - { key: readability-identifier-naming.StaticConstantCase, value: CamelCase } + - { key: readability-identifier-naming.StructCase, value: CamelCase } + - { key: readability-identifier-naming.TemplateParameterCase, value: CamelCase } + - { key: readability-identifier-naming.VariableCase, value: lower_case } diff --git a/qt/AboutDialog.h b/qt/AboutDialog.h index d23ee0852..01797666d 100644 --- a/qt/AboutDialog.h +++ b/qt/AboutDialog.h @@ -28,7 +28,7 @@ private slots: void showLicense(); private: - Ui::AboutDialog ui_; + Ui::AboutDialog ui_{}; QPointer license_dialog_; }; diff --git a/qt/Application.cc b/qt/Application.cc index cf122b12d..534f22b6c 100644 --- a/qt/Application.cc +++ b/qt/Application.cc @@ -6,6 +6,7 @@ * */ +#include #include #include @@ -41,12 +42,12 @@ namespace { -auto const MY_CONFIG_NAME = QStringLiteral("transmission"); -auto const MY_READABLE_NAME = QStringLiteral("transmission-qt"); +auto const MyConfigName = QStringLiteral("transmission"); +auto const MyReadableName = QStringLiteral("transmission-qt"); -tr_option const opts[] = +std::array const Opts = { - { 'g', "config-dir", "Where to look for configuration files", "g", true, "" }, + tr_option{ 'g', "config-dir", "Where to look for configuration files", "g", true, "" }, { 'm', "minimized", "Start minimized in system tray", "m", false, nullptr }, { 'p', "port", "Port to use when connecting to an existing session", "p", true, "" }, { 'r', "remote", "Connect to an existing session at the specified hostname", "r", true, "" }, @@ -87,7 +88,7 @@ bool loadTranslation(QTranslator& translator, QString const& name, QLocale const Application::Application(int& argc, char** argv) : QApplication(argc, argv) { - setApplicationName(MY_CONFIG_NAME); + setApplicationName(MyConfigName); loadTranslations(); Formatter::initUnits(); @@ -106,10 +107,8 @@ Application::Application(int& argc, char** argv) : if (icon.isNull()) { - QList sizes; - sizes << 16 << 22 << 24 << 32 << 48 << 64 << 72 << 96 << 128 << 192 << 256; - - for (int const size : sizes) + static std::array constexpr Sizes = { 16, 22, 24, 32, 48, 64, 72, 96, 128, 192, 256 }; + for (auto const size : Sizes) { icon.addPixmap(QPixmap(QStringLiteral(":/icons/transmission-%1.png").arg(size))); } @@ -132,7 +131,7 @@ Application::Application(int& argc, char** argv) : QString config_dir; QStringList filenames; - while ((c = tr_getopt(getUsage(), argc, const_cast(argv), opts, &optarg)) != TR_OPT_DONE) + while ((c = tr_getopt(getUsage(), argc, const_cast(argv), Opts.data(), &optarg)) != TR_OPT_DONE) { switch (c) { @@ -161,13 +160,13 @@ Application::Application(int& argc, char** argv) : break; case 'v': - std::cerr << qPrintable(MY_READABLE_NAME) << ' ' << LONG_VERSION_STRING << std::endl; + std::cerr << qPrintable(MyReadableName) << ' ' << LONG_VERSION_STRING << std::endl; quitLater(); return; case TR_OPT_ERR: std::cerr << qPrintable(QObject::tr("Invalid option")) << std::endl; - tr_getopt_usage(qPrintable(MY_READABLE_NAME), getUsage(), opts); + tr_getopt_usage(qPrintable(MyReadableName), getUsage(), Opts.data()); quitLater(); return; @@ -377,8 +376,8 @@ void Application::loadTranslations() installTranslator(&qt_translator_); } - if (loadTranslation(app_translator_, MY_CONFIG_NAME, locale, app_qm_dirs) || - loadTranslation(app_translator_, MY_CONFIG_NAME, english_locale, app_qm_dirs)) + if (loadTranslation(app_translator_, MyConfigName, locale, app_qm_dirs) || + loadTranslation(app_translator_, MyConfigName, english_locale, app_qm_dirs)) { installTranslator(&app_translator_); } @@ -464,11 +463,11 @@ Application::~Application() { if (prefs_ != nullptr && window_ != nullptr) { - QRect const mainwinRect(window_->geometry()); - prefs_->set(Prefs::MAIN_WINDOW_HEIGHT, std::max(100, mainwinRect.height())); - prefs_->set(Prefs::MAIN_WINDOW_WIDTH, std::max(100, mainwinRect.width())); - prefs_->set(Prefs::MAIN_WINDOW_X, mainwinRect.x()); - prefs_->set(Prefs::MAIN_WINDOW_Y, mainwinRect.y()); + auto const geometry = window_->geometry(); + prefs_->set(Prefs::MAIN_WINDOW_HEIGHT, std::max(100, geometry.height())); + prefs_->set(Prefs::MAIN_WINDOW_WIDTH, std::max(100, geometry.width())); + prefs_->set(Prefs::MAIN_WINDOW_X, geometry.x()); + prefs_->set(Prefs::MAIN_WINDOW_Y, geometry.y()); } delete watch_dir_; @@ -584,16 +583,16 @@ bool Application::notifyApp(QString const& title, QString const& body) const { #ifdef QT_DBUS_LIB - auto const DBUS_SERVICE_NAME = QStringLiteral("org.freedesktop.Notifications"); - auto const DBUS_INTERFACE_NAME = QStringLiteral("org.freedesktop.Notifications"); - auto const DBUS_PATH = QStringLiteral("/org/freedesktop/Notifications"); + auto const dbus_service_name = QStringLiteral("org.freedesktop.Notifications"); + auto const dbus_interface_name = QStringLiteral("org.freedesktop.Notifications"); + auto const dbus_path = QStringLiteral("/org/freedesktop/Notifications"); QDBusConnection bus = QDBusConnection::sessionBus(); if (bus.isConnected()) { QDBusMessage m = - QDBusMessage::createMethodCall(DBUS_SERVICE_NAME, DBUS_PATH, DBUS_INTERFACE_NAME, QStringLiteral("Notify")); + QDBusMessage::createMethodCall(dbus_service_name, dbus_path, dbus_interface_name, QStringLiteral("Notify")); QVariantList args; args.append(QStringLiteral("Transmission")); // app_name args.append(0U); // replaces_id @@ -627,7 +626,7 @@ FaviconCache& Application::faviconCache() **** ***/ -int tr_main(int argc, char* argv[]) +int tr_main(int argc, char** argv) { InteropHelper::initialize(); diff --git a/qt/ColumnResizer.cc b/qt/ColumnResizer.cc index b374dfa52..b1da51132 100644 --- a/qt/ColumnResizer.cc +++ b/qt/ColumnResizer.cc @@ -24,7 +24,10 @@ int itemColumnSpan(QGridLayout* layout, QLayoutItem const* item) continue; } - int row, column, row_span, column_span; + int row = {}; + int column = {}; + int row_span = {}; + int column_span = {}; layout->getItemPosition(i, &row, &column, &row_span, &column_span); return column_span; } diff --git a/qt/ComInteropHelper.cc b/qt/ComInteropHelper.cc index b8a4d54c2..42b5f4b91 100644 --- a/qt/ComInteropHelper.cc +++ b/qt/ComInteropHelper.cc @@ -22,10 +22,10 @@ QAXCLASS(InteropObject) QAXFACTORY_END() // These are ActiveQt internals; declaring here as I don't like their WinMain much... -extern HANDLE qAxInstance; -extern bool qAxOutProcServer; -extern wchar_t qAxModuleFilename[MAX_PATH]; -extern QString qAxInit(); +extern HANDLE qAxInstance; // NOLINT +extern bool qAxOutProcServer; // NOLINT +extern wchar_t qAxModuleFilename[MAX_PATH]; // NOLINT +extern QString qAxInit(); // NOLINT ComInteropHelper::ComInteropHelper() : client_(new QAxObject(QStringLiteral("Transmission.QtClient"))) diff --git a/qt/DBusInteropHelper.cc b/qt/DBusInteropHelper.cc index c88e8ce02..4df37bb8a 100644 --- a/qt/DBusInteropHelper.cc +++ b/qt/DBusInteropHelper.cc @@ -20,9 +20,9 @@ namespace { -auto const DBUS_SERVICE = QStringLiteral("com.transmissionbt.Transmission"); -auto const DBUS_OBJECT_PATH = QStringLiteral("/com/transmissionbt/Transmission"); -auto const DBUS_INTERFACE = QStringLiteral("com.transmissionbt.Transmission"); +auto const DBusService = QStringLiteral("com.transmissionbt.Transmission"); +auto const DBusObjectPath = QStringLiteral("/com/transmissionbt/Transmission"); +auto const DBusInterface = QStringLiteral("com.transmissionbt.Transmission"); } // namespace @@ -33,7 +33,7 @@ bool DBusInteropHelper::isConnected() const QVariant DBusInteropHelper::addMetainfo(QString const& metainfo) { - QDBusMessage request = QDBusMessage::createMethodCall(DBUS_SERVICE, DBUS_OBJECT_PATH, DBUS_INTERFACE, + QDBusMessage request = QDBusMessage::createMethodCall(DBusService, DBusObjectPath, DBusInterface, QStringLiteral("AddMetainfo")); request.setArguments(QVariantList() << metainfo); @@ -50,13 +50,13 @@ void DBusInteropHelper::registerObject(QObject* parent) return; } - if (!bus.registerService(DBUS_SERVICE)) + if (!bus.registerService(DBusService)) { - std::cerr << "couldn't register " << qPrintable(DBUS_SERVICE) << std::endl; + std::cerr << "couldn't register " << qPrintable(DBusService) << std::endl; } - if (!bus.registerObject(DBUS_OBJECT_PATH, new InteropObject(parent), QDBusConnection::ExportAllSlots)) + if (!bus.registerObject(DBusObjectPath, new InteropObject(parent), QDBusConnection::ExportAllSlots)) { - std::cerr << "couldn't register " << qPrintable(DBUS_OBJECT_PATH) << std::endl; + std::cerr << "couldn't register " << qPrintable(DBusObjectPath) << std::endl; } } diff --git a/qt/DBusInteropHelper.h b/qt/DBusInteropHelper.h index b2d99ff98..e129aba3c 100644 --- a/qt/DBusInteropHelper.h +++ b/qt/DBusInteropHelper.h @@ -15,6 +15,9 @@ class QVariant; class DBusInteropHelper { public: + DBusInteropHelper() = default; + ~DBusInteropHelper() = default; + bool isConnected() const; QVariant addMetainfo(QString const& metainfo); diff --git a/qt/DetailsDialog.cc b/qt/DetailsDialog.cc index f728cbc81..7a6c2bda5 100644 --- a/qt/DetailsDialog.cc +++ b/qt/DetailsDialog.cc @@ -55,9 +55,9 @@ class Session; namespace { -int const REFRESH_INTERVAL_MSEC = 4000; +int constexpr RefreshIntervalMSec = 4000; -char const* PREF_KEY("pref-key"); +char const constexpr* const PrefKey = "pref_key"; enum // peer columns { @@ -89,13 +89,13 @@ int measureViewItem(QTreeWidget* view, int column, QString const& text) class PeerItem : public QTreeWidgetItem { - Peer peer; - QString mutable collated_address; - QString status; + Peer peer_; + QString mutable collated_address_; + QString status_; public: - PeerItem(Peer const& p) : - peer(p) + explicit PeerItem(Peer p) : + peer_(std::move(p)) { } @@ -103,17 +103,17 @@ public: void refresh(Peer const& p) { - if (p.address != peer.address) + if (p.address != peer_.address) { - collated_address.clear(); + collated_address_.clear(); } - peer = p; + peer_ = p; } void setStatus(QString const& s) { - status = s; + status_ = s; } bool operator <(QTreeWidgetItem const& other) const override @@ -127,22 +127,22 @@ public: switch (column) { case COL_UP: - return peer.rate_to_peer < i->peer.rate_to_peer; + return peer_.rate_to_peer < i->peer_.rate_to_peer; case COL_DOWN: - return peer.rate_to_client < i->peer.rate_to_client; + return peer_.rate_to_client < i->peer_.rate_to_client; case COL_PERCENT: - return peer.progress < i->peer.progress; + return peer_.progress < i->peer_.progress; case COL_STATUS: - return status < i->status; + return status_ < i->status_; case COL_CLIENT: - return peer.client_name < i->peer.client_name; + return peer_.client_name < i->peer_.client_name; case COL_LOCK: - return peer.is_encrypted && !i->peer.is_encrypted; + return peer_.is_encrypted && !i->peer_.is_encrypted; default: return address() < i->address(); @@ -152,16 +152,16 @@ public: private: QString const& address() const { - if (collated_address.isEmpty()) + if (collated_address_.isEmpty()) { QHostAddress ip_address; - if (ip_address.setAddress(peer.address)) + if (ip_address.setAddress(peer_.address)) { if (ip_address.protocol() == QAbstractSocket::IPv4Protocol) { quint32 const ipv4_address = ip_address.toIPv4Address(); - collated_address = QStringLiteral("1-") + QString::fromUtf8(QByteArray::number(ipv4_address, 16). + collated_address_ = QStringLiteral("1-") + QString::fromUtf8(QByteArray::number(ipv4_address, 16). rightJustified(8, '0')); } else if (ip_address.protocol() == QAbstractSocket::IPv6Protocol) @@ -174,17 +174,17 @@ private: tmp[i] = ipv6_address[i]; } - collated_address = QStringLiteral("2-") + QString::fromUtf8(tmp.toHex()); + collated_address_ = QStringLiteral("2-") + QString::fromUtf8(tmp.toHex()); } } - if (collated_address.isEmpty()) + if (collated_address_.isEmpty()) { - collated_address = QStringLiteral("3-") + peer.address.toLower(); + collated_address_ = QStringLiteral("3-") + peer_.address.toLower(); } } - return collated_address; + return collated_address_; } }; @@ -221,10 +221,13 @@ DetailsDialog::DetailsDialog(Session& session, Prefs& prefs, TorrentModel const& adjustSize(); ui_.commentBrowser->setMaximumHeight(QWIDGETSIZE_MAX); - QList init_keys; - init_keys << Prefs::SHOW_TRACKER_SCRAPES << Prefs::SHOW_BACKUP_TRACKERS; + static std::array constexpr InitKeys = + { + Prefs::SHOW_TRACKER_SCRAPES, + Prefs::SHOW_BACKUP_TRACKERS + }; - for (int const key : init_keys) + for (int const key : InitKeys) { refreshPref(key); } @@ -235,7 +238,7 @@ DetailsDialog::DetailsDialog(Session& session, Prefs& prefs, TorrentModel const& onTimer(); timer_.setSingleShot(false); - timer_.start(REFRESH_INTERVAL_MSEC); + timer_.start(RefreshIntervalMSec); } DetailsDialog::~DetailsDialog() @@ -798,7 +801,7 @@ void DetailsDialog::refresh() // myCommentBrowser string = none; - bool isCommentMixed = false; + bool is_comment_mixed = false; if (!torrents.empty()) { @@ -809,7 +812,7 @@ void DetailsDialog::refresh() if (string != t->comment()) { string = mixed; - isCommentMixed = true; + is_comment_mixed = true; break; } } @@ -820,7 +823,7 @@ void DetailsDialog::refresh() ui_.commentBrowser->setText(string); } - ui_.commentBrowser->setEnabled(!isCommentMixed && !string.isEmpty()); + ui_.commentBrowser->setEnabled(!is_comment_mixed && !string.isEmpty()); // myOriginLabel string = none; @@ -967,8 +970,8 @@ void DetailsDialog::refresh() setIfIdle(ui_.bandwidthPriorityCombo, i); - setIfIdle(ui_.singleDownSpin, int(baseline.downloadLimit().KBps())); - setIfIdle(ui_.singleUpSpin, int(baseline.uploadLimit().KBps())); + setIfIdle(ui_.singleDownSpin, int(baseline.downloadLimit().getKBps())); + setIfIdle(ui_.singleUpSpin, int(baseline.uploadLimit().getKBps())); setIfIdle(ui_.peerLimitSpin, baseline.peerLimit()); } @@ -1025,31 +1028,31 @@ void DetailsDialog::refresh() /// QMap peers2; - QList newItems; + QList new_items; for (Torrent const* const t : torrents) { - QString const idStr(QString::number(t->id())); + QString const id_str(QString::number(t->id())); PeerList peers = t->peers(); for (Peer const& peer : peers) { - QString const key = idStr + QLatin1Char(':') + peer.address; + QString const key = id_str + QLatin1Char(':') + peer.address; PeerItem* item = static_cast(peers_.value(key, nullptr)); if (item == nullptr) // new peer has connected { - static QIcon const ENCRYPTION_ICON(QStringLiteral(":/icons/encrypted.png")); - static QIcon const EMPTY_ICON; + static QIcon const EncryptionIcon(QStringLiteral(":/icons/encrypted.png")); + static QIcon const EmptyIcon; item = new PeerItem(peer); item->setTextAlignment(COL_UP, Qt::AlignRight | Qt::AlignVCenter); item->setTextAlignment(COL_DOWN, Qt::AlignRight | Qt::AlignVCenter); item->setTextAlignment(COL_PERCENT, Qt::AlignRight | Qt::AlignVCenter); - item->setIcon(COL_LOCK, peer.is_encrypted ? ENCRYPTION_ICON : EMPTY_ICON); + item->setIcon(COL_LOCK, peer.is_encrypted ? EncryptionIcon : EmptyIcon); item->setToolTip(COL_LOCK, peer.is_encrypted ? tr("Encrypted connection") : QString()); item->setText(COL_ADDRESS, peer.address); item->setText(COL_CLIENT, peer.client_name); - newItems << item; + new_items << item; } QString const code = peer.flags; @@ -1135,7 +1138,7 @@ void DetailsDialog::refresh() } } - ui_.peersView->addTopLevelItems(newItems); + ui_.peersView->addTopLevelItems(new_items); for (QString const& key : peers_.keys()) { @@ -1216,7 +1219,7 @@ void DetailsDialog::onDownloadLimitedToggled(bool val) void DetailsDialog::onSpinBoxEditingFinished() { QObject const* spin = sender(); - tr_quark const key = spin->property(PREF_KEY).toInt(); + tr_quark const key = spin->property(PrefKey).toInt(); auto const* d = qobject_cast(spin); if (d != nullptr) @@ -1247,11 +1250,11 @@ void DetailsDialog::onIdleModeChanged(int index) void DetailsDialog::onIdleLimitChanged() { //: Spin box suffix, "Stop seeding if idle for: [ 5 minutes ]" (includes leading space after the number, if needed) - QString const unitsSuffix = tr(" minute(s)", nullptr, ui_.idleSpin->value()); + QString const units_suffix = tr(" minute(s)", nullptr, ui_.idleSpin->value()); - if (ui_.idleSpin->suffix() != unitsSuffix) + if (ui_.idleSpin->suffix() != units_suffix) { - ui_.idleSpin->setSuffix(unitsSuffix); + ui_.idleSpin->setSuffix(units_suffix); } } @@ -1323,11 +1326,11 @@ void DetailsDialog::onEditTrackerClicked() QModelIndexList selected_rows = selection_model->selectedRows(); assert(selected_rows.size() == 1); QModelIndex i = selection_model->currentIndex(); - auto const trackerInfo = ui_.trackersView->model()->data(i, TrackerModel::TrackerRole).value(); + auto const tracker_info = ui_.trackersView->model()->data(i, TrackerModel::TrackerRole).value(); bool ok = false; QString const newval = QInputDialog::getText(this, tr("Edit URL "), tr("Edit tracker announce URL:"), QLineEdit::Normal, - trackerInfo.st.announce, &ok); + tracker_info.st.announce, &ok); if (!ok) { @@ -1339,9 +1342,9 @@ void DetailsDialog::onEditTrackerClicked() } else { - torrent_ids_t ids{ trackerInfo.torrent_id }; + torrent_ids_t ids{ tracker_info.torrent_id }; - QPair const id_url = qMakePair(trackerInfo.st.id, newval); + QPair const id_url = qMakePair(tracker_info.st.id, newval); session_.torrentSet(ids, TR_KEY_trackerReplace, id_url); getNewData(); @@ -1374,16 +1377,16 @@ void DetailsDialog::onRemoveTrackerClicked() void DetailsDialog::initOptionsTab() { - QString const speed_K_str = Formatter::unitStr(Formatter::SPEED, Formatter::KB); + auto const speed_unit_str = Formatter::unitStr(Formatter::SPEED, Formatter::KB); - ui_.singleDownSpin->setSuffix(QStringLiteral(" %1").arg(speed_K_str)); - ui_.singleUpSpin->setSuffix(QStringLiteral(" %1").arg(speed_K_str)); + ui_.singleDownSpin->setSuffix(QStringLiteral(" %1").arg(speed_unit_str)); + ui_.singleUpSpin->setSuffix(QStringLiteral(" %1").arg(speed_unit_str)); - ui_.singleDownSpin->setProperty(PREF_KEY, TR_KEY_downloadLimit); - ui_.singleUpSpin->setProperty(PREF_KEY, TR_KEY_uploadLimit); - ui_.ratioSpin->setProperty(PREF_KEY, TR_KEY_seedRatioLimit); - ui_.idleSpin->setProperty(PREF_KEY, TR_KEY_seedIdleLimit); - ui_.peerLimitSpin->setProperty(PREF_KEY, TR_KEY_peer_limit); + ui_.singleDownSpin->setProperty(PrefKey, TR_KEY_downloadLimit); + ui_.singleUpSpin->setProperty(PrefKey, TR_KEY_uploadLimit); + ui_.ratioSpin->setProperty(PrefKey, TR_KEY_seedRatioLimit); + ui_.idleSpin->setProperty(PrefKey, TR_KEY_seedIdleLimit); + ui_.peerLimitSpin->setProperty(PrefKey, TR_KEY_peer_limit); ui_.bandwidthPriorityCombo->addItem(tr("High"), TR_PRI_HIGH); ui_.bandwidthPriorityCombo->addItem(tr("Normal"), TR_PRI_NORMAL); @@ -1404,14 +1407,14 @@ void DetailsDialog::initOptionsTab() cr->addLayout(ui_.peerConnectionsSectionLayout); cr->update(); - void (QComboBox::* comboIndexChanged)(int) = &QComboBox::currentIndexChanged; - void (QSpinBox::* spinValueChanged)(int) = &QSpinBox::valueChanged; - connect(ui_.bandwidthPriorityCombo, comboIndexChanged, this, &DetailsDialog::onBandwidthPriorityChanged); - connect(ui_.idleCombo, comboIndexChanged, this, &DetailsDialog::onIdleModeChanged); + void (QComboBox::* combo_index_changed)(int) = &QComboBox::currentIndexChanged; + void (QSpinBox::* spin_value_changed)(int) = &QSpinBox::valueChanged; + connect(ui_.bandwidthPriorityCombo, combo_index_changed, this, &DetailsDialog::onBandwidthPriorityChanged); + connect(ui_.idleCombo, combo_index_changed, this, &DetailsDialog::onIdleModeChanged); connect(ui_.idleSpin, &QSpinBox::editingFinished, this, &DetailsDialog::onSpinBoxEditingFinished); - connect(ui_.idleSpin, spinValueChanged, this, &DetailsDialog::onIdleLimitChanged); + connect(ui_.idleSpin, spin_value_changed, this, &DetailsDialog::onIdleLimitChanged); connect(ui_.peerLimitSpin, &QSpinBox::editingFinished, this, &DetailsDialog::onSpinBoxEditingFinished); - connect(ui_.ratioCombo, comboIndexChanged, this, &DetailsDialog::onRatioModeChanged); + connect(ui_.ratioCombo, combo_index_changed, this, &DetailsDialog::onRatioModeChanged); connect(ui_.ratioSpin, &QSpinBox::editingFinished, this, &DetailsDialog::onSpinBoxEditingFinished); connect(ui_.sessionLimitCheck, &QCheckBox::clicked, this, &DetailsDialog::onHonorsSessionLimitsToggled); connect(ui_.singleDownCheck, &QCheckBox::clicked, this, &DetailsDialog::onDownloadLimitedToggled); @@ -1533,14 +1536,14 @@ void DetailsDialog::onOpenRequested(QString const& path) continue; } - QString const localFilePath = tor->getPath() + QLatin1Char('/') + path; + QString const local_file_path = tor->getPath() + QLatin1Char('/') + path; - if (!QFile::exists(localFilePath)) + if (!QFile::exists(local_file_path)) { continue; } - if (QDesktopServices::openUrl(QUrl::fromLocalFile(localFilePath))) + if (QDesktopServices::openUrl(QUrl::fromLocalFile(local_file_path))) { break; } diff --git a/qt/DetailsDialog.h b/qt/DetailsDialog.h index d5a6c75da..f20a3256d 100644 --- a/qt/DetailsDialog.h +++ b/qt/DetailsDialog.h @@ -93,12 +93,12 @@ private: Prefs& prefs_; TorrentModel const& model_; - Ui::DetailsDialog ui_; + Ui::DetailsDialog ui_ = {}; torrent_ids_t ids_; QTimer timer_; - bool changed_torrents_; - bool have_pending_refresh_; + bool changed_torrents_ = {}; + bool have_pending_refresh_ = {}; TrackerModel* tracker_model_ = {}; TrackerModelFilter* tracker_filter_ = {}; diff --git a/qt/FaviconCache.cc b/qt/FaviconCache.cc index b4d18c081..e96235afe 100644 --- a/qt/FaviconCache.cc +++ b/qt/FaviconCache.cc @@ -160,9 +160,9 @@ void FaviconCache::onRequestFinished(QNetworkReply* reply) pixmaps_[key] = scale(pixmap); // save it on disk... - QDir cacheDir(getCacheDir()); - cacheDir.mkpath(cacheDir.absolutePath()); - QFile file(cacheDir.absoluteFilePath(key)); + QDir cache_dir(getCacheDir()); + cache_dir.mkpath(cache_dir.absolutePath()); + QFile file(cache_dir.absoluteFilePath(key)); file.open(QIODevice::WriteOnly); file.write(content); file.close(); diff --git a/qt/FileTreeDelegate.cc b/qt/FileTreeDelegate.cc index a30c54209..6963cb4ce 100644 --- a/qt/FileTreeDelegate.cc +++ b/qt/FileTreeDelegate.cc @@ -67,9 +67,9 @@ void FileTreeDelegate::paint(QPainter* painter, QStyleOptionViewItem const& opti { QStyleOptionViewItem vi(option); vi.features |= QStyleOptionViewItem::HasCheckIndicator; - QRect checkRect = style->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &vi, nullptr); - checkRect.moveCenter(option.rect.center()); - drawCheck(painter, vi, checkRect, static_cast(index.data().toInt())); + QRect check_rect = style->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &vi, nullptr); + check_rect.moveCenter(option.rect.center()); + drawCheck(painter, vi, check_rect, static_cast(index.data().toInt())); } QItemDelegate::drawFocus(painter, option, option.rect); diff --git a/qt/FileTreeItem.cc b/qt/FileTreeItem.cc index 9e5f5441c..df2fbede6 100644 --- a/qt/FileTreeItem.cc +++ b/qt/FileTreeItem.cc @@ -7,6 +7,7 @@ */ #include +#include #include #include @@ -231,7 +232,7 @@ uint64_t FileTreeItem::size() const std::pair FileTreeItem::update(QString const& name, bool wanted, int priority, uint64_t have_size, bool update_fields) { int changed_count = 0; - int changed_columns[4]; + std::array changed_columns = {}; if (name_ != name) { @@ -272,9 +273,9 @@ std::pair FileTreeItem::update(QString const& name, bool wanted, int p if (changed_count > 0) { - std::sort(changed_columns, changed_columns + changed_count); - changed.first = changed_columns[0]; - changed.second = changed_columns[changed_count - 1]; + std::sort(changed_columns.begin(), changed_columns.end()); + changed.first = changed_columns.front(); + changed.second = changed_columns.back(); } return changed; diff --git a/qt/FileTreeModel.cc b/qt/FileTreeModel.cc index 977800411..3453d06b5 100644 --- a/qt/FileTreeModel.cc +++ b/qt/FileTreeModel.cc @@ -31,27 +31,27 @@ protected: QString token_; int slash_index_; - static QChar const slash_char; + static QChar const SlashChar; }; -QChar const PathIteratorBase::slash_char = QLatin1Char('/'); +QChar const PathIteratorBase::SlashChar = QLatin1Char('/'); class ForwardPathIterator : public PathIteratorBase { public: - ForwardPathIterator(QString const& path) : + explicit ForwardPathIterator(QString const& path) : PathIteratorBase(path, path.size() - 1) { } - bool hasNext() const + [[nodiscard]] bool hasNext() const { return slash_index_ > -1; } QString const& next() { - int new_slash_index = path_.lastIndexOf(slash_char, slash_index_); + int new_slash_index = path_.lastIndexOf(SlashChar, slash_index_); token_.truncate(0); token_ += path_.midRef(new_slash_index + 1, slash_index_ - new_slash_index); slash_index_ = new_slash_index - 1; @@ -62,19 +62,19 @@ public: class BackwardPathIterator : public PathIteratorBase { public: - BackwardPathIterator(QString const& path) : + explicit BackwardPathIterator(QString const& path) : PathIteratorBase(path, 0) { } - bool hasNext() const + [[nodiscard]] bool hasNext() const { return slash_index_ < path_.size(); } QString const& next() { - int new_slash_index = path_.indexOf(slash_char, slash_index_); + int new_slash_index = path_.indexOf(SlashChar, slash_index_); if (new_slash_index == -1) { @@ -274,18 +274,11 @@ QModelIndex FileTreeModel::parent(QModelIndex const& child, int column) const int FileTreeModel::rowCount(QModelIndex const& parent) const { - FileTreeItem* parentItem; + FileTreeItem* parent_item = parent.isValid() ? + itemFromIndex(parent) : + root_item_; - if (parent.isValid()) - { - parentItem = itemFromIndex(parent); - } - else - { - parentItem = root_item_; - } - - return parentItem->childCount(); + return parent_item->childCount(); } int FileTreeModel::columnCount(QModelIndex const& parent) const @@ -463,11 +456,11 @@ void FileTreeModel::emitParentsChanged(QModelIndex const& index, int first_colum } } -void FileTreeModel::emitSubtreeChanged(QModelIndex const& index, int first_column, int last_column) +void FileTreeModel::emitSubtreeChanged(QModelIndex const& idx, int first_column, int last_column) { assert(first_column <= last_column); - int const child_count = rowCount(index); + int const child_count = rowCount(idx); if (child_count == 0) { @@ -475,12 +468,12 @@ void FileTreeModel::emitSubtreeChanged(QModelIndex const& index, int first_colum } // tell everyone that this item changed - emit dataChanged(index.child(0, first_column), index.child(child_count - 1, last_column)); + emit dataChanged(index(0, first_column, idx), index(child_count - 1, last_column, idx)); // walk the subitems for (int i = 0; i < child_count; ++i) { - emitSubtreeChanged(index.child(i, 0), first_column, last_column); + emitSubtreeChanged(index(i, 0, idx), first_column, last_column); } } diff --git a/qt/FileTreeModel.h b/qt/FileTreeModel.h index 6237e3599..514b70b4d 100644 --- a/qt/FileTreeModel.h +++ b/qt/FileTreeModel.h @@ -8,10 +8,9 @@ #pragma once -#include +#include // uint64_t #include -#include #include #include diff --git a/qt/FileTreeView.cc b/qt/FileTreeView.cc index 9876b51e2..05fcc2f05 100644 --- a/qt/FileTreeView.cc +++ b/qt/FileTreeView.cc @@ -251,14 +251,14 @@ bool FileTreeView::edit(QModelIndex const& index, EditTrigger trigger, QEvent* e return false; } - QModelIndex const nameIndex = index.sibling(index.row(), FileTreeModel::COL_NAME); + QModelIndex const name_index = index.sibling(index.row(), FileTreeModel::COL_NAME); if (editTriggers().testFlag(trigger)) { - selectionModel()->setCurrentIndex(nameIndex, QItemSelectionModel::NoUpdate); + selectionModel()->setCurrentIndex(name_index, QItemSelectionModel::NoUpdate); } - return QTreeView::edit(nameIndex, trigger, event); + return QTreeView::edit(name_index, trigger, event); } void FileTreeView::checkSelectedItems() @@ -308,9 +308,11 @@ void FileTreeView::onlyCheckSelectedItems() continue; } + auto const* parent_model = parent_index.model(); + for (int i = 0, count = model_->rowCount(parent_index); i < count; ++i) { - QModelIndex const child_index = parent_index.child(i, 0); + QModelIndex const child_index = parent_model->index(i, 0, parent_index); int const child_check_state = child_index.data(FileTreeModel::WantedRole).toInt(); if (child_check_state == Qt::Unchecked || diff --git a/qt/FilterBar.cc b/qt/FilterBar.cc index 2795a6a54..ac82b5080 100644 --- a/qt/FilterBar.cc +++ b/qt/FilterBar.cc @@ -28,8 +28,8 @@ enum { - ActivityRole = FilterBarComboBox::UserRole, - TrackerRole + ACTIVITY_ROLE = FilterBarComboBox::UserRole, + TRACKER_ROLE }; /*** @@ -45,38 +45,38 @@ FilterBarComboBox* FilterBar::createActivityCombo() auto* model = new QStandardItemModel(this); auto* row = new QStandardItem(tr("All")); - row->setData(FilterMode::SHOW_ALL, ActivityRole); + row->setData(FilterMode::SHOW_ALL, ACTIVITY_ROLE); model->appendRow(row); model->appendRow(new QStandardItem); // separator delegate->setSeparator(model, model->index(1, 0)); row = new QStandardItem(QIcon::fromTheme(QStringLiteral("system-run")), tr("Active")); - row->setData(FilterMode::SHOW_ACTIVE, ActivityRole); + row->setData(FilterMode::SHOW_ACTIVE, ACTIVITY_ROLE); model->appendRow(row); row = new QStandardItem(QIcon::fromTheme(QStringLiteral("go-down")), tr("Downloading")); - row->setData(FilterMode::SHOW_DOWNLOADING, ActivityRole); + row->setData(FilterMode::SHOW_DOWNLOADING, ACTIVITY_ROLE); model->appendRow(row); row = new QStandardItem(QIcon::fromTheme(QStringLiteral("go-up")), tr("Seeding")); - row->setData(FilterMode::SHOW_SEEDING, ActivityRole); + row->setData(FilterMode::SHOW_SEEDING, ACTIVITY_ROLE); model->appendRow(row); row = new QStandardItem(QIcon::fromTheme(QStringLiteral("media-playback-pause")), tr("Paused")); - row->setData(FilterMode::SHOW_PAUSED, ActivityRole); + row->setData(FilterMode::SHOW_PAUSED, ACTIVITY_ROLE); model->appendRow(row); row = new QStandardItem(QIcon::fromTheme(QStringLiteral("dialog-ok")), tr("Finished")); - row->setData(FilterMode::SHOW_FINISHED, ActivityRole); + row->setData(FilterMode::SHOW_FINISHED, ACTIVITY_ROLE); model->appendRow(row); row = new QStandardItem(QIcon::fromTheme(QStringLiteral("view-refresh")), tr("Verifying")); - row->setData(FilterMode::SHOW_VERIFYING, ActivityRole); + row->setData(FilterMode::SHOW_VERIFYING, ACTIVITY_ROLE); model->appendRow(row); row = new QStandardItem(QIcon::fromTheme(QStringLiteral("process-stop")), tr("Error")); - row->setData(FilterMode::SHOW_ERROR, ActivityRole); + row->setData(FilterMode::SHOW_ERROR, ACTIVITY_ROLE); model->appendRow(row); c->setModel(model); @@ -119,13 +119,13 @@ void FilterBar::refreshTrackers() item->setData(int(num_trackers), FilterBarComboBox::CountRole); item->setData(getCountString(num_trackers), FilterBarComboBox::CountStringRole); - auto updateTrackerItem = [](QStandardItem* i, auto const& it) + auto update_tracker_item = [](QStandardItem* i, auto const& it) { auto const& display_name = it->first; auto const& count = it->second; auto const icon = qApp->faviconCache().find(FaviconCache::getKey(display_name)); i->setData(display_name, Qt::DisplayRole); - i->setData(display_name, TrackerRole); + i->setData(display_name, TRACKER_ROLE); i->setData(getCountString(count), FilterBarComboBox::CountStringRole); i->setData(icon, Qt::DecorationRole); i->setData(int(count), FilterBarComboBox::CountRole); @@ -144,7 +144,7 @@ void FilterBar::refreshTrackers() { if ((old_it == old_end) || ((new_it != new_end) && (old_it->first > new_it->first))) { - tracker_model_->insertRow(row, updateTrackerItem(new QStandardItem(1), new_it)); + tracker_model_->insertRow(row, update_tracker_item(new QStandardItem(1), new_it)); any_added = true; ++new_it; ++row; @@ -156,7 +156,7 @@ void FilterBar::refreshTrackers() } else // update { - updateTrackerItem(tracker_model_->item(row), new_it); + update_tracker_item(tracker_model_->item(row), new_it); ++old_it; ++new_it; ++row; @@ -178,7 +178,7 @@ FilterBarComboBox* FilterBar::createTrackerCombo(QStandardItemModel* model) c->setItemDelegate(delegate); auto* row = new QStandardItem(tr("All")); - row->setData(QString(), TrackerRole); + row->setData(QString(), TRACKER_ROLE); int const count = torrents_.rowCount(); row->setData(count, FilterBarComboBox::CountRole); row->setData(getCountString(count), FilterBarComboBox::CountStringRole); @@ -274,7 +274,7 @@ void FilterBar::refreshPref(int key) { auto const m = prefs_.get(key); QAbstractItemModel* model = activity_combo_->model(); - QModelIndexList indices = model->match(model->index(0, 0), ActivityRole, m.mode()); + QModelIndexList indices = model->match(model->index(0, 0), ACTIVITY_ROLE, m.mode()); activity_combo_->setCurrentIndex(indices.isEmpty() ? 0 : indices.first().row()); break; } @@ -315,7 +315,7 @@ void FilterBar::onTrackerIndexChanged(int i) if (!is_bootstrapping_) { QString str; - bool const is_tracker = !tracker_combo_->itemData(i, TrackerRole).toString().isEmpty(); + bool const is_tracker = !tracker_combo_->itemData(i, TRACKER_ROLE).toString().isEmpty(); if (!is_tracker) { @@ -323,7 +323,7 @@ void FilterBar::onTrackerIndexChanged(int i) } else { - str = tracker_combo_->itemData(i, TrackerRole).toString(); + str = tracker_combo_->itemData(i, TRACKER_ROLE).toString(); int const pos = str.lastIndexOf(QLatin1Char('.')); if (pos >= 0) @@ -340,7 +340,7 @@ void FilterBar::onActivityIndexChanged(int i) { if (!is_bootstrapping_) { - FilterMode const mode = activity_combo_->itemData(i, ActivityRole).toInt(); + FilterMode const mode = activity_combo_->itemData(i, ACTIVITY_ROLE).toInt(); prefs_.set(Prefs::FILTER_MODE, mode); } } @@ -362,13 +362,12 @@ void FilterBar::recount() { QAbstractItemModel* model = activity_combo_->model(); - int torrents_per_mode[FilterMode::NUM_MODES] = {}; - filter_.countTorrentsPerMode(torrents_per_mode); + auto const torrents_per_mode = filter_.countTorrentsPerMode(); for (int row = 0, n = model->rowCount(); row < n; ++row) { QModelIndex index = model->index(row, 0); - int const mode = index.data(ActivityRole).toInt(); + int const mode = index.data(ACTIVITY_ROLE).toInt(); int const count = torrents_per_mode[mode]; model->setData(index, count, FilterBarComboBox::CountRole); model->setData(index, getCountString(count), FilterBarComboBox::CountStringRole); diff --git a/qt/Filters.cc b/qt/Filters.cc index 4057bf36b..24bd344b9 100644 --- a/qt/Filters.cc +++ b/qt/Filters.cc @@ -8,7 +8,7 @@ #include "Filters.h" -QString const FilterMode::names_[NUM_MODES] = +std::array const FilterMode::Names = { QStringLiteral("show-all"), QStringLiteral("show-active"), @@ -24,7 +24,7 @@ int FilterMode::modeFromName(QString const& name) { for (int i = 0; i < NUM_MODES; ++i) { - if (names_[i] == name) + if (Names[i] == name) { return i; } @@ -33,7 +33,7 @@ int FilterMode::modeFromName(QString const& name) return FilterMode().mode(); // use the default value } -QString const SortMode::names_[NUM_MODES] = +std::array const SortMode::Names = { QStringLiteral("sort-by-activity"), QStringLiteral("sort-by-age"), @@ -51,7 +51,7 @@ int SortMode::modeFromName(QString const& name) { for (int i = 0; i < NUM_MODES; ++i) { - if (names_[i] == name) + if (Names[i] == name) { return i; } diff --git a/qt/Filters.h b/qt/Filters.h index 2230be973..189127b00 100644 --- a/qt/Filters.h +++ b/qt/Filters.h @@ -8,6 +8,8 @@ #pragma once +#include + #include #include #include @@ -53,13 +55,13 @@ public: static QString const& nameFromMode(int mode) { - return names_[mode]; + return Names[mode]; } private: int mode_; - static QString const names_[]; + static std::array const Names; }; Q_DECLARE_METATYPE(FilterMode) @@ -100,7 +102,7 @@ public: QString const& name() const { - return names_[mode_]; + return Names[mode_]; } static int modeFromName(QString const& name); @@ -109,7 +111,7 @@ public: private: int mode_ = SORT_BY_ID; - static QString const names_[]; + static std::array const Names; }; Q_DECLARE_METATYPE(SortMode) diff --git a/qt/Formatter.cc b/qt/Formatter.cc index 86b16f07a..c2e497aa7 100644 --- a/qt/Formatter.cc +++ b/qt/Formatter.cc @@ -6,6 +6,8 @@ * */ +#include + #include #include // tr_formatter @@ -19,57 +21,45 @@ namespace { -unsigned int speed_K; -unsigned int mem_K; -unsigned int size_K; +auto constexpr SpeedBase = 1000; +auto constexpr SizeBase = 1000; +auto constexpr MemBase = 1024; } // namespace -QString Formatter::unit_strings_[3][5]; +std::array, Formatter::NUM_TYPES> const Formatter::UnitStrings = +{{ + /* SPEED */ { tr("B/s"), tr("kB/s"), tr("MB/s"), tr("GB/s"), tr("TB/s") }, + /* SIZE */ { tr("B"), tr("kB"), tr("MB"), tr("GB"), tr("TB") }, + /* MEM */ { tr("B"), tr("KiB"), tr("MiB"), tr("GiB"), tr("TiB") } +}}; void Formatter::initUnits() { - speed_K = 1000; - unit_strings_[SPEED][B] = tr("B/s"); - unit_strings_[SPEED][KB] = tr("kB/s"); - unit_strings_[SPEED][MB] = tr("MB/s"); - unit_strings_[SPEED][GB] = tr("GB/s"); - unit_strings_[SPEED][TB] = tr("TB/s"); - tr_formatter_speed_init(speed_K, unit_strings_[SPEED][KB].toUtf8().constData(), - unit_strings_[SPEED][MB].toUtf8().constData(), - unit_strings_[SPEED][GB].toUtf8().constData(), unit_strings_[SPEED][TB].toUtf8().constData()); + tr_formatter_speed_init(SpeedBase, UnitStrings[SPEED][KB].toUtf8().constData(), + UnitStrings[SPEED][MB].toUtf8().constData(), UnitStrings[SPEED][GB].toUtf8().constData(), + UnitStrings[SPEED][TB].toUtf8().constData()); - size_K = 1000; - unit_strings_[SIZE][B] = tr("B"); - unit_strings_[SIZE][KB] = tr("kB"); - unit_strings_[SIZE][MB] = tr("MB"); - unit_strings_[SIZE][GB] = tr("GB"); - unit_strings_[SIZE][TB] = tr("TB"); - tr_formatter_size_init(size_K, unit_strings_[SIZE][KB].toUtf8().constData(), unit_strings_[SIZE][MB].toUtf8().constData(), - unit_strings_[SIZE][GB].toUtf8().constData(), unit_strings_[SIZE][TB].toUtf8().constData()); + tr_formatter_size_init(SizeBase, UnitStrings[SIZE][KB].toUtf8().constData(), + UnitStrings[SIZE][MB].toUtf8().constData(), + UnitStrings[SIZE][GB].toUtf8().constData(), UnitStrings[SIZE][TB].toUtf8().constData()); - mem_K = 1024; - unit_strings_[MEM][B] = tr("B"); - unit_strings_[MEM][KB] = tr("KiB"); - unit_strings_[MEM][MB] = tr("MiB"); - unit_strings_[MEM][GB] = tr("GiB"); - unit_strings_[MEM][TB] = tr("TiB"); - tr_formatter_mem_init(mem_K, unit_strings_[MEM][KB].toUtf8().constData(), unit_strings_[MEM][MB].toUtf8().constData(), - unit_strings_[MEM][GB].toUtf8().constData(), unit_strings_[MEM][TB].toUtf8().constData()); + tr_formatter_mem_init(MemBase, UnitStrings[MEM][KB].toUtf8().constData(), UnitStrings[MEM][MB].toUtf8().constData(), + UnitStrings[MEM][GB].toUtf8().constData(), UnitStrings[MEM][TB].toUtf8().constData()); } /*** **** ***/ -double Speed::KBps() const +double Speed::getKBps() const { - return _Bps / static_cast(speed_K); + return getBps() / static_cast(SpeedBase); } Speed Speed::fromKBps(double KBps) { - return static_cast(KBps * speed_K); + return Speed{ static_cast(KBps * SpeedBase) }; } /*** @@ -88,9 +78,9 @@ QString Formatter::memToString(int64_t bytes) return tr("None"); } - char buf[128]; - tr_formatter_mem_B(buf, bytes, sizeof(buf)); - return QString::fromUtf8(buf); + auto buf = std::array{}; + tr_formatter_mem_B(buf.data(), bytes, buf.size()); + return QString::fromUtf8(buf.data()); } QString Formatter::sizeToString(int64_t bytes) @@ -105,69 +95,58 @@ QString Formatter::sizeToString(int64_t bytes) return tr("None"); } - char buf[128]; - tr_formatter_size_B(buf, bytes, sizeof(buf)); - return QString::fromUtf8(buf); + auto buf = std::array{}; + tr_formatter_size_B(buf.data(), bytes, buf.size()); + return QString::fromUtf8(buf.data()); } QString Formatter::speedToString(Speed const& speed) { - char buf[128]; - tr_formatter_speed_KBps(buf, speed.KBps(), sizeof(buf)); - return QString::fromUtf8(buf); + auto buf = std::array{}; + tr_formatter_speed_KBps(buf.data(), speed.getKBps(), buf.size()); + return QString::fromUtf8(buf.data()); } QString Formatter::uploadSpeedToString(Speed const& upload_speed) { - static QChar constexpr upload_symbol(0x25B4); + static QChar constexpr UploadSymbol(0x25B4); - return tr("%1 %2").arg(speedToString(upload_speed)).arg(upload_symbol); + return tr("%1 %2").arg(speedToString(upload_speed)).arg(UploadSymbol); } QString Formatter::downloadSpeedToString(Speed const& download_speed) { - static QChar constexpr download_symbol(0x25BE); + static QChar constexpr DownloadSymbol(0x25BE); - return tr("%1 %2").arg(speedToString(download_speed)).arg(download_symbol); + return tr("%1 %2").arg(speedToString(download_speed)).arg(DownloadSymbol); } QString Formatter::percentToString(double x) { - char buf[128]; - return QString::fromUtf8(tr_strpercent(buf, x, sizeof(buf))); + auto buf = std::array{}; + return QString::fromUtf8(tr_strpercent(buf.data(), x, buf.size())); } QString Formatter::ratioToString(double ratio) { - char buf[128]; - return QString::fromUtf8(tr_strratio(buf, sizeof(buf), ratio, "\xE2\x88\x9E")); + auto buf = std::array{}; + return QString::fromUtf8(tr_strratio(buf.data(), buf.size(), ratio, "\xE2\x88\x9E")); } QString Formatter::timeToString(int seconds) { - int days; - int hours; - int minutes; - QString d; - QString h; - QString m; - QString s; - QString str; - - if (seconds < 0) - { - seconds = 0; - } - - days = seconds / 86400; - hours = (seconds % 86400) / 3600; - minutes = (seconds % 3600) / 60; + seconds = std::max(seconds, 0); + auto const days = seconds / 86400; + auto const hours = (seconds % 86400) / 3600; + auto const minutes = (seconds % 3600) / 60; seconds %= 60; - d = tr("%Ln day(s)", nullptr, days); - h = tr("%Ln hour(s)", nullptr, hours); - m = tr("%Ln minute(s)", nullptr, minutes); - s = tr("%Ln second(s)", nullptr, seconds); + auto const d = tr("%Ln day(s)", nullptr, days); + auto const h = tr("%Ln hour(s)", nullptr, hours); + auto const m = tr("%Ln minute(s)", nullptr, minutes); + auto const s = tr("%Ln second(s)", nullptr, seconds); + + QString str; if (days != 0) { diff --git a/qt/Formatter.h b/qt/Formatter.h index 39e34fc72..14be452fb 100644 --- a/qt/Formatter.h +++ b/qt/Formatter.h @@ -8,9 +8,10 @@ #pragma once +#include #include // int64_t -#include +#include // Q_DECLARE_TR_FUNCTIONS #include class Speed; @@ -26,14 +27,18 @@ public: KB, MB, GB, - TB + TB, + + NUM_SIZES }; enum Type { SPEED, SIZE, - MEM + MEM, + + NUM_TYPES }; public: @@ -48,11 +53,11 @@ public: static QString unitStr(Type t, Size s) { - return unit_strings_[t][s]; + return UnitStrings[t][s]; } static void initUnits(); private: - static QString unit_strings_[3][5]; + static std::array, Formatter::NUM_TYPES> const UnitStrings; }; diff --git a/qt/FreeSpaceLabel.cc b/qt/FreeSpaceLabel.cc index 3b9de6eb3..83038d967 100644 --- a/qt/FreeSpaceLabel.cc +++ b/qt/FreeSpaceLabel.cc @@ -19,17 +19,16 @@ namespace { -int const INTERVAL_MSEC = 15000; +int const IntervalMSec = 15000; } // namespace FreeSpaceLabel::FreeSpaceLabel(QWidget* parent) : QLabel(parent), - session_(nullptr), timer_(this) { timer_.setSingleShot(true); - timer_.setInterval(INTERVAL_MSEC); + timer_.setInterval(IntervalMSec); connect(&timer_, SIGNAL(timeout()), this, SLOT(onTimer())); } diff --git a/qt/InteropHelper.cc b/qt/InteropHelper.cc index 8797cf2eb..8c6e9c7e3 100644 --- a/qt/InteropHelper.cc +++ b/qt/InteropHelper.cc @@ -12,25 +12,21 @@ bool InteropHelper::isConnected() const { + bool is_connected = false; + #ifdef ENABLE_DBUS_INTEROP - if (dbus_client_.isConnected()) - { - return true; - } + is_connected |= dbus_client_.isConnected(); #endif #ifdef ENABLE_COM_INTEROP - if (com_client_.isConnected()) - { - return true; - } + is_connected |= com_client_.isConnected(); #endif - return false; + return is_connected; } bool InteropHelper::addMetainfo(QString const& metainfo) diff --git a/qt/InteropHelper.h b/qt/InteropHelper.h index 0b0bed3ca..1cd75d216 100644 --- a/qt/InteropHelper.h +++ b/qt/InteropHelper.h @@ -31,9 +31,9 @@ public: private: #ifdef ENABLE_DBUS_INTEROP - DBusInteropHelper dbus_client_; + DBusInteropHelper dbus_client_ = {}; #endif #ifdef ENABLE_COM_INTEROP - ComInteropHelper com_client_; + ComInteropHelper com_client_ = {}; #endif }; diff --git a/qt/InteropObject.cc b/qt/InteropObject.cc index 68edac8f6..5f0e5bd1f 100644 --- a/qt/InteropObject.cc +++ b/qt/InteropObject.cc @@ -15,12 +15,14 @@ InteropObject::InteropObject(QObject* parent) : { } +// NOLINTNEXTLINE(readability-identifier-naming) bool InteropObject::PresentWindow() { qApp->raise(); return true; } +// NOLINTNEXTLINE(readability-identifier-naming) bool InteropObject::AddMetainfo(QString const& metainfo) { AddData addme(metainfo); diff --git a/qt/LicenseDialog.h b/qt/LicenseDialog.h index 20ecf8c22..5efb1c46c 100644 --- a/qt/LicenseDialog.h +++ b/qt/LicenseDialog.h @@ -22,5 +22,5 @@ public: virtual ~LicenseDialog() = default; private: - Ui::LicenseDialog ui_; + Ui::LicenseDialog ui_ = {}; }; diff --git a/qt/MainWindow.cc b/qt/MainWindow.cc index 4ce76ef10..0f9a05b3f 100644 --- a/qt/MainWindow.cc +++ b/qt/MainWindow.cc @@ -6,7 +6,9 @@ * */ +#include #include +#include #include #include @@ -50,10 +52,10 @@ namespace { -auto const TOTAL_RATIO_STATS_MODE_NAME = QStringLiteral("total-ratio"); -auto const TOTAL_TRANSFER_STATS_MODE_NAME = QStringLiteral("total-transfer"); -auto const SESSION_RATIO_STATS_MODE_NAME = QStringLiteral("session-ratio"); -auto const SESSION_TRANSFER_STATS_MODE_NAME = QStringLiteral("session-transfer"); +auto const TotalRatioStatsModeName = QStringLiteral("total-ratio"); +auto const TotalTransferStatsModeName = QStringLiteral("total-transfer"); +auto const SessionRatioStatsModeName = QStringLiteral("session-ratio"); +auto const SessionTransferStatsModeName = QStringLiteral("session-transfer"); } // namespace @@ -184,17 +186,15 @@ MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool ui_.action_QueueMoveDown->setIcon(getStockIcon(QStringLiteral("go-down"), QStyle::SP_ArrowDown)); ui_.action_QueueMoveBottom->setIcon(getStockIcon(QStringLiteral("go-bottom"))); - auto makeNetworkPixmap = [this](char const* name_in, QSize size = QSize(16, 16)) + auto make_network_pixmap = [this](QString name, QSize size = { 16, 16 }) { - auto const name = QString::fromUtf8(name_in); - QIcon const icon = getStockIcon(name, QStyle::SP_DriveNetIcon); - return icon.pixmap(size); + return getStockIcon(name, QStyle::SP_DriveNetIcon).pixmap(size); }; - pixmap_network_error_ = makeNetworkPixmap("network-error"); - pixmap_network_idle_ = makeNetworkPixmap("network-idle"); - pixmap_network_receive_ = makeNetworkPixmap("network-receive"); - pixmap_network_transmit_ = makeNetworkPixmap("network-transmit"); - pixmap_network_transmit_receive_ = makeNetworkPixmap("network-transmit-receive"); + pixmap_network_error_ = make_network_pixmap(QStringLiteral("network-error")); + pixmap_network_idle_ = make_network_pixmap(QStringLiteral("network-idle")); + pixmap_network_receive_ = make_network_pixmap(QStringLiteral("network-receive")); + pixmap_network_transmit_ = make_network_pixmap(QStringLiteral("network-transmit")); + pixmap_network_transmit_receive_ = make_network_pixmap(QStringLiteral("network-transmit-receive")); // ui signals connect(ui_.action_Toolbar, SIGNAL(toggled(bool)), this, SLOT(setToolbarVisible(bool))); @@ -233,35 +233,36 @@ MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool connect(ui_.action_DeselectAll, SIGNAL(triggered()), ui_.listView, SLOT(clearSelection())); connect(ui_.action_Quit, SIGNAL(triggered()), qApp, SLOT(quit())); - auto refreshActionSensitivitySoon = [this]() { refreshSoon(REFRESH_ACTION_SENSITIVITY); }; - connect(&filter_model_, &TorrentFilter::rowsInserted, this, refreshActionSensitivitySoon); - connect(&filter_model_, &TorrentFilter::rowsRemoved, this, refreshActionSensitivitySoon); - connect(&model_, &TorrentModel::torrentsChanged, this, refreshActionSensitivitySoon); + auto refresh_action_sensitivity_soon = [this]() { refreshSoon(REFRESH_ACTION_SENSITIVITY); }; + connect(&filter_model_, &TorrentFilter::rowsInserted, this, refresh_action_sensitivity_soon); + connect(&filter_model_, &TorrentFilter::rowsRemoved, this, refresh_action_sensitivity_soon); + connect(&model_, &TorrentModel::torrentsChanged, this, refresh_action_sensitivity_soon); // torrent view filter_model_.setSourceModel(&model_); - auto refreshSoonAdapter = [this]() { refreshSoon(); }; - connect(&model_, &TorrentModel::modelReset, this, refreshSoonAdapter); - connect(&model_, &TorrentModel::rowsRemoved, this, refreshSoonAdapter); - connect(&model_, &TorrentModel::rowsInserted, this, refreshSoonAdapter); - connect(&model_, &TorrentModel::dataChanged, this, refreshSoonAdapter); + auto refresh_soon_adapter = [this]() { refreshSoon(); }; + connect(&model_, &TorrentModel::modelReset, this, refresh_soon_adapter); + connect(&model_, &TorrentModel::rowsRemoved, this, refresh_soon_adapter); + connect(&model_, &TorrentModel::rowsInserted, this, refresh_soon_adapter); + connect(&model_, &TorrentModel::dataChanged, this, refresh_soon_adapter); ui_.listView->setModel(&filter_model_); - connect(ui_.listView->selectionModel(), &QItemSelectionModel::selectionChanged, refreshActionSensitivitySoon); + connect(ui_.listView->selectionModel(), &QItemSelectionModel::selectionChanged, refresh_action_sensitivity_soon); - QPair const sort_modes[] = - { - qMakePair(ui_.action_SortByActivity, static_cast(SortMode::SORT_BY_ACTIVITY)), - qMakePair(ui_.action_SortByAge, static_cast(SortMode::SORT_BY_AGE)), - qMakePair(ui_.action_SortByETA, static_cast(SortMode::SORT_BY_ETA)), - qMakePair(ui_.action_SortByName, static_cast(SortMode::SORT_BY_NAME)), - qMakePair(ui_.action_SortByProgress, static_cast(SortMode::SORT_BY_PROGRESS)), - qMakePair(ui_.action_SortByQueue, static_cast(SortMode::SORT_BY_QUEUE)), - qMakePair(ui_.action_SortByRatio, static_cast(SortMode::SORT_BY_RATIO)), - qMakePair(ui_.action_SortBySize, static_cast(SortMode::SORT_BY_SIZE)), - qMakePair(ui_.action_SortByState, static_cast(SortMode::SORT_BY_STATE)) - }; + std::array, 9> const sort_modes = + {{ + { ui_.action_SortByActivity, SortMode::SORT_BY_ACTIVITY }, + { ui_.action_SortByAge, SortMode::SORT_BY_AGE }, + { ui_.action_SortByETA, SortMode::SORT_BY_ETA }, + { ui_.action_SortByName, SortMode::SORT_BY_NAME }, + { ui_.action_SortByProgress, SortMode::SORT_BY_PROGRESS }, + { ui_.action_SortByQueue, SortMode::SORT_BY_QUEUE }, + { ui_.action_SortByRatio, SortMode::SORT_BY_RATIO }, + { ui_.action_SortBySize, SortMode::SORT_BY_SIZE }, + { ui_.action_SortByState, SortMode::SORT_BY_STATE } + }}; + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) auto* action_group = new QActionGroup(this); for (auto const& mode : sort_modes) @@ -272,6 +273,7 @@ MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool connect(action_group, SIGNAL(triggered(QAction*)), this, SLOT(onSortModeChanged(QAction*))); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) alt_speed_action_ = new QAction(tr("Speed Limits"), this); alt_speed_action_->setIcon(ui_.altSpeedButton->icon()); alt_speed_action_->setCheckable(true); @@ -311,14 +313,26 @@ MainWindow::MainWindow(Session& session, Prefs& prefs, TorrentModel& model, bool connect(&filter_model_, &TorrentFilter::rowsRemoved, this, refresh_header_soon); connect(ui_.listView, SIGNAL(headerDoubleClicked()), filter_bar_, SLOT(clear())); - QList init_keys; - init_keys << Prefs::MAIN_WINDOW_X << Prefs::SHOW_TRAY_ICON << Prefs::SORT_REVERSED << Prefs::SORT_MODE << - Prefs::FILTERBAR << - Prefs::STATUSBAR << Prefs::STATUSBAR_STATS << Prefs::TOOLBAR << Prefs::ALT_SPEED_LIMIT_ENABLED << - Prefs::COMPACT_VIEW << Prefs::DSPEED << Prefs::DSPEED_ENABLED << Prefs::USPEED << Prefs::USPEED_ENABLED << - Prefs::RATIO << Prefs::RATIO_ENABLED; - - for (int const key : init_keys) + static std::array constexpr InitKeys = + { + Prefs::ALT_SPEED_LIMIT_ENABLED, + Prefs::COMPACT_VIEW, + Prefs::DSPEED, + Prefs::DSPEED_ENABLED, + Prefs::FILTERBAR, + Prefs::MAIN_WINDOW_X, + Prefs::RATIO, + Prefs::RATIO_ENABLED, + Prefs::SHOW_TRAY_ICON, + Prefs::SORT_MODE, + Prefs::SORT_REVERSED, + Prefs::STATUSBAR, + Prefs::STATUSBAR_STATS, + Prefs::TOOLBAR, + Prefs::USPEED, + Prefs::USPEED_ENABLED, + }; + for (auto const key : InitKeys) { refreshPref(key); } @@ -394,9 +408,10 @@ QMenu* MainWindow::createOptionsMenu() { auto const init_speed_sub_menu = [this](QMenu* menu, QAction*& off_action, QAction*& on_action, int pref, int enabled_pref) { - int const stock_speeds[] = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750 }; + std::array stock_speeds = { 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500, 750 }; int const current_value = prefs_.get(pref); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) auto* action_group = new QActionGroup(this); off_action = menu->addAction(tr("Unlimited")); @@ -421,9 +436,10 @@ QMenu* MainWindow::createOptionsMenu() } }; - auto const initSeedRatioSubMenu = [this](QMenu* menu, QAction*& off_action, QAction*& on_action, int pref, int enabled_pref) + auto const init_seed_ratio_sub_menu = + [this](QMenu* menu, QAction*& off_action, QAction*& on_action, int pref, int enabled_pref) { - double const stock_ratios[] = { 0.25, 0.50, 0.75, 1, 1.5, 2, 3 }; + std::array stock_ratios = { 0.25, 0.50, 0.75, 1, 1.5, 2, 3 }; auto const current_value = prefs_.get(pref); auto* action_group = new QActionGroup(this); @@ -459,7 +475,7 @@ QMenu* MainWindow::createOptionsMenu() menu->addSeparator(); - initSeedRatioSubMenu(menu->addMenu(tr("Stop Seeding at Ratio")), ratio_off_action_, ratio_on_action_, Prefs::RATIO, + init_seed_ratio_sub_menu(menu->addMenu(tr("Stop Seeding at Ratio")), ratio_off_action_, ratio_on_action_, Prefs::RATIO, Prefs::RATIO_ENABLED); return menu; @@ -467,26 +483,27 @@ QMenu* MainWindow::createOptionsMenu() QMenu* MainWindow::createStatsModeMenu() { - QPair const stats_modes[] = + std::array, 4> stats_modes = { - qMakePair(ui_.action_TotalRatio, TOTAL_RATIO_STATS_MODE_NAME), - qMakePair(ui_.action_TotalTransfer, TOTAL_TRANSFER_STATS_MODE_NAME), - qMakePair(ui_.action_SessionRatio, SESSION_RATIO_STATS_MODE_NAME), - qMakePair(ui_.action_SessionTransfer, SESSION_TRANSFER_STATS_MODE_NAME) + qMakePair(ui_.action_TotalRatio, TotalRatioStatsModeName), + qMakePair(ui_.action_TotalTransfer, TotalTransferStatsModeName), + qMakePair(ui_.action_SessionRatio, SessionRatioStatsModeName), + qMakePair(ui_.action_SessionTransfer, SessionTransferStatsModeName) }; - auto* actionGroup = new QActionGroup(this); + auto* action_group = new QActionGroup(this); auto* menu = new QMenu(this); for (auto const& mode : stats_modes) { mode.first->setProperty(STATS_MODE_KEY, QString(mode.second)); - actionGroup->addAction(mode.first); + action_group->addAction(mode.first); menu->addAction(mode.first); } - connect(actionGroup, SIGNAL(triggered(QAction*)), this, SLOT(onStatsModeChanged(QAction*))); + connect(action_group, SIGNAL(triggered(QAction*)), this, SLOT(onStatsModeChanged(QAction*))); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) return menu; } @@ -566,7 +583,7 @@ namespace #define HAVE_OPEN_SELECT -static void openSelect(QString const& path) +void openSelect(QString const& path) { auto const explorer = QStringLiteral("explorer"); QString param; @@ -584,7 +601,7 @@ static void openSelect(QString const& path) #define HAVE_OPEN_SELECT -static void openSelect(QString const& path) +void openSelect(QString const& path) { QStringList script_args; script_args << QStringLiteral("-e") << @@ -792,17 +809,17 @@ void MainWindow::refreshStatusBar(TransferStats const& stats) QString const mode(prefs_.getString(Prefs::STATUSBAR_STATS)); QString str; - if (mode == SESSION_RATIO_STATS_MODE_NAME) + if (mode == SessionRatioStatsModeName) { str = tr("Ratio: %1").arg(Formatter::ratioToString(session_.getStats().ratio)); } - else if (mode == SESSION_TRANSFER_STATS_MODE_NAME) + else if (mode == SessionTransferStatsModeName) { tr_session_stats const& stats(session_.getStats()); str = tr("Down: %1, Up: %2").arg(Formatter::sizeToString(stats.downloadedBytes)). arg(Formatter::sizeToString(stats.uploadedBytes)); } - else if (mode == TOTAL_TRANSFER_STATS_MODE_NAME) + else if (mode == TotalTransferStatsModeName) { tr_session_stats const& stats(session_.getCumulativeStats()); str = tr("Down: %1, Up: %2").arg(Formatter::sizeToString(stats.downloadedBytes)). @@ -810,7 +827,7 @@ void MainWindow::refreshStatusBar(TransferStats const& stats) } else // default is "total-ratio" { - assert(mode == TOTAL_RATIO_STATS_MODE_NAME); + assert(mode == TotalRatioStatsModeName); str = tr("Ratio: %1").arg(Formatter::ratioToString(session_.getCumulativeStats().ratio)); } @@ -849,12 +866,12 @@ void MainWindow::refreshActionSensitivity() auto const now = time(nullptr); for (int row = 0; row < row_count; ++row) { - QModelIndex const modelIndex(model->index(row, 0)); - auto const& tor = model->data(modelIndex, TorrentModel::TorrentRole).value(); + QModelIndex const model_index(model->index(row, 0)); + auto const& tor = model->data(model_index, TorrentModel::TorrentRole).value(); if (tor != nullptr) { - bool const is_selected = has_selection && selection_model->isSelected(modelIndex); + bool const is_selected = has_selection && selection_model->isSelected(model_index); bool const is_paused = tor->isPaused(); if (is_paused) @@ -926,6 +943,7 @@ void MainWindow::refreshActionSensitivity() *** **/ +// NOLINTNEXTLINE(readability-make-member-function-const) void MainWindow::clearSelection() { ui_.action_DeselectAll->trigger(); @@ -1245,7 +1263,7 @@ void MainWindow::refreshPref(int key) namespace { -auto const SHOW_OPTIONS_CHECKBOX_NAME = QStringLiteral("show-options-checkbox"); +auto const ShowOptionsCheckboxName = QStringLiteral("show-options-checkbox"); } // namespace @@ -1270,7 +1288,7 @@ void MainWindow::openTorrent() { auto* b = new QCheckBox(tr("Show &options dialog")); b->setChecked(prefs_.getBool(Prefs::OPTIONS_PROMPT)); - b->setObjectName(SHOW_OPTIONS_CHECKBOX_NAME); + b->setObjectName(ShowOptionsCheckboxName); l->addWidget(b, l->rowCount(), 0, 1, -1, Qt::AlignLeft); } @@ -1304,7 +1322,7 @@ void MainWindow::addTorrents(QStringList const& filenames) if (file_dialog != nullptr) { - auto const* const b = file_dialog->findChild(SHOW_OPTIONS_CHECKBOX_NAME); + auto const* const b = file_dialog->findChild(ShowOptionsCheckboxName); if (b != nullptr) { @@ -1443,12 +1461,12 @@ void MainWindow::removeTorrents(bool const delete_files) void MainWindow::updateNetworkIcon() { - static constexpr int const period = 3; + static constexpr int const Period = 3; time_t const now = time(nullptr); time_t const seconds_since_last_send = now - last_send_time_; time_t const seconds_since_last_read = now - last_read_time_; - bool const is_sending = seconds_since_last_send <= period; - bool const is_reading = seconds_since_last_read <= period; + bool const is_sending = seconds_since_last_send <= Period; + bool const is_reading = seconds_since_last_read <= Period; QPixmap pixmap; if (network_error_) diff --git a/qt/MainWindow.h b/qt/MainWindow.h index 5375dd78d..eaf29464d 100644 --- a/qt/MainWindow.h +++ b/qt/MainWindow.h @@ -149,7 +149,7 @@ private: QPixmap pixmap_network_transmit_; QPixmap pixmap_network_transmit_receive_; - Ui_MainWindow ui_; + Ui_MainWindow ui_ = {}; time_t last_full_update_time_ = {}; QPointer session_dialog_; diff --git a/qt/MakeDialog.cc b/qt/MakeDialog.cc index 8a6326127..2d1140df0 100644 --- a/qt/MakeDialog.cc +++ b/qt/MakeDialog.cc @@ -41,7 +41,7 @@ private slots: private: Session& session_; tr_metainfo_builder& builder_; - Ui::MakeProgressDialog ui_; + Ui::MakeProgressDialog ui_ = {}; QTimer timer_; }; diff --git a/qt/MakeDialog.h b/qt/MakeDialog.h index 2c0ed2dbe..58c740830 100644 --- a/qt/MakeDialog.h +++ b/qt/MakeDialog.h @@ -46,7 +46,7 @@ private slots: private: Session& session_; - Ui::MakeDialog ui_; + Ui::MakeDialog ui_ = {}; std::unique_ptr builder_; }; diff --git a/qt/OptionsDialog.cc b/qt/OptionsDialog.cc index 300a8f71b..c86efd39d 100644 --- a/qt/OptionsDialog.cc +++ b/qt/OptionsDialog.cc @@ -25,9 +25,9 @@ **** ***/ -OptionsDialog::OptionsDialog(Session& session, Prefs const& prefs, AddData const& addme, QWidget* parent) : +OptionsDialog::OptionsDialog(Session& session, Prefs const& prefs, AddData addme, QWidget* parent) : BaseDialog(parent), - add_(addme), + add_(std::move(addme)), verify_hash_(QCryptographicHash::Sha1), verify_button_(new QPushButton(tr("&Verify Local Data"), this)), edit_timer_(this), @@ -73,8 +73,8 @@ OptionsDialog::OptionsDialog(Session& session, Prefs const& prefs, AddData const ui_.sourceStack->setFixedHeight(ui_.sourceStack->currentWidget()->sizeHint().height()); ui_.sourceLabel->setBuddy(ui_.sourceStack->currentWidget()); - QFontMetrics const fontMetrics(font()); - int const width = fontMetrics.size(0, QStringLiteral("This is a pretty long torrent filename indeed.torrent")).width(); + QFontMetrics const font_metrics(font()); + int const width = font_metrics.size(0, QStringLiteral("This is a pretty long torrent filename indeed.torrent")).width(); ui_.sourceStack->setMinimumWidth(width); QString const download_dir(Utils::removeTrailingDirSeparator(prefs.getString(Prefs::DOWNLOAD_DIR))); @@ -422,11 +422,11 @@ void OptionsDialog::onTimeout() if (verify_file_.isOpen() && verify_file_.seek(verify_file_pos_)) { - int64_t numRead = verify_file_.read(verify_buf_, bytes_this_pass); + int64_t num_read = verify_file_.read(verify_buf_, bytes_this_pass); - if (numRead == bytes_this_pass) + if (num_read == bytes_this_pass) { - verify_hash_.addData(verify_buf_, numRead); + verify_hash_.addData(verify_buf_, num_read); } } diff --git a/qt/OptionsDialog.h b/qt/OptionsDialog.h index 68f0ba591..1ee645fb1 100644 --- a/qt/OptionsDialog.h +++ b/qt/OptionsDialog.h @@ -35,7 +35,7 @@ class OptionsDialog : public BaseDialog Q_OBJECT public: - OptionsDialog(Session& session, Prefs const& prefs, AddData const& addme, QWidget* parent = nullptr); + OptionsDialog(Session& session, Prefs const& prefs, AddData addme, QWidget* parent = nullptr); virtual ~OptionsDialog(); private: @@ -72,9 +72,9 @@ private: QVector wanted_; QVector priorities_; Session& session_; - Ui::OptionsDialog ui_; + Ui::OptionsDialog ui_ = {}; mybins_t verify_bins_; - tr_info info_; + tr_info info_ = {}; uint64_t verify_file_pos_ = {}; uint32_t verify_piece_index_ = {}; uint32_t verify_piece_pos_ = {}; diff --git a/qt/Prefs.cc b/qt/Prefs.cc index 2a5b0a2bd..6a8823894 100644 --- a/qt/Prefs.cc +++ b/qt/Prefs.cc @@ -25,10 +25,10 @@ **** ***/ -Prefs::PrefItem Prefs::items_[] = +std::array const Prefs::Items { /* gui settings */ - { OPTIONS_PROMPT, TR_KEY_show_options_window, QVariant::Bool }, + PrefItem{ OPTIONS_PROMPT, TR_KEY_show_options_window, QVariant::Bool }, { OPEN_DIALOG_FOLDER, TR_KEY_open_dialog_dir, QVariant::String }, { INHIBIT_HIBERNATION, TR_KEY_inhibit_desktop_hibernation, QVariant::Bool }, { DIR_WATCH, TR_KEY_watch_dir, QVariant::String }, @@ -125,16 +125,16 @@ Prefs::PrefItem Prefs::items_[] = **** ***/ -Prefs::Prefs(QString const& config_dir) : - config_dir_(config_dir) +Prefs::Prefs(QString config_dir) : + config_dir_(std::move(config_dir)) { - assert(sizeof(items_) / sizeof(items_[0]) == PREFS_COUNT); + static_assert(sizeof(Items) / sizeof(Items[0]) == PREFS_COUNT); #ifndef NDEBUG for (int i = 0; i < PREFS_COUNT; ++i) { - assert(items_[i].id == i); + assert(Items[i].id == i); } #endif @@ -155,9 +155,9 @@ Prefs::Prefs(QString const& config_dir) : int64_t int_val; char const* str; size_t str_len; - tr_variant* b(tr_variantDictFind(&top, items_[i].key)); + tr_variant* b(tr_variantDictFind(&top, Items[i].key)); - switch (items_[i].type) + switch (Items[i].type) { case QVariant::Int: if (tr_variantGetInt(b, &int_val)) @@ -237,10 +237,10 @@ Prefs::~Prefs() continue; } - tr_quark const key = items_[i].key; + tr_quark const key = Items[i].key; QVariant const& val = values_[i]; - switch (items_[i].type) + switch (Items[i].type) { case QVariant::Int: tr_variantDictAddInt(¤t_settings, key, val.toInt()); @@ -360,13 +360,13 @@ void Prefs::initDefaults(tr_variant* d) bool Prefs::getBool(int key) const { - assert(items_[key].type == QVariant::Bool); + assert(Items[key].type == QVariant::Bool); return values_[key].toBool(); } QString Prefs::getString(int key) const { - assert(items_[key].type == QVariant::String); + assert(Items[key].type == QVariant::String); QByteArray const b = values_[key].toByteArray(); if (Utils::isValidUtf8(b.constData())) @@ -379,19 +379,19 @@ QString Prefs::getString(int key) const int Prefs::getInt(int key) const { - assert(items_[key].type == QVariant::Int); + assert(Items[key].type == QVariant::Int); return values_[key].toInt(); } double Prefs::getDouble(int key) const { - assert(items_[key].type == QVariant::Double); + assert(Items[key].type == QVariant::Double); return values_[key].toDouble(); } QDateTime Prefs::getDateTime(int key) const { - assert(items_[key].type == QVariant::DateTime); + assert(Items[key].type == QVariant::DateTime); return values_[key].toDateTime(); } diff --git a/qt/Prefs.h b/qt/Prefs.h index 9bf1f5598..0e8615b41 100644 --- a/qt/Prefs.h +++ b/qt/Prefs.h @@ -8,6 +8,8 @@ #pragma once +#include + #include #include #include @@ -129,7 +131,7 @@ public: }; public: - Prefs(QString const& config_dir); + Prefs(QString config_dir); virtual ~Prefs(); bool isCore(int key) const @@ -144,17 +146,17 @@ public: char const* keyStr(int i) const { - return tr_quark_get_string(items_[i].key, nullptr); + return tr_quark_get_string(Items[i].key, nullptr); } tr_quark getKey(int i) const { - return items_[i].key; + return Items[i].key; } int type(int i) const { - return items_[i].type; + return Items[i].type; } QVariant const& variant(int i) const @@ -200,17 +202,15 @@ private: int type; }; -private: void initDefaults(tr_variant*); // Intentionally not implemented void set(int key, char const* value); -private: QString const config_dir_; QSet temporary_prefs_; QVariant mutable values_[PREFS_COUNT]; - static PrefItem items_[]; + static std::array const Items; }; diff --git a/qt/PrefsDialog.cc b/qt/PrefsDialog.cc index 1edf9ff95..a9dd2c173 100644 --- a/qt/PrefsDialog.cc +++ b/qt/PrefsDialog.cc @@ -25,7 +25,6 @@ #include #include #include -#include #include #include #include @@ -53,49 +52,49 @@ namespace class PreferenceWidget { - static char const* const PREF_KEY; + static char const* const PrefKey; public: explicit PreferenceWidget(QObject* object) : - m_object(object) + object_(object) { } template - bool is() const + [[nodiscard]] bool is() const { - return qobject_cast(m_object) != nullptr; + return qobject_cast(object_) != nullptr; } template - T const* as() const + [[nodiscard]] T const* as() const { assert(is()); - return static_cast(m_object); + return static_cast(object_); } template - T* as() + [[nodiscard]] T* as() { assert(is()); - return static_cast(m_object); + return static_cast(object_); } void setPrefKey(int key) { - m_object->setProperty(PREF_KEY, key); + object_->setProperty(PrefKey, key); } - int getPrefKey() const + [[nodiscard]] int getPrefKey() const { - return m_object->property(PREF_KEY).toInt(); + return object_->property(PrefKey).toInt(); } private: - QObject* const m_object; + QObject* const object_; }; -char const* const PreferenceWidget::PREF_KEY = "pref-key"; +char const* const PreferenceWidget::PrefKey = "pref-key"; int qtDayToTrDay(int day) { @@ -271,11 +270,11 @@ void PrefsDialog::lineEditingFinished() if (pref_widget.is()) { - auto const* const lineEdit = pref_widget.as(); + auto const* const line_edit = pref_widget.as(); - if (lineEdit->isModified()) + if (line_edit->isModified()) { - setPref(pref_widget.getPrefKey(), lineEdit->text()); + setPref(pref_widget.getPrefKey(), line_edit->text()); } } } @@ -324,13 +323,14 @@ void PrefsDialog::altSpeedDaysEdited(int i) void PrefsDialog::initSpeedTab() { - QString const speed_K_str = Formatter::unitStr(Formatter::SPEED, Formatter::KB); + QString const speed_unit_str = Formatter::unitStr(Formatter::SPEED, Formatter::KB); + auto const suffix = QStringLiteral(" %1").arg(speed_unit_str); QLocale const locale; - ui_.uploadSpeedLimitSpin->setSuffix(QStringLiteral(" %1").arg(speed_K_str)); - ui_.downloadSpeedLimitSpin->setSuffix(QStringLiteral(" %1").arg(speed_K_str)); - ui_.altUploadSpeedLimitSpin->setSuffix(QStringLiteral(" %1").arg(speed_K_str)); - ui_.altDownloadSpeedLimitSpin->setSuffix(QStringLiteral(" %1").arg(speed_K_str)); + ui_.uploadSpeedLimitSpin->setSuffix(suffix); + ui_.downloadSpeedLimitSpin->setSuffix(suffix); + ui_.altUploadSpeedLimitSpin->setSuffix(suffix); + ui_.altDownloadSpeedLimitSpin->setSuffix(suffix); ui_.altSpeedLimitDaysCombo->addItem(tr("Every Day"), QVariant(TR_SCHED_ALL)); ui_.altSpeedLimitDaysCombo->addItem(tr("Weekdays"), QVariant(TR_SCHED_WEEKDAY)); @@ -616,12 +616,21 @@ PrefsDialog::PrefsDialog(Session& session, Prefs& prefs, QWidget* parent) : connect(&session_, SIGNAL(sessionUpdated()), SLOT(sessionUpdated())); - QList keys; - keys << Prefs::RPC_ENABLED << Prefs::ALT_SPEED_LIMIT_ENABLED << Prefs::ALT_SPEED_LIMIT_TIME_ENABLED << Prefs::ENCRYPTION << - Prefs::BLOCKLIST_ENABLED << Prefs::DIR_WATCH << Prefs::DOWNLOAD_DIR << Prefs::INCOMPLETE_DIR << - Prefs::INCOMPLETE_DIR_ENABLED << Prefs::SCRIPT_TORRENT_DONE_FILENAME; + static std::array constexpr InitKeys = + { + Prefs::ALT_SPEED_LIMIT_ENABLED, + Prefs::ALT_SPEED_LIMIT_TIME_ENABLED, + Prefs::BLOCKLIST_ENABLED, + Prefs::DIR_WATCH, + Prefs::DOWNLOAD_DIR, + Prefs::ENCRYPTION, + Prefs::INCOMPLETE_DIR, + Prefs::INCOMPLETE_DIR_ENABLED, + Prefs::RPC_ENABLED, + Prefs::SCRIPT_TORRENT_DONE_FILENAME + }; - for (int const key : keys) + for (auto const key : InitKeys) { refreshPref(key); } @@ -744,9 +753,9 @@ void PrefsDialog::refreshPref(int key) { if (key == Prefs::ENCRYPTION) { - auto* comboBox = qobject_cast(w); - int const index = comboBox->findData(prefs_.getInt(key)); - comboBox->setCurrentIndex(index); + auto* combo_box = qobject_cast(w); + int const index = combo_box->findData(prefs_.getInt(key)); + combo_box->setCurrentIndex(index); } } } diff --git a/qt/PrefsDialog.h b/qt/PrefsDialog.h index 8d57e84d6..c5a09838a 100644 --- a/qt/PrefsDialog.h +++ b/qt/PrefsDialog.h @@ -73,7 +73,7 @@ private: Session& session_; Prefs& prefs_; - Ui::PrefsDialog ui_; + Ui::PrefsDialog ui_ = {}; bool const is_server_; bool is_local_ = {}; diff --git a/qt/RelocateDialog.cc b/qt/RelocateDialog.cc index a34d87d29..cce5700f9 100644 --- a/qt/RelocateDialog.cc +++ b/qt/RelocateDialog.cc @@ -13,23 +13,23 @@ #include "Torrent.h" #include "TorrentModel.h" -bool RelocateDialog::move_flag_ = true; +bool RelocateDialog::move_flag = true; void RelocateDialog::onSetLocation() { - session_.torrentSetLocation(ids_, newLocation(), move_flag_); + session_.torrentSetLocation(ids_, newLocation(), move_flag); close(); } void RelocateDialog::onMoveToggled(bool b) { - move_flag_ = b; + move_flag = b; } -RelocateDialog::RelocateDialog(Session& session, TorrentModel const& model, torrent_ids_t const& ids, QWidget* parent) : +RelocateDialog::RelocateDialog(Session& session, TorrentModel const& model, torrent_ids_t ids, QWidget* parent) : BaseDialog(parent), session_(session), - ids_(ids) + ids_(std::move(ids)) { ui_.setupUi(this); @@ -75,7 +75,7 @@ RelocateDialog::RelocateDialog(Session& session, TorrentModel const& model, torr ui_.newLocationStack->setFixedHeight(ui_.newLocationStack->currentWidget()->sizeHint().height()); ui_.newLocationLabel->setBuddy(ui_.newLocationStack->currentWidget()); - if (move_flag_) + if (move_flag) { ui_.moveDataRadio->setChecked(true); } diff --git a/qt/RelocateDialog.h b/qt/RelocateDialog.h index ed57fb2bd..2ea6a61dc 100644 --- a/qt/RelocateDialog.h +++ b/qt/RelocateDialog.h @@ -21,7 +21,7 @@ class RelocateDialog : public BaseDialog Q_OBJECT public: - RelocateDialog(Session&, TorrentModel const&, torrent_ids_t const& ids, QWidget* parent = nullptr); + RelocateDialog(Session&, TorrentModel const&, torrent_ids_t ids, QWidget* parent = nullptr); virtual ~RelocateDialog() = default; @@ -36,7 +36,7 @@ private: Session& session_; torrent_ids_t const ids_; - Ui::RelocateDialog ui_; + Ui::RelocateDialog ui_ = {}; - static bool move_flag_; + static bool move_flag; }; diff --git a/qt/RpcQueue.cc b/qt/RpcQueue.cc index a437a2d54..ef37aad0f 100644 --- a/qt/RpcQueue.cc +++ b/qt/RpcQueue.cc @@ -66,7 +66,7 @@ void RpcQueue::runNext(RpcResponseFuture const& response) { assert(!queue_.isEmpty()); - RpcResponseFuture const oldFuture = future_watcher_.future(); + RpcResponseFuture const old_future = future_watcher_.future(); while (true) { @@ -74,7 +74,7 @@ void RpcQueue::runNext(RpcResponseFuture const& response) next_error_handler_ = next.second; future_watcher_.setFuture((next.first)(response)); - if (oldFuture != future_watcher_.future()) + if (old_future != future_watcher_.future()) { break; } diff --git a/qt/Session.cc b/qt/Session.cc index 30c6e38df..07ef738d2 100644 --- a/qt/Session.cc +++ b/qt/Session.cc @@ -55,10 +55,10 @@ void addList(tr_variant* list, KeyList const& keys) } // If this object is passed as "ids" (compared by address), then recently active torrents are queried. -auto const recently_active_ids = torrent_ids_t{ -1 }; +auto const RecentlyActiveIDs = torrent_ids_t{ -1 }; // If this object is passed as "ids" (compared by being empty), then all torrents are queried. -auto const all_ids = torrent_ids_t{}; +auto const AllIDs = torrent_ids_t{}; } // namespace @@ -297,8 +297,8 @@ void Session::updatePref(int key) **** ***/ -Session::Session(QString const& config_dir, Prefs& prefs) : - config_dir_(config_dir), +Session::Session(QString config_dir, Prefs& prefs) : + config_dir_(std::move(config_dir)), prefs_(prefs) { stats_.ratio = TR_RATIO_NA; @@ -405,7 +405,7 @@ namespace void addOptionalIds(tr_variant* args, torrent_ids_t const& ids) { - if (&ids == &recently_active_ids) + if (&ids == &RecentlyActiveIDs) { tr_variantDictAddStr(args, TR_KEY_ids, "recently-active"); } @@ -527,7 +527,7 @@ void Session::torrentRenamePath(torrent_ids_t const& ids, QString const& oldpath tr_variantDictFindStr(r.args.get(), TR_KEY_name, &name, nullptr); auto* d = new QMessageBox(QMessageBox::Information, tr("Error Renaming Path"), - tr("

Unable to rename \"%1\" as \"%2\": %3.

Please correct the errors and try again.

"). + tr(R"(

Unable to rename "%1" as "%2": %3.

Please correct the errors and try again.

)"). arg(QString::fromUtf8(path)).arg(QString::fromUtf8(name)).arg(r.result), QMessageBox::Close, qApp->activeWindow()); QObject::connect(d, &QMessageBox::rejected, d, &QMessageBox::deleteLater); @@ -579,12 +579,12 @@ void Session::refreshTorrents(torrent_ids_t const& ids, KeyList const& keys) void Session::refreshDetailInfo(torrent_ids_t const& ids) { - refreshTorrents(ids, Torrent::detailInfoKeys); + refreshTorrents(ids, Torrent::DetailInfoKeys); } void Session::refreshExtraStats(torrent_ids_t const& ids) { - refreshTorrents(ids, Torrent::mainStatKeys + Torrent::detailStatKeys); + refreshTorrents(ids, Torrent::MainStatKeys + Torrent::DetailStatKeys); } void Session::sendTorrentRequest(char const* request, torrent_ids_t const& ids) @@ -602,7 +602,7 @@ void Session::sendTorrentRequest(char const* request, torrent_ids_t const& ids) q->add([this, ids]() { - refreshTorrents(ids, Torrent::mainStatKeys); + refreshTorrents(ids, Torrent::MainStatKeys); }); q->run(); @@ -645,17 +645,17 @@ void Session::queueMoveBottom(torrent_ids_t const& ids) void Session::refreshActiveTorrents() { - refreshTorrents(recently_active_ids, Torrent::mainStatKeys); + refreshTorrents(RecentlyActiveIDs, Torrent::MainStatKeys); } void Session::refreshAllTorrents() { - refreshTorrents(all_ids, Torrent::mainStatKeys); + refreshTorrents(AllIDs, Torrent::MainStatKeys); } void Session::initTorrents(torrent_ids_t const& ids) { - refreshTorrents(ids, Torrent::allMainKeys); + refreshTorrents(ids, Torrent::AllMainKeys); } void Session::refreshSessionStats() @@ -999,7 +999,7 @@ void Session::addTorrent(AddData const& add_me, tr_variant* args, bool trash_ori { QString const name = QString::fromUtf8(str); auto* d = new QMessageBox(QMessageBox::Warning, tr("Add Torrent"), - tr("

Unable to add \"%1\".

It is a duplicate of \"%2\" which is already added.

"). + tr(R"(

Unable to add "%1".

It is a duplicate of "%2" which is already added.

)"). arg(add_me.readableShortName()).arg(name), QMessageBox::Close, qApp->activeWindow()); QObject::connect(d, &QMessageBox::rejected, d, &QMessageBox::deleteLater); d->show(); diff --git a/qt/Session.h b/qt/Session.h index 543b28a69..a0eb06b76 100644 --- a/qt/Session.h +++ b/qt/Session.h @@ -32,7 +32,7 @@ class Session : public QObject Q_OBJECT public: - Session(QString const& config_dir, Prefs& prefs); + Session(QString config_dir, Prefs& prefs); virtual ~Session(); void stop(); @@ -143,8 +143,8 @@ private: int64_t blocklist_size_ = -1; tr_session* session_ = {}; QStringList idle_json_; - tr_session_stats stats_; - tr_session_stats cumulative_stats_; + tr_session_stats stats_ = {}; + tr_session_stats cumulative_stats_ = {}; QString session_version_; QString session_id_; bool is_definitely_local_session_ = true; diff --git a/qt/SessionDialog.h b/qt/SessionDialog.h index 7f57cb2a5..5193afc3a 100644 --- a/qt/SessionDialog.h +++ b/qt/SessionDialog.h @@ -35,7 +35,7 @@ private: Session& session_; Prefs& prefs_; - Ui::SessionDialog ui_; + Ui::SessionDialog ui_ = {}; QWidgetList remote_widgets_; QWidgetList auth_widgets_; diff --git a/qt/Speed.h b/qt/Speed.h index f31b087c7..eedbd745a 100644 --- a/qt/Speed.h +++ b/qt/Speed.h @@ -13,62 +13,62 @@ class Speed public: Speed() = default; - double KBps() const; + double getKBps() const; - int Bps() const + [[nodiscard]] int getBps() const { - return _Bps; + return bytes_per_second_; } - bool isZero() const + [[nodiscard]] bool isZero() const { - return _Bps == 0; + return bytes_per_second_ == 0; } static Speed fromKBps(double KBps); static Speed fromBps(int Bps) { - return Speed(Bps); + return Speed{ Bps }; } void setBps(int Bps) { - _Bps = Bps; + bytes_per_second_ = Bps; } Speed& operator +=(Speed const& that) { - _Bps += that._Bps; + bytes_per_second_ += that.bytes_per_second_; return *this; } - Speed operator +(Speed const& that) const + [[nodiscard]] Speed operator +(Speed const& that) const { - return Speed(_Bps + that._Bps); + return Speed{ getBps() + that.getBps() }; } - bool operator <(Speed const& that) const + [[nodiscard]] bool operator <(Speed const& that) const { - return _Bps < that._Bps; + return getBps() < that.getBps(); } - bool operator ==(Speed const& that) const + [[nodiscard]] bool operator ==(Speed const& that) const { - return _Bps == that._Bps; + return getBps() == that.getBps(); } - bool operator !=(Speed const& that) const + [[nodiscard]] bool operator !=(Speed const& that) const { - return _Bps != that._Bps; + return getBps() != that.getBps(); } private: - Speed(int Bps) : - _Bps(Bps) + explicit Speed(int bytes_per_second) : + bytes_per_second_{bytes_per_second} { } private: - int _Bps = 0; + int bytes_per_second_ = {}; }; diff --git a/qt/SqueezeLabel.cc b/qt/SqueezeLabel.cc index 4788ea271..e813536dd 100644 --- a/qt/SqueezeLabel.cc +++ b/qt/SqueezeLabel.cc @@ -66,11 +66,11 @@ void SqueezeLabel::paintEvent(QPaintEvent* paintEvent) QFontMetrics fm = fontMetrics(); QStyleOption opt; opt.initFrom(this); - QString const fullText = text(); - QString const elidedText = fm.elidedText(fullText, Qt::ElideRight, width()); - style()->drawItemText(&painter, contentsRect(), alignment(), opt.palette, isEnabled(), elidedText, foregroundRole()); + auto const full_text = text(); + auto const elided_text = fm.elidedText(full_text, Qt::ElideRight, width()); + style()->drawItemText(&painter, contentsRect(), alignment(), opt.palette, isEnabled(), elided_text, foregroundRole()); #ifndef QT_NO_TOOLTIP - setToolTip(fullText != elidedText ? fullText : QString()); + setToolTip(full_text != elided_text ? full_text : QString{}); #endif } diff --git a/qt/StatsDialog.h b/qt/StatsDialog.h index 0239e28f7..bf202ea54 100644 --- a/qt/StatsDialog.h +++ b/qt/StatsDialog.h @@ -33,7 +33,7 @@ private slots: private: Session& session_; - Ui::StatsDialog ui_; + Ui::StatsDialog ui_ = {}; QTimer* timer_ = {}; }; diff --git a/qt/Torrent.cc b/qt/Torrent.cc index 395118334..9e9101b4a 100644 --- a/qt/Torrent.cc +++ b/qt/Torrent.cc @@ -27,7 +27,7 @@ ***/ // unchanging fields needed by the main window -Torrent::KeyList const Torrent::mainInfoKeys{ +Torrent::KeyList const Torrent::MainInfoKeys{ TR_KEY_addedDate, TR_KEY_downloadDir, TR_KEY_hashString, @@ -38,7 +38,7 @@ Torrent::KeyList const Torrent::mainInfoKeys{ }; // changing fields needed by the main window -Torrent::KeyList const Torrent::mainStatKeys{ +Torrent::KeyList const Torrent::MainStatKeys{ TR_KEY_downloadedEver, TR_KEY_error, TR_KEY_errorString, @@ -66,10 +66,10 @@ Torrent::KeyList const Torrent::mainStatKeys{ TR_KEY_webseedsSendingToUs }; -Torrent::KeyList const Torrent::allMainKeys = Torrent::mainInfoKeys + Torrent::mainStatKeys; +Torrent::KeyList const Torrent::AllMainKeys = Torrent::MainInfoKeys + Torrent::MainStatKeys; // unchanging fields needed by the details dialog -Torrent::KeyList const Torrent::detailInfoKeys{ +Torrent::KeyList const Torrent::DetailInfoKeys{ TR_KEY_comment, TR_KEY_creator, TR_KEY_dateCreated, @@ -82,7 +82,7 @@ Torrent::KeyList const Torrent::detailInfoKeys{ }; // changing fields needed by the details dialog -Torrent::KeyList const Torrent::detailStatKeys{ +Torrent::KeyList const Torrent::DetailStatKeys{ TR_KEY_activityDate, TR_KEY_bandwidthPriority, TR_KEY_corruptEver, @@ -350,17 +350,17 @@ bool change(QVector& setme, tr_variant const* value) bool Torrent::getSeedRatio(double& setmeRatio) const { - bool isLimited; + bool is_limited; switch (seedRatioMode()) { case TR_RATIOLIMIT_SINGLE: - isLimited = true; + is_limited = true; setmeRatio = seedRatioLimit(); break; case TR_RATIOLIMIT_GLOBAL: - if ((isLimited = prefs_.getBool(Prefs::RATIO_ENABLED))) + if ((is_limited = prefs_.getBool(Prefs::RATIO_ENABLED))) { setmeRatio = prefs_.getDouble(Prefs::RATIO); } @@ -368,11 +368,11 @@ bool Torrent::getSeedRatio(double& setmeRatio) const break; default: // TR_RATIOLIMIT_UNLIMITED: - isLimited = false; + is_limited = false; break; } - return isLimited; + return is_limited; } bool Torrent::hasTrackerSubstring(QString const& substr) const @@ -619,17 +619,17 @@ bool Torrent::update(tr_quark const* keys, tr_variant const* const* values, size trackers_.swap(urls); // rebuild trackerDisplayNames - QStringList displayNames; - displayNames.reserve(trackers_.size()); + QStringList display_names; + display_names.reserve(trackers_.size()); for (auto const& tracker : trackers_) { auto const url = QUrl(tracker); auto const key = qApp->faviconCache().add(url); - displayNames.append(FaviconCache::getDisplayName(key)); + display_names.append(FaviconCache::getDisplayName(key)); } - displayNames.removeDuplicates(); - tracker_display_names_.swap(displayNames); + display_names.removeDuplicates(); + tracker_display_names_.swap(display_names); break; } } diff --git a/qt/Torrent.h b/qt/Torrent.h index 5bcac5574..e6012cce2 100644 --- a/qt/Torrent.h +++ b/qt/Torrent.h @@ -502,11 +502,11 @@ public: } using KeyList = QSet; - static KeyList const allMainKeys; - static KeyList const detailInfoKeys; - static KeyList const detailStatKeys; - static KeyList const mainInfoKeys; - static KeyList const mainStatKeys; + static KeyList const AllMainKeys; + static KeyList const DetailInfoKeys; + static KeyList const DetailStatKeys; + static KeyList const MainInfoKeys; + static KeyList const MainStatKeys; private: void updateMimeIcon(); diff --git a/qt/TorrentDelegate.cc b/qt/TorrentDelegate.cc index a86dc5650..13c12bcec 100644 --- a/qt/TorrentDelegate.cc +++ b/qt/TorrentDelegate.cc @@ -28,12 +28,12 @@ enum BAR_HEIGHT = 12 }; -QColor TorrentDelegate::green_brush_; -QColor TorrentDelegate::blue_brush_; -QColor TorrentDelegate::silver_brush_; -QColor TorrentDelegate::green_back_; -QColor TorrentDelegate::blue_back_; -QColor TorrentDelegate::silver_back_; +QColor TorrentDelegate::green_brush; +QColor TorrentDelegate::blue_brush; +QColor TorrentDelegate::silver_brush; +QColor TorrentDelegate::green_back; +QColor TorrentDelegate::blue_back; +QColor TorrentDelegate::silver_back; namespace { @@ -57,42 +57,41 @@ public: QRect bar_rect; QRect progress_rect; - ItemLayout(QString const& name_text, QString const& status_text, QString const& progress_text, QIcon const& emblem_icon, - QFont const& base_font, Qt::LayoutDirection direction, QPoint const& top_left, int width); + ItemLayout(QString name_text, QString status_text, QString progress_text, QIcon const& emblem_icon, QFont const& base_font, + Qt::LayoutDirection direction, QPoint const& top_left, int width); - QSize size() const + [[nodiscard]] QSize size() const { return (icon_rect | name_rect | status_rect | bar_rect | progress_rect).size(); } - QString nameText() const + [[nodiscard]] QString nameText() const { return elidedText(name_font, name_text_, name_rect.width()); } - QString statusText() const + [[nodiscard]] QString statusText() const { return elidedText(status_font, status_text_, status_rect.width()); } - QString progressText() const + [[nodiscard]] QString progressText() const { return elidedText(progress_font, progress_text_, progress_rect.width()); } private: - QString elidedText(QFont const& font, QString const& text, int width) const + [[nodiscard]] QString elidedText(QFont const& font, QString const& text, int width) const { return QFontMetrics(font).elidedText(text, Qt::ElideRight, width); } }; -ItemLayout::ItemLayout(QString const& name_text, QString const& status_text, QString const& progress_text, - QIcon const& emblem_icon, QFont const& base_font, Qt::LayoutDirection direction, QPoint const& top_left, - int width) : - name_text_(name_text), - status_text_(status_text), - progress_text_(progress_text), +ItemLayout::ItemLayout(QString name_text, QString status_text, QString progress_text, QIcon const& emblem_icon, + QFont const& base_font, Qt::LayoutDirection direction, QPoint const& top_left, int width) : + name_text_(std::move(name_text)), + status_text_(std::move(status_text)), + progress_text_(std::move(progress_text)), name_font(base_font), status_font(base_font), progress_font(base_font) @@ -134,14 +133,14 @@ TorrentDelegate::TorrentDelegate(QObject* parent) : progress_bar_style_->minimum = 0; progress_bar_style_->maximum = 1000; - green_brush_ = QColor("forestgreen"); - green_back_ = QColor("darkseagreen"); + green_brush = QColor("forestgreen"); + green_back = QColor("darkseagreen"); - blue_brush_ = QColor("steelblue"); - blue_back_ = QColor("lightgrey"); + blue_brush = QColor("steelblue"); + blue_back = QColor("lightgrey"); - silver_brush_ = QColor("silver"); - silver_back_ = QColor("grey"); + silver_brush = QColor("silver"); + silver_back = QColor("grey"); } TorrentDelegate::~TorrentDelegate() @@ -538,14 +537,14 @@ void TorrentDelegate::drawTorrent(QPainter* painter, QStyleOptionViewItem const& cr = QPalette::Text; } - QStyle::State progressBarState(option.state); + QStyle::State progress_bar_state(option.state); if (is_paused) { - progressBarState = QStyle::State_None; + progress_bar_state = QStyle::State_None; } - progressBarState |= QStyle::State_Small; + progress_bar_state |= QStyle::State_Small; QIcon::Mode const emblem_im = is_item_selected ? QIcon::Selected : QIcon::Normal; QIcon const emblem_icon = tor.hasError() ? getWarningEmblem() : QIcon(); @@ -583,24 +582,24 @@ void TorrentDelegate::drawTorrent(QPainter* painter, QStyleOptionViewItem const& if (tor.isDownloading()) { - progress_bar_style_->palette.setBrush(QPalette::Highlight, blue_brush_); - progress_bar_style_->palette.setColor(QPalette::Base, blue_back_); - progress_bar_style_->palette.setColor(QPalette::Window, blue_back_); + progress_bar_style_->palette.setBrush(QPalette::Highlight, blue_brush); + progress_bar_style_->palette.setColor(QPalette::Base, blue_back); + progress_bar_style_->palette.setColor(QPalette::Window, blue_back); } else if (tor.isSeeding()) { - progress_bar_style_->palette.setBrush(QPalette::Highlight, green_brush_); - progress_bar_style_->palette.setColor(QPalette::Base, green_back_); - progress_bar_style_->palette.setColor(QPalette::Window, green_back_); + progress_bar_style_->palette.setBrush(QPalette::Highlight, green_brush); + progress_bar_style_->palette.setColor(QPalette::Base, green_back); + progress_bar_style_->palette.setColor(QPalette::Window, green_back); } else { - progress_bar_style_->palette.setBrush(QPalette::Highlight, silver_brush_); - progress_bar_style_->palette.setColor(QPalette::Base, silver_back_); - progress_bar_style_->palette.setColor(QPalette::Window, silver_back_); + progress_bar_style_->palette.setBrush(QPalette::Highlight, silver_brush); + progress_bar_style_->palette.setColor(QPalette::Base, silver_back); + progress_bar_style_->palette.setColor(QPalette::Window, silver_back); } - progress_bar_style_->state = progressBarState; + progress_bar_style_->state = progress_bar_state; setProgressBarPercentDone(option, tor); style->drawControl(QStyle::CE_ProgressBar, progress_bar_style_, painter); diff --git a/qt/TorrentDelegate.h b/qt/TorrentDelegate.h index 50ce682f8..56956f006 100644 --- a/qt/TorrentDelegate.h +++ b/qt/TorrentDelegate.h @@ -45,12 +45,12 @@ protected: QStyleOptionProgressBar* progress_bar_style_ = {}; - static QColor blue_brush_; - static QColor green_brush_; - static QColor silver_brush_; - static QColor blue_back_; - static QColor green_back_; - static QColor silver_back_; + static QColor blue_brush; + static QColor green_brush; + static QColor silver_brush; + static QColor blue_back; + static QColor green_back; + static QColor silver_back; private: mutable std::optional height_hint_; diff --git a/qt/TorrentDelegateMin.cc b/qt/TorrentDelegateMin.cc index 232708910..d07cf8a5a 100644 --- a/qt/TorrentDelegateMin.cc +++ b/qt/TorrentDelegateMin.cc @@ -62,35 +62,35 @@ public: QRect status_rect; QRect bar_rect; - ItemLayout(QString const& name_text, QString const& status_text, QIcon const& emblem_icon, QFont const& base_font, + ItemLayout(QString name_text, QString status_text, QIcon const& emblem_icon, QFont const& base_font, Qt::LayoutDirection direction, QPoint const& top_left, int width); - QSize size() const + [[nodiscard]] QSize size() const { return (icon_rect | name_rect | status_rect | bar_rect).size(); } - QString nameText() const + [[nodiscard]] QString nameText() const { return elidedText(name_font, name_text_, name_rect.width()); } - QString statusText() const + [[nodiscard]] QString statusText() const { return status_text_; } private: - QString elidedText(QFont const& font, QString const& text, int width) const + [[nodiscard]] QString elidedText(QFont const& font, QString const& text, int width) const { return QFontMetrics(font).elidedText(text, Qt::ElideRight, width); } }; -ItemLayout::ItemLayout(QString const& name_text, QString const& status_text, QIcon const& emblem_icon, QFont const& base_font, +ItemLayout::ItemLayout(QString name_text, QString status_text, QIcon const& emblem_icon, QFont const& base_font, Qt::LayoutDirection direction, QPoint const& top_left, int width) : - name_text_(name_text), - status_text_(status_text), + name_text_(std::move(name_text)), + status_text_(std::move(status_text)), name_font(base_font), status_font(base_font) { @@ -131,9 +131,9 @@ ItemLayout::ItemLayout(QString const& name_text, QString const& status_text, QIc QSize TorrentDelegateMin::sizeHint(QStyleOptionViewItem const& option, Torrent const& tor) const { - bool const isMagnet(!tor.hasMetadata()); + bool const is_magnet(!tor.hasMetadata()); QSize const m(margin(*qApp->style())); - ItemLayout const layout(isMagnet ? progressString(tor) : tor.name(), shortStatusString(tor), QIcon(), option.font, + ItemLayout const layout(is_magnet ? progressString(tor) : tor.name(), shortStatusString(tor), QIcon(), option.font, option.direction, QPoint(0, 0), option.rect.width() - m.width() * 2); return layout.size() + m * 2; } @@ -255,21 +255,21 @@ void TorrentDelegateMin::drawTorrent(QPainter* painter, QStyleOptionViewItem con if (tor.isDownloading()) { - progress_bar_style_->palette.setBrush(QPalette::Highlight, blue_brush_); - progress_bar_style_->palette.setColor(QPalette::Base, blue_back_); - progress_bar_style_->palette.setColor(QPalette::Window, blue_back_); + progress_bar_style_->palette.setBrush(QPalette::Highlight, blue_brush); + progress_bar_style_->palette.setColor(QPalette::Base, blue_back); + progress_bar_style_->palette.setColor(QPalette::Window, blue_back); } else if (tor.isSeeding()) { - progress_bar_style_->palette.setBrush(QPalette::Highlight, green_brush_); - progress_bar_style_->palette.setColor(QPalette::Base, green_back_); - progress_bar_style_->palette.setColor(QPalette::Window, green_back_); + progress_bar_style_->palette.setBrush(QPalette::Highlight, green_brush); + progress_bar_style_->palette.setColor(QPalette::Base, green_back); + progress_bar_style_->palette.setColor(QPalette::Window, green_back); } else { - progress_bar_style_->palette.setBrush(QPalette::Highlight, silver_brush_); - progress_bar_style_->palette.setColor(QPalette::Base, silver_back_); - progress_bar_style_->palette.setColor(QPalette::Window, silver_back_); + progress_bar_style_->palette.setBrush(QPalette::Highlight, silver_brush); + progress_bar_style_->palette.setColor(QPalette::Base, silver_back); + progress_bar_style_->palette.setColor(QPalette::Window, silver_back); } progress_bar_style_->state = progress_bar_state; diff --git a/qt/TorrentFilter.cc b/qt/TorrentFilter.cc index 2ec51be6d..3cccf03ab 100644 --- a/qt/TorrentFilter.cc +++ b/qt/TorrentFilter.cc @@ -36,24 +36,24 @@ TorrentFilter::~TorrentFilter() = default; void TorrentFilter::onPrefChanged(int key) { // For refiltering nearly immediately. Used to debounce batched prefs changes. - static int const fast_msec = 50; + static int const FastMSec = 50; // For waiting a little longer. Useful when user is typing the filter text. - static int const slow_msec = 500; + static int const SlowMSec = 500; std::optional msec; switch (key) { case Prefs::FILTER_TEXT: // special case for isEmpty: user probably hit the 'clear' button - msec = prefs_.getString(key).isEmpty() ? fast_msec : slow_msec; + msec = prefs_.getString(key).isEmpty() ? FastMSec : SlowMSec; break; case Prefs::FILTER_MODE: case Prefs::FILTER_TRACKERS: case Prefs::SORT_MODE: case Prefs::SORT_REVERSED: - msec = fast_msec; + msec = FastMSec; break; } @@ -311,9 +311,9 @@ bool TorrentFilter::filterAcceptsRow(int source_row, QModelIndex const& source_p return accepts; } -void TorrentFilter::countTorrentsPerMode(int* setme_counts) const +std::array TorrentFilter::countTorrentsPerMode() const { - std::fill_n(setme_counts, static_cast(FilterMode::NUM_MODES), 0); + std::array torrent_counts = {}; for (auto const& tor : dynamic_cast(sourceModel())->torrents()) { @@ -321,8 +321,10 @@ void TorrentFilter::countTorrentsPerMode(int* setme_counts) const { if (activityFilterAcceptsTorrent(tor, mode)) { - ++setme_counts[mode]; + ++torrent_counts[mode]; } } } + + return torrent_counts; } diff --git a/qt/TorrentFilter.h b/qt/TorrentFilter.h index 42260639c..e55078cc1 100644 --- a/qt/TorrentFilter.h +++ b/qt/TorrentFilter.h @@ -8,9 +8,13 @@ #pragma once +#include + #include #include +#include "Filters.h" + class QString; class FilterMode; @@ -30,25 +34,23 @@ public: }; public: - TorrentFilter(Prefs const& prefs); + explicit TorrentFilter(Prefs const& prefs); virtual ~TorrentFilter(); - - void countTorrentsPerMode(int* setmeCounts) const; + [[nodiscard]] std::array countTorrentsPerMode() const; protected: // QSortFilterProxyModel bool filterAcceptsRow(int, QModelIndex const&) const override; bool lessThan(QModelIndex const&, QModelIndex const&) const override; -private: - bool activityFilterAcceptsTorrent(Torrent const* tor, FilterMode const& mode) const; - bool trackerFilterAcceptsTorrent(Torrent const* tor, QString const& tracker) const; - private slots: void onPrefChanged(int key); void refilter(); private: + bool activityFilterAcceptsTorrent(Torrent const* tor, FilterMode const& mode) const; + bool trackerFilterAcceptsTorrent(Torrent const* tor, QString const& tracker) const; + QTimer refilter_timer_; Prefs const& prefs_; }; diff --git a/qt/TorrentModel.cc b/qt/TorrentModel.cc index 21909ea4c..02e734bfd 100644 --- a/qt/TorrentModel.cc +++ b/qt/TorrentModel.cc @@ -164,9 +164,9 @@ void TorrentModel::updateTorrents(tr_variant* torrents, bool is_complete_list) auto const now = time(nullptr); auto const recently_added = [now](auto const& tor) { - static auto constexpr max_age = 60; + static auto constexpr MaxAge = 60; auto const date = tor->dateAdded(); - return (date != 0) && (difftime(now, date) < max_age); + return (date != 0) && (difftime(now, date) < MaxAge); }; // build a list of the property keys diff --git a/qt/TorrentView.cc b/qt/TorrentView.cc index 053a61d01..31ede22f0 100644 --- a/qt/TorrentView.cc +++ b/qt/TorrentView.cc @@ -15,7 +15,7 @@ class TorrentView::HeaderWidget : public QWidget { public: - HeaderWidget(TorrentView* parent) : + explicit HeaderWidget(TorrentView* parent) : QWidget(parent), text_() { @@ -29,14 +29,14 @@ public: } // QWidget - QSize sizeHint() const override + [[nodiscard]] QSize sizeHint() const override { QStyleOptionHeader option; option.rect = QRect(0, 0, 100, 100); - QRect const labelRect = style()->subElementRect(QStyle::SE_HeaderLabel, &option, this); + QRect const label_rect = style()->subElementRect(QStyle::SE_HeaderLabel, &option, this); - return QSize(100, fontMetrics().height() + (option.rect.height() - labelRect.height())); + return QSize(100, fontMetrics().height() + (option.rect.height() - label_rect.height())); } protected: diff --git a/qt/TrackerDelegate.cc b/qt/TrackerDelegate.cc index 42ad9bb6b..6447ff21d 100644 --- a/qt/TrackerDelegate.cc +++ b/qt/TrackerDelegate.cc @@ -29,8 +29,9 @@ namespace { -int const SPACING = 6; -QSize const myMargin(10, 10); +auto constexpr Spacing = int{ 6 }; + +auto constexpr Margin = QSize{ 10, 10 }; class ItemLayout { @@ -43,12 +44,12 @@ public: ItemLayout(QString const& text, bool suppress_colors, Qt::LayoutDirection direction, QPoint const& top_left, int width); - QSize size() const + [[nodiscard]] QSize size() const { return (icon_rect | text_rect).size(); } - QAbstractTextDocumentLayout* textLayout() const + [[nodiscard]] QAbstractTextDocumentLayout* textLayout() const { return text_document_.documentLayout(); } @@ -63,7 +64,7 @@ ItemLayout::ItemLayout(QString const& text, bool suppress_colors, Qt::LayoutDire QRect base_rect(top_left, QSize(width, 0)); icon_rect = style->alignedRect(direction, Qt::AlignLeft | Qt::AlignTop, icon_size, base_rect); - Utils::narrowRect(base_rect, icon_size.width() + SPACING, 0, direction); + Utils::narrowRect(base_rect, icon_size.width() + Spacing, 0, direction); text_document_.setDocumentMargin(0); text_document_.setTextWidth(base_rect.width()); @@ -91,8 +92,8 @@ ItemLayout::ItemLayout(QString const& text, bool suppress_colors, Qt::LayoutDire QSize TrackerDelegate::sizeHint(QStyleOptionViewItem const& option, TrackerInfo const& info) const { - ItemLayout const layout(getText(info), true, option.direction, QPoint(0, 0), option.rect.width() - myMargin.width() * 2); - return layout.size() + myMargin * 2; + ItemLayout const layout(getText(info), true, option.direction, QPoint(0, 0), option.rect.width() - Margin.width() * 2); + return layout.size() + Margin * 2; } QSize TrackerDelegate::sizeHint(QStyleOptionViewItem const& option, QModelIndex const& index) const @@ -118,9 +119,9 @@ void TrackerDelegate::drawTracker(QPainter* painter, QStyleOptionViewItem const& bool const is_item_enabled((option.state & QStyle::State_Enabled) != 0); bool const is_item_active((option.state & QStyle::State_Active) != 0); - QIcon trackerIcon(inf.st.getFavicon()); + QIcon tracker_icon(inf.st.getFavicon()); - QRect const content_rect(option.rect.adjusted(myMargin.width(), myMargin.height(), -myMargin.width(), -myMargin.height())); + QRect const content_rect(option.rect.adjusted(Margin.width(), Margin.height(), -Margin.width(), -Margin.height())); ItemLayout const layout(getText(inf), is_item_selected, option.direction, content_rect.topLeft(), content_rect.width()); painter->save(); @@ -137,7 +138,7 @@ void TrackerDelegate::drawTracker(QPainter* painter, QStyleOptionViewItem const& painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight)); } - trackerIcon.paint(painter, layout.icon_rect, Qt::AlignCenter, is_item_selected ? QIcon::Selected : QIcon::Normal, + tracker_icon.paint(painter, layout.icon_rect, Qt::AlignCenter, is_item_selected ? QIcon::Selected : QIcon::Normal, QIcon::On); QAbstractTextDocumentLayout::PaintContext paint_context; diff --git a/qt/TrackerModelFilter.cc b/qt/TrackerModelFilter.cc index a118fae7a..6b00f3788 100644 --- a/qt/TrackerModelFilter.cc +++ b/qt/TrackerModelFilter.cc @@ -23,6 +23,6 @@ void TrackerModelFilter::setShowBackupTrackers(bool b) bool TrackerModelFilter::filterAcceptsRow(int source_row, QModelIndex const& source_parent) const { QModelIndex index = sourceModel()->index(source_row, 0, source_parent); - auto const trackerInfo = index.data(TrackerModel::TrackerRole).value(); - return show_backups_ || !trackerInfo.st.is_backup; + auto const tracker_info = index.data(TrackerModel::TrackerRole).value(); + return show_backups_ || !tracker_info.st.is_backup; } diff --git a/qt/Utils.cc b/qt/Utils.cc index 6311641ac..66feb092f 100644 --- a/qt/Utils.cc +++ b/qt/Utils.cc @@ -110,7 +110,7 @@ QIcon fileIcon() return icon; } -std::unordered_map iconCache; +std::unordered_map icon_cache; QIcon getMimeIcon(QString const& filename) { @@ -132,11 +132,11 @@ QIcon getMimeIcon(QString const& filename) return folderIcon(); } - QIcon& icon = iconCache[ext]; + QIcon& icon = icon_cache[ext]; if (icon.isNull()) // cache miss { - QMimeDatabase mimeDb; - QMimeType type = mimeDb.mimeTypeForFile(filename, QMimeDatabase::MatchExtension); + QMimeDatabase mime_db; + QMimeType type = mime_db.mimeTypeForFile(filename, QMimeDatabase::MatchExtension); if (icon.isNull()) { icon = QIcon::fromTheme(type.iconName());