diff --git a/.clang-format b/.clang-format index 8e67ddc3f..9e7b23592 100644 --- a/.clang-format +++ b/.clang-format @@ -16,8 +16,8 @@ AllowAllParametersOfDeclarationOnNextLine: true AllowShortEnumsOnASingleLine: true AllowShortBlocksOnASingleLine: Never AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: All -AllowShortLambdasOnASingleLine: All +AllowShortFunctionsOnASingleLine: Empty +AllowShortLambdasOnASingleLine: Empty AllowShortIfStatementsOnASingleLine: Never AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None @@ -40,16 +40,16 @@ BraceWrapping: AfterUnion: false AfterExternBlock: false BeforeCatch: false - BeforeElse: false + BeforeElse: true BeforeLambdaBody: false - BeforeWhile: false + BeforeWhile: true IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true BreakBeforeBinaryOperators: None BreakBeforeConceptDeclarations: true -BreakBeforeBraces: Attach +BreakBeforeBraces: Custom BreakBeforeInheritanceComma: false BreakInheritanceList: BeforeColon BreakBeforeTernaryOperators: true @@ -59,7 +59,7 @@ BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true ColumnLimit: 120 CommentPragmas: '^ IWYU pragma:' -QualifierAlignment: Leave +QualifierAlignment: Left CompactNamespaces: false ConstructorInitializerIndentWidth: 2 ContinuationIndentWidth: 2 @@ -97,7 +97,7 @@ IncludeCategories: CaseSensitive: false IncludeIsMainRegex: '(Test)?$' IncludeIsMainSourceRegex: '' -IndentAccessModifiers: false +IndentAccessModifiers: true IndentCaseLabels: false IndentCaseBlocks: false IndentGotoLabels: true @@ -114,7 +114,7 @@ LambdaBodyIndentation: Signature MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 -NamespaceIndentation: None +NamespaceIndentation: All ObjCBinPackProtocolList: Auto ObjCBlockIndentWidth: 2 ObjCBreakBeforeNestedBlockParam: true @@ -130,7 +130,7 @@ PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 PenaltyIndentedWhitespace: 0 -PointerAlignment: Right +PointerAlignment: Left PPIndentWidth: -1 ReferenceAlignment: Pointer ReflowComments: true diff --git a/src/librssguard/core/feedsmodel.cpp b/src/librssguard/core/feedsmodel.cpp index 518c70fa0..afe96b987 100644 --- a/src/librssguard/core/feedsmodel.cpp +++ b/src/librssguard/core/feedsmodel.cpp @@ -24,13 +24,11 @@ using RootItemPtr = RootItem*; -FeedsModel::FeedsModel(QObject* parent) : QAbstractItemModel(parent), m_rootItem(new RootItem()) -{ +FeedsModel::FeedsModel(QObject* parent) : QAbstractItemModel(parent), m_rootItem(new RootItem()) { setObjectName(QSL("FeedsModel")); // Create root item. - // : Name of root item of feed list which can be seen in feed add/edit dialog. m_rootItem->setTitle(tr("Root")); m_rootItem->setIcon(qApp->icons()->fromTheme(QSL("folder"))); @@ -40,9 +38,8 @@ FeedsModel::FeedsModel(QObject* parent) : QAbstractItemModel(parent), m_rootItem // : Title text in the feed list header. m_headerData << tr("Title"); - m_tooltipData - << /*: Feed list header "titles" column tooltip.*/ tr("Titles of feeds/categories.") - << /*: Feed list header "counts" column tooltip.*/ tr("Counts of unread/all mesages."); + m_tooltipData << /*: Feed list header "titles" column tooltip.*/ tr("Titles of feeds/categories.") + << /*: Feed list header "counts" column tooltip.*/ tr("Counts of unread/all mesages."); setupFonts(); } @@ -78,8 +75,8 @@ QStringList FeedsModel::mimeTypes() const { return QStringList() << QSL(MIME_TYPE_ITEM_POINTER); } -bool FeedsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, - int column, const QModelIndex& parent) { +bool FeedsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) { Q_UNUSED(row) Q_UNUSED(column) @@ -99,7 +96,8 @@ bool FeedsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int QDataStream stream(&dragged_items_data, QIODevice::OpenModeFlag::ReadOnly); while (!stream.atEnd()) { - quintptr pointer_to_item; stream >> pointer_to_item; + quintptr pointer_to_item; + stream >> pointer_to_item; // We have item we want to drag, we also determine the target item. auto* dragged_item = RootItemPtr(pointer_to_item); @@ -108,16 +106,17 @@ bool FeedsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int ServiceRoot* target_item_root = target_item->getParentServiceRoot(); if (dragged_item == target_item || dragged_item->parent() == target_item) { - qDebug("Dragged item is equal to target item or its parent is equal to target item. Cancelling drag-drop action."); + qDebug( + "Dragged item is equal to target item or its parent is equal to target item. Cancelling drag-drop action."); return false; } if (dragged_item_root != target_item_root) { // Transferring of items between different accounts is not possible. - qApp->showGuiMessage(Notification::Event::GeneralEvent, { - tr("Cannot perform drag & drop operation"), - tr("You can't transfer dragged item into different account, this is not supported."), - QSystemTrayIcon::MessageIcon::Critical }); + qApp->showGuiMessage(Notification::Event::GeneralEvent, + {tr("Cannot perform drag & drop operation"), + tr("You can't transfer dragged item into different account, this is not supported."), + QSystemTrayIcon::MessageIcon::Critical}); qDebugNN << LOGSEC_FEEDMODEL << "Dragged item cannot be dragged into different account. Cancelling drag-drop action."; return false; @@ -155,27 +154,27 @@ QVariant FeedsModel::headerData(int section, Qt::Orientation orientation, int ro } switch (role) { - case Qt::DisplayRole: - if (section == FDS_MODEL_TITLE_INDEX) { - return m_headerData.at(FDS_MODEL_TITLE_INDEX); - } - else { - return QVariant(); - } - - case Qt::ToolTipRole: - return m_tooltipData.at(section); - - case Qt::DecorationRole: - if (section == FDS_MODEL_COUNTS_INDEX) { - return m_countsIcon; - } - else { - return QVariant(); - } - - default: + case Qt::DisplayRole: + if (section == FDS_MODEL_TITLE_INDEX) { + return m_headerData.at(FDS_MODEL_TITLE_INDEX); + } + else { return QVariant(); + } + + case Qt::ToolTipRole: + return m_tooltipData.at(section); + + case Qt::DecorationRole: + if (section == FDS_MODEL_COUNTS_INDEX) { + return m_countsIcon; + } + else { + return QVariant(); + } + + default: + return QVariant(); } } @@ -291,7 +290,7 @@ void FeedsModel::reassignNodeToNewParent(RootItem* original_node, RootItem* new_ } } -QListFeedsModel::serviceRoots() const { +QList FeedsModel::serviceRoots() const { QList roots; auto ch = m_rootItem->childItems(); @@ -304,42 +303,42 @@ QListFeedsModel::serviceRoots() const { return roots; } -QListFeedsModel::feedsForScheduledUpdate(bool auto_update_now) { - QListfeeds_for_update; +QList FeedsModel::feedsForScheduledUpdate(bool auto_update_now) { + QList feeds_for_update; auto stf = m_rootItem->getSubTreeFeeds(); for (Feed* feed : qAsConst(stf)) { switch (feed->autoUpdateType()) { - case Feed::AutoUpdateType::DontAutoUpdate: + case Feed::AutoUpdateType::DontAutoUpdate: - // Do not auto-update this feed ever. - continue; + // Do not auto-update this feed ever. + continue; - case Feed::AutoUpdateType::DefaultAutoUpdate: + case Feed::AutoUpdateType::DefaultAutoUpdate: - if (auto_update_now) { - feeds_for_update.append(feed); - } + if (auto_update_now) { + feeds_for_update.append(feed); + } - break; + break; - case Feed::AutoUpdateType::SpecificAutoUpdate: - default: - int remaining_interval = feed->autoUpdateRemainingInterval(); + case Feed::AutoUpdateType::SpecificAutoUpdate: + default: + int remaining_interval = feed->autoUpdateRemainingInterval(); - if (--remaining_interval <= 0) { - // Interval of this feed passed, include this feed in the output list - // and reset the interval. - feeds_for_update.append(feed); - feed->setAutoUpdateRemainingInterval(feed->autoUpdateInitialInterval()); - } - else { - // Interval did not pass, set new decremented interval and do NOT - // include this feed in the output list. - feed->setAutoUpdateRemainingInterval(remaining_interval); - } + if (--remaining_interval <= 0) { + // Interval of this feed passed, include this feed in the output list + // and reset the interval. + feeds_for_update.append(feed); + feed->setAutoUpdateRemainingInterval(feed->autoUpdateInitialInterval()); + } + else { + // Interval did not pass, set new decremented interval and do NOT + // include this feed in the output list. + feed->setAutoUpdateRemainingInterval(remaining_interval); + } - break; + break; } } @@ -385,9 +384,8 @@ QModelIndex FeedsModel::indexForItem(const RootItem* item) const { while (!chain.isEmpty()) { const RootItem* parent_item = chain.pop(); - target_index = index(parent_item->parent()->childItems().indexOf(const_cast(parent_item)), - 0, - target_index); + target_index = + index(parent_item->parent()->childItems().indexOf(const_cast(parent_item)), 0, target_index); } return target_index; @@ -428,16 +426,12 @@ void FeedsModel::notifyWithCounts() { void FeedsModel::onItemDataChanged(const QList& items) { if (items.size() > RELOAD_MODEL_BORDER_NUM) { - qDebugNN << LOGSEC_FEEDMODEL - << "There is request to reload feed model for more than " - << RELOAD_MODEL_BORDER_NUM + qDebugNN << LOGSEC_FEEDMODEL << "There is request to reload feed model for more than " << RELOAD_MODEL_BORDER_NUM << " items, reloading model fully."; reloadWholeLayout(); } else { - qDebugNN << LOGSEC_FEEDMODEL - << "There is request to reload feed model, reloading the " - << items.size() + qDebugNN << LOGSEC_FEEDMODEL << "There is request to reload feed model, reloading the " << items.size() << " items individually."; for (RootItem* item : items) { @@ -451,7 +445,8 @@ void FeedsModel::onItemDataChanged(const QList& items) { void FeedsModel::setupFonts() { QFont fon; - fon.fromString(qApp->settings()->value(GROUP(Feeds), Feeds::ListFont, Application::font("FeedsView").toString()).toString()); + fon.fromString( + qApp->settings()->value(GROUP(Feeds), Feeds::ListFont, Application::font("FeedsView").toString()).toString()); m_normalFont = fon; @@ -478,7 +473,8 @@ bool FeedsModel::addServiceAccount(ServiceRoot* root, bool freshly_activated) { endInsertRows(); // Connect. - connect(root, &ServiceRoot::itemRemovalRequested, this, static_cast(&FeedsModel::removeItem)); + connect(root, &ServiceRoot::itemRemovalRequested, this, + static_cast(&FeedsModel::removeItem)); connect(root, &ServiceRoot::itemReassignmentRequested, this, &FeedsModel::reassignNodeToNewParent); connect(root, &ServiceRoot::dataChanged, this, &FeedsModel::onItemDataChanged); connect(root, &ServiceRoot::reloadMessageListRequested, this, &FeedsModel::reloadMessageListRequested); @@ -554,7 +550,7 @@ void FeedsModel::stopServiceAccounts() { } } -QListFeedsModel::feedsForIndex(const QModelIndex& index) const { +QList FeedsModel::feedsForIndex(const QModelIndex& index) const { return itemForIndex(index)->getSubTreeFeeds(); } @@ -576,27 +572,26 @@ bool FeedsModel::markItemCleared(RootItem* item, bool clean_read_only) { QVariant FeedsModel::data(const QModelIndex& index, int role) const { switch (role) { - case Qt::ItemDataRole::FontRole: { - RootItem* it = itemForIndex(index); - bool is_bold = it->countOfUnreadMessages() > 0; - bool is_striked = it->kind() == RootItem::Kind::Feed - ? qobject_cast(it)->isSwitchedOff() - : false; + case Qt::ItemDataRole::FontRole: { + RootItem* it = itemForIndex(index); + bool is_bold = it->countOfUnreadMessages() > 0; + bool is_striked = it->kind() == RootItem::Kind::Feed ? qobject_cast(it)->isSwitchedOff() : false; - if (is_bold) { - return is_striked ? m_boldStrikedFont : m_boldFont; - } - else { - return is_striked ? m_normalStrikedFont : m_normalFont; - } + if (is_bold) { + return is_striked ? m_boldStrikedFont : m_boldFont; + } + else { + return is_striked ? m_normalStrikedFont : m_normalFont; + } + } + + case Qt::ItemDataRole::ToolTipRole: + if (!qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::EnableTooltipsFeedsMessages)).toBool()) { + return QVariant(); } - case Qt::ItemDataRole::ToolTipRole: - if (!qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::EnableTooltipsFeedsMessages)).toBool()) { - return QVariant(); - } - - default: - return itemForIndex(index)->data(index.column(), role);; + default: + return itemForIndex(index)->data(index.column(), role); + ; } } diff --git a/src/librssguard/miscellaneous/application.cpp b/src/librssguard/miscellaneous/application.cpp index fd8049515..fc758a97c 100644 --- a/src/librssguard/miscellaneous/application.cpp +++ b/src/librssguard/miscellaneous/application.cpp @@ -63,7 +63,7 @@ #endif Application::Application(const QString &id, int &argc, char **argv, const QStringList &raw_cli_args) - : SingleApplication(id, argc, argv), m_updateFeedsLock(new Mutex()) { + : SingleApplication(id, argc, argv), m_updateFeedsLock(new Mutex()) { parseCmdArgumentsFromMyInstance(raw_cli_args); qInstallMessageHandler(performLogging); @@ -133,8 +133,8 @@ Application::Application(const QString &id, int &argc, char **argv, const QStrin if (!app_dir.isEmpty()) { bool success = qputenv("GST_PLUGIN_SYSTEM_PATH_1_0", QSL("%1/usr/lib/gstreamer-1.0:%2") - .arg(app_dir, QString::fromLocal8Bit(qgetenv("GST_PLUGIN_SYSTEM_PATH_1_0"))) - .toLocal8Bit()); + .arg(app_dir, QString::fromLocal8Bit(qgetenv("GST_PLUGIN_SYSTEM_PATH_1_0"))) + .toLocal8Bit()); success = qputenv("GST_PLUGIN_SCANNER_1_0", QSL("%1/usr/lib/gstreamer1.0/gstreamer-1.0/gst-plugin-scanner").arg(app_dir).toLocal8Bit()) && success; @@ -165,7 +165,7 @@ Application::Application(const QString &id, int &argc, char **argv, const QStrin QTimer::singleShot(3000, this, [=]() { try { m_webFactory->adBlock()->setEnabled( - qApp->settings()->value(GROUP(AdBlock), SETTING(AdBlock::AdBlockEnabled)).toBool()); + qApp->settings()->value(GROUP(AdBlock), SETTING(AdBlock::AdBlockEnabled)).toBool()); } catch (...) { onAdBlockFailure(); } @@ -269,7 +269,7 @@ void Application::offerChanges() const { {tr("Welcome"), tr("Welcome to %1.\n\nPlease, check NEW stuff included in this\n" "version by clicking this popup notification.") - .arg(QSL(APP_LONG_NAME)), + .arg(QSL(APP_LONG_NAME)), QSystemTrayIcon::MessageIcon::NoIcon}, {}, {tr("Go to changelog"), [] { FormAbout(qApp->mainForm()).exec(); }}); } @@ -277,9 +277,9 @@ void Application::offerChanges() const { bool Application::isAlreadyRunning() { return m_allowMultipleInstances - ? false - : sendMessage((QStringList() << QSL("-%1").arg(QSL(CLI_IS_RUNNING)) << Application::arguments().mid(1)) - .join(QSL(ARGUMENTS_LIST_SEPARATOR))); + ? false + : sendMessage((QStringList() << QSL("-%1").arg(QSL(CLI_IS_RUNNING)) << Application::arguments().mid(1)) + .join(QSL(ARGUMENTS_LIST_SEPARATOR))); } QStringList Application::builtinSounds() const { @@ -449,14 +449,14 @@ void Application::restoreDatabaseSettings(bool restore_database, bool restore_se if (restore_database) { if (!qApp->database()->driver()->initiateRestoration(source_database_file_path)) { throw ApplicationException( - tr("Database restoration was not initiated. Make sure that output directory is writable.")); + tr("Database restoration was not initiated. Make sure that output directory is writable.")); } } if (restore_settings) { if (!qApp->settings()->initiateRestoration(source_settings_file_path)) { throw ApplicationException( - tr("Settings restoration was not initiated. Make sure that output directory is writable.")); + tr("Settings restoration was not initiated. Make sure that output directory is writable.")); } } } @@ -664,8 +664,8 @@ void Application::showMessagesNumber(int unread_messages, bool any_feed_has_new_ #endif HRESULT overlay_result = m_windowsTaskBar->SetOverlayIcon( - reinterpret_cast(m_mainForm->winId()), - (task_bar_count_enabled && unread_messages > 0) ? overlay_hicon : nullptr, nullptr); + reinterpret_cast(m_mainForm->winId()), + (task_bar_count_enabled && unread_messages > 0) ? overlay_hicon : nullptr, nullptr); DestroyIcon(overlay_hicon); @@ -677,8 +677,8 @@ void Application::showMessagesNumber(int unread_messages, bool any_feed_has_new_ if (m_mainForm != nullptr) { m_mainForm->setWindowTitle(unread_messages > 0 - ? QSL("[%2] %1").arg(QSL(APP_LONG_NAME), QString::number(unread_messages)) - : QSL(APP_LONG_NAME)); + ? QSL("[%2] %1").arg(QSL(APP_LONG_NAME), QString::number(unread_messages)) + : QSL(APP_LONG_NAME)); } } @@ -817,7 +817,7 @@ void Application::onAdBlockFailure() { void Application::determineFirstRuns() { m_firstRunEver = settings()->value(GROUP(General), SETTING(General::FirstRun)).toBool(); m_firstRunCurrentVersion = - settings()->value(GROUP(General), QString(General::FirstRun) + QL1C('_') + APP_VERSION, true).toBool(); + settings()->value(GROUP(General), QString(General::FirstRun) + QL1C('_') + APP_VERSION, true).toBool(); eliminateFirstRuns(); } @@ -843,8 +843,8 @@ void Application::parseCmdArgumentsFromOtherInstance(const QString &message) { cmd_parser.addOption(QCommandLineOption({QSL(CLI_QUIT_INSTANCE)})); cmd_parser.addOption(QCommandLineOption({QSL(CLI_IS_RUNNING)})); cmd_parser.addPositionalArgument( - QSL("urls"), QSL("List of URL addresses pointing to individual online feeds which should be added."), - QSL("[url-1 ... url-n]")); + QSL("urls"), QSL("List of URL addresses pointing to individual online feeds which should be added."), + QSL("[url-1 ... url-n]")); if (!cmd_parser.parse(messages)) { qCriticalNN << LOGSEC_CORE << cmd_parser.errorText(); @@ -882,12 +882,11 @@ void Application::parseCmdArgumentsFromMyInstance(const QStringList &raw_cli_arg QCommandLineOption help({QSL(CLI_HELP_SHORT), QSL(CLI_HELP_LONG)}, QSL("Displays overview of CLI.")); QCommandLineOption version({QSL(CLI_VER_SHORT), QSL(CLI_VER_LONG)}, QSL("Displays version of the application.")); QCommandLineOption log_file( - {QSL(CLI_LOG_SHORT), QSL(CLI_LOG_LONG)}, - QSL("Write application debug log to file. Note that logging to file may slow application down."), - QSL("log-file")); + {QSL(CLI_LOG_SHORT), QSL(CLI_LOG_LONG)}, + QSL("Write application debug log to file. Note that logging to file may slow application down."), QSL("log-file")); QCommandLineOption custom_data_folder( - {QSL(CLI_DAT_SHORT), QSL(CLI_DAT_LONG)}, - QSL("Use custom folder for user data and disable single instance application mode."), QSL("user-data-folder")); + {QSL(CLI_DAT_SHORT), QSL(CLI_DAT_LONG)}, + QSL("Use custom folder for user data and disable single instance application mode."), QSL("user-data-folder")); QCommandLineOption disable_singleinstance({QSL(CLI_SIN_SHORT), QSL(CLI_SIN_LONG)}, QSL("Allow running of multiple application instances.")); @@ -906,13 +905,13 @@ void Application::parseCmdArgumentsFromMyInstance(const QStringList &raw_cli_arg m_cmdParser.addOptions({ help, version, log_file, custom_data_folder, disable_singleinstance, disable_only_debug, disable_debug, #if defined(USE_WEBENGINE) - force_nowebengine, + force_nowebengine, #endif - forced_style + forced_style }); m_cmdParser.addPositionalArgument( - QSL("urls"), QSL("List of URL addresses pointing to individual online feeds which should be added."), - QSL("[url-1 ... url-n]")); + QSL("urls"), QSL("List of URL addresses pointing to individual online feeds which should be added."), + QSL("[url-1 ... url-n]")); m_cmdParser.setApplicationDescription(QSL(APP_NAME)); m_cmdParser.setSingleDashWordOptionMode(QCommandLineParser::SingleDashWordOptionMode::ParseAsLongOptions); @@ -972,10 +971,10 @@ void Application::parseCmdArgumentsFromMyInstance(const QStringList &raw_cli_arg void Application::onNodeJsPackageUpdateError(const QList &pkgs, const QString &error) { qApp->showGuiMessage( - Notification::Event::NodePackageFailedToUpdate, - {{}, - tr("Packages %1 were NOT updated because of error: %2.").arg(NodeJs::packagesToString(pkgs), error), - QSystemTrayIcon::MessageIcon::Critical}); + Notification::Event::NodePackageFailedToUpdate, + {{}, + tr("Packages %1 were NOT updated because of error: %2.").arg(NodeJs::packagesToString(pkgs), error), + QSystemTrayIcon::MessageIcon::Critical}); } void Application::onNodeJsPackageInstalled(const QList &pkgs, bool already_up_to_date) { diff --git a/src/librssguard/miscellaneous/application.h b/src/librssguard/miscellaneous/application.h index ac85f8814..3f079f9e8 100644 --- a/src/librssguard/miscellaneous/application.h +++ b/src/librssguard/miscellaneous/application.h @@ -18,11 +18,11 @@ #include "miscellaneous/systemfactory.h" #include "network-web/downloadmanager.h" +#include + #include #include -#include - #if defined(qApp) #undef qApp #endif @@ -79,7 +79,7 @@ struct GuiAction { }; class RSSGUARD_DLLSPEC Application : public SingleApplication { - Q_OBJECT + Q_OBJECT public: explicit Application(const QString& id, int& argc, char** argv, const QStringList& raw_cli_args); @@ -144,8 +144,8 @@ class RSSGUARD_DLLSPEC Application : public SingleApplication { void setMainForm(FormMain* main_form); - void backupDatabaseSettings(bool backup_database, bool backup_settings, - const QString& target_path, const QString& backup_name); + void backupDatabaseSettings(bool backup_database, bool backup_settings, const QString& target_path, + const QString& backup_name); void restoreDatabaseSettings(bool restore_database, bool restore_settings, const QString& source_database_file_path = QString(), const QString& source_settings_file_path = QString()); @@ -155,11 +155,8 @@ class RSSGUARD_DLLSPEC Application : public SingleApplication { // Displays given simple message in tray icon bubble or OSD // or in message box if tray icon is disabled. - void showGuiMessage(Notification::Event event, - const GuiMessage& msg, - const GuiMessageDestination& dest = {}, - const GuiAction& action = {}, - QWidget* parent = nullptr); + void showGuiMessage(Notification::Event event, const GuiMessage& msg, const GuiMessageDestination& dest = {}, + const GuiAction& action = {}, QWidget* parent = nullptr); WebViewer* createWebView(); @@ -174,7 +171,6 @@ class RSSGUARD_DLLSPEC Application : public SingleApplication { static void performLogging(QtMsgType type, const QMessageLogContext& context, const QString& msg); public slots: - // Restarts the application. void restart(); @@ -199,15 +195,15 @@ class RSSGUARD_DLLSPEC Application : public SingleApplication { #endif #endif -#if defined(Q_OS_WIN) - QImage generateOverlayIcon(int number) const; -#endif - void onFeedUpdatesStarted(); void onFeedUpdatesProgress(const Feed* feed, int current, int total); void onFeedUpdatesFinished(const FeedDownloadResults& results); private: +#if defined(Q_OS_WIN) + QImage generateOverlayIcon(int number) const; +#endif + void setupCustomDataFolder(const QString& data_folder); void determineFirstRuns(); void eliminateFirstRuns(); @@ -260,8 +256,6 @@ class RSSGUARD_DLLSPEC Application : public SingleApplication { #endif }; -inline Application* Application::instance() { - return static_cast(QCoreApplication::instance()); -} +inline Application* Application::instance() { return static_cast(QCoreApplication::instance()); } #endif // APPLICATION_H diff --git a/src/librssguard/network-web/downloadmanager.cpp b/src/librssguard/network-web/downloadmanager.cpp index 9e1421976..297595549 100644 --- a/src/librssguard/network-web/downloadmanager.cpp +++ b/src/librssguard/network-web/downloadmanager.cpp @@ -23,13 +23,11 @@ #include #include -DownloadItem::DownloadItem(QNetworkReply* reply, - const QString& preferred_file_name, - const std::function& run_on_finish, - QWidget* parent) : QWidget(parent), - m_ui(new Ui::DownloadItem), m_reply(reply), m_preferredFileName(preferred_file_name), - m_runOnFinish(run_on_finish), m_bytesReceived(0), m_requestFileName(false), m_startedSaving(false), - m_finishedDownloading(false), m_gettingFileName(false), m_canceledFileSelect(false) { +DownloadItem::DownloadItem(QNetworkReply* reply, const QString& preferred_file_name, + const std::function& run_on_finish, QWidget* parent) + : QWidget(parent), m_ui(new Ui::DownloadItem), m_reply(reply), m_preferredFileName(preferred_file_name), + m_runOnFinish(run_on_finish), m_bytesReceived(0), m_requestFileName(false), m_startedSaving(false), + m_finishedDownloading(false), m_gettingFileName(false), m_canceledFileSelect(false) { m_ui->setupUi(this); m_ui->m_btnTryAgain->hide(); m_requestFileName = qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::AlwaysPromptForFilename)).toBool(); @@ -68,7 +66,8 @@ void DownloadItem::init() { #if QT_VERSION >= 0x050F00 // Qt >= 5.15.0 connect(m_reply, &QNetworkReply::errorOccurred, this, &DownloadItem::error); #else - connect(m_reply, static_cast(&QNetworkReply::error), this, &DownloadItem::error); + connect(m_reply, static_cast(&QNetworkReply::error), this, + &DownloadItem::error); #endif connect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadItem::downloadProgress); @@ -96,14 +95,15 @@ void DownloadItem::getFileName() { const QString download_directory = qApp->downloadManager()->downloadDirectory(); QString chosen_filename = saveFileName(download_directory); - const QString filename_for_prompt = qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetExplicitDirectory)).toString() + - QDir::separator() + - QFileInfo(chosen_filename).fileName(); + const QString filename_for_prompt = + qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetExplicitDirectory)).toString() + + QDir::separator() + QFileInfo(chosen_filename).fileName(); if (m_requestFileName) { // User must provide the path where he wants to save downloaded file in. m_gettingFileName = true; - chosen_filename = QFileDialog::getSaveFileName(this, tr("Select destination for downloaded file"), filename_for_prompt); + chosen_filename = + QFileDialog::getSaveFileName(this, tr("Select destination for downloaded file"), filename_for_prompt); m_gettingFileName = false; if (chosen_filename.isEmpty()) { @@ -166,7 +166,9 @@ QString DownloadItem::saveFileName(const QString& directory) const { QString base_name = info.completeBaseName(); QString end_name = info.suffix(); - if (base_name.isEmpty() || base_name.contains(QRegularExpression(QSL("\\/|<|\\?")))) { + static QRegularExpression reg(QSL("\\/|<|\\?")); + + if (base_name.isEmpty() || base_name.contains(reg)) { base_name = QSL("unnamed_download"); } @@ -188,8 +190,7 @@ QString DownloadItem::saveFileName(const QString& directory) const { return name; } -const QFile& DownloadItem::output() const -{ +const QFile& DownloadItem::output() const { return m_output; } @@ -201,27 +202,23 @@ void DownloadItem::stop() { m_ui->m_btnTryAgain->show(); setUpdatesEnabled(true); m_reply->abort(); + emit downloadFinished(); } void DownloadItem::openFile() { if (!QDesktopServices::openUrl(QUrl::fromLocalFile(m_output.fileName()))) { - qApp->showGuiMessage(Notification::Event::GeneralEvent, { - tr("Cannot open file"), - tr("Cannot open output file. Open it manually."), - QSystemTrayIcon::MessageIcon::Warning }); + qApp->showGuiMessage(Notification::Event::GeneralEvent, + {tr("Cannot open file"), tr("Cannot open output file. Open it manually."), + QSystemTrayIcon::MessageIcon::Warning}); } } void DownloadItem::openFolder() { if (m_output.exists()) { if (!SystemFactory::openFolderFile(m_output.fileName())) { - MsgBox::show(this, - QMessageBox::Icon::Warning, - tr("Cannot open directory"), - tr("Cannot open output directory. Open it manually."), - QString(), - m_output.fileName()); + MsgBox::show(this, QMessageBox::Icon::Warning, tr("Cannot open directory"), + tr("Cannot open output directory. Open it manually."), QString(), m_output.fileName()); } } } @@ -346,7 +343,7 @@ double DownloadItem::remainingTime() const { double time_remaining = ((double)(bytesTotal() - bytesReceived())) / currentSpeed(); // When downloading the ETA should never be 0. - if ((int) time_remaining == 0) { + if ((int)time_remaining == 0) { time_remaining = 1.0; } @@ -380,18 +377,18 @@ void DownloadItem::updateDownloadInfoLabel() { remaining = DownloadManager::timeString(time_remaining); } - info = QString(tr("%1 of %2 (%3 per second) - %4")).arg(DownloadManager::dataString(m_bytesReceived), - bytes_total == 0 ? QSL("?") : DownloadManager::dataString(bytes_total), - DownloadManager::dataString((int)speed), - remaining); + info = QString(tr("%1 of %2 (%3 per second) - %4")) + .arg(DownloadManager::dataString(m_bytesReceived), + bytes_total == 0 ? QSL("?") : DownloadManager::dataString(bytes_total), + DownloadManager::dataString((int)speed), remaining); } else { if (m_bytesReceived == bytes_total) { info = DownloadManager::dataString(m_output.size()); } else { - info = tr("%1 of %2 - download completed").arg(DownloadManager::dataString(m_bytesReceived), - DownloadManager::dataString(m_bytesReceived)); + info = tr("%1 of %2 - download completed") + .arg(DownloadManager::dataString(m_bytesReceived), DownloadManager::dataString(m_bytesReceived)); } } @@ -401,7 +398,7 @@ void DownloadItem::updateDownloadInfoLabel() { bool DownloadItem::downloading() const { return !m_finishedDownloading; - //return (m_ui->m_progressDownload->isVisible()); + // return (m_ui->m_progressDownload->isVisible()); } bool DownloadItem::downloadedSuccessfully() const { @@ -430,16 +427,14 @@ void DownloadItem::finished() { } if (downloadedSuccessfully()) { - qApp->showGuiMessage(Notification::Event::GeneralEvent, { - tr("Download finished"), - tr("File '%1' is downloaded.\nClick here to open parent directory.").arg(QDir::toNativeSeparators( - m_output.fileName())), - QSystemTrayIcon::MessageIcon::Information }, - {}, { - tr("Open folder"), - [this] { - openFolder(); - } }); + qApp->showGuiMessage(Notification::Event::GeneralEvent, + {tr("Download finished"), + tr("File '%1' is downloaded.\nClick here to open parent directory.") + .arg(QDir::toNativeSeparators(m_output.fileName())), + QSystemTrayIcon::MessageIcon::Information}, + {}, {tr("Open folder"), [this] { + openFolder(); + }}); } } @@ -448,9 +443,10 @@ void DownloadItem::updateInfoAndUrlLabel() { m_ui->m_lblLocalFilename->setText(tr("Local file: %1").arg(QDir::toNativeSeparators(m_output.fileName()))); } -DownloadManager::DownloadManager(QWidget* parent) : TabContent(parent), m_ui(new Ui::DownloadManager), - m_autoSaver(new AutoSaver(this)), m_model(new DownloadModel(this)), - m_networkManager(new SilentNetworkAccessManager(this)), m_iconProvider(nullptr), m_removePolicy(RemovePolicy::Never) { +DownloadManager::DownloadManager(QWidget* parent) + : TabContent(parent), m_ui(new Ui::DownloadManager), m_autoSaver(new AutoSaver(this)), + m_model(new DownloadModel(this)), m_networkManager(new SilentNetworkAccessManager(this)), m_iconProvider(nullptr), + m_removePolicy(RemovePolicy::Never) { m_ui->setupUi(this); m_ui->m_viewDownloads->setShowGrid(false); m_ui->m_viewDownloads->verticalHeader()->hide(); @@ -503,9 +499,8 @@ int DownloadManager::downloadProgress() const { } } -void DownloadManager::download(const QNetworkRequest& request, - const QString& preferred_file_name, - const std::function& run_on_finish) { +void DownloadManager::download(const QNetworkRequest& request, const QString& preferred_file_name, + const std::function& run_on_finish) { if (!request.url().isEmpty()) { handleUnsupportedContent(m_networkManager->get(request), preferred_file_name, run_on_finish); } @@ -515,9 +510,8 @@ void DownloadManager::download(const QUrl& url) { download(QNetworkRequest(url)); } -void DownloadManager::handleUnsupportedContent(QNetworkReply* reply, - const QString& preferred_file_name, - const std::function& run_on_finish) { +void DownloadManager::handleUnsupportedContent(QNetworkReply* reply, const QString& preferred_file_name, + const std::function& run_on_finish) { if (reply == nullptr || reply->url().isEmpty()) { return; } @@ -534,14 +528,15 @@ void DownloadManager::handleUnsupportedContent(QNetworkReply* reply, addItem(item); - if (!item->m_canceledFileSelect && qApp->settings()->value(GROUP(Downloads), - SETTING(Downloads::ShowDownloadsWhenNewDownloadStarts)).toBool()) { + if (!item->m_canceledFileSelect && + qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::ShowDownloadsWhenNewDownloadStarts)).toBool()) { qApp->mainForm()->tabWidget()->showDownloadManager(); } } void DownloadManager::addItem(DownloadItem* item) { - connect(item, &DownloadItem::statusChanged, this, static_cast(&DownloadManager::updateRow)); + connect(item, &DownloadItem::statusChanged, this, + static_cast(&DownloadManager::updateRow)); connect(item, &DownloadItem::progress, this, &DownloadManager::itemProgress); connect(item, &DownloadItem::downloadFinished, this, &DownloadManager::itemFinished); @@ -646,12 +641,13 @@ void DownloadManager::save() const { Settings* settings = qApp->settings(); QString key; - settings->setValue(GROUP(Downloads), Downloads::RemovePolicy, (int) removePolicy()); + settings->setValue(GROUP(Downloads), Downloads::RemovePolicy, (int)removePolicy()); // Save all download items. for (int i = 0; i < m_downloads.count(); i++) { settings->setValue(GROUP(Downloads), QString(Downloads::ItemUrl).arg(i), m_downloads[i]->m_url); - settings->setValue(GROUP(Downloads), QString(Downloads::ItemLocation).arg(i), QFileInfo(m_downloads[i]->m_output).filePath()); + settings->setValue(GROUP(Downloads), QString(Downloads::ItemLocation).arg(i), + QFileInfo(m_downloads[i]->m_output).filePath()); settings->setValue(GROUP(Downloads), QString(Downloads::ItemDone).arg(i), m_downloads[i]->downloadedSuccessfully()); } @@ -671,7 +667,8 @@ void DownloadManager::load() { int i = 0; // Restore the policy. - m_removePolicy = static_cast(settings->value(GROUP(Downloads), SETTING(Downloads::RemovePolicy)).toInt()); + m_removePolicy = + static_cast(settings->value(GROUP(Downloads), SETTING(Downloads::RemovePolicy)).toInt()); // Restore downloads. while (settings->contains(GROUP(Downloads), QString(Downloads::ItemUrl).arg(i))) { @@ -725,11 +722,11 @@ QString DownloadManager::timeString(double time_remaining) { if (time_remaining > 60) { time_remaining = time_remaining / 60; time_remaining = floor(time_remaining); - remaining = tr("%n minutes remaining", "", (int) time_remaining); + remaining = tr("%n minutes remaining", "", (int)time_remaining); } else { time_remaining = floor(time_remaining); - remaining = tr("%n seconds remaining", "", (int) time_remaining); + remaining = tr("%n seconds remaining", "", (int)time_remaining); } return remaining; @@ -829,7 +826,8 @@ QMimeData* DownloadModel::mimeData(const QModelIndexList& indexes) const { continue; } - urls.append(QUrl::fromLocalFile(QFileInfo(m_downloadManager->m_downloads.at(index.row())->m_output).absoluteFilePath())); + urls.append( + QUrl::fromLocalFile(QFileInfo(m_downloadManager->m_downloads.at(index.row())->m_output).absoluteFilePath())); } mimeData->setUrls(urls);