fix warnings, update clang file

This commit is contained in:
Martin Rotter 2022-04-09 09:35:55 +02:00
parent 3beb4a6c08
commit ad4ffddf8d
5 changed files with 195 additions and 209 deletions

View file

@ -16,8 +16,8 @@ AllowAllParametersOfDeclarationOnNextLine: true
AllowShortEnumsOnASingleLine: true AllowShortEnumsOnASingleLine: true
AllowShortBlocksOnASingleLine: Never AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All AllowShortFunctionsOnASingleLine: Empty
AllowShortLambdasOnASingleLine: All AllowShortLambdasOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: Never AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterDefinitionReturnType: None
@ -40,16 +40,16 @@ BraceWrapping:
AfterUnion: false AfterUnion: false
AfterExternBlock: false AfterExternBlock: false
BeforeCatch: false BeforeCatch: false
BeforeElse: false BeforeElse: true
BeforeLambdaBody: false BeforeLambdaBody: false
BeforeWhile: false BeforeWhile: true
IndentBraces: false IndentBraces: false
SplitEmptyFunction: true SplitEmptyFunction: true
SplitEmptyRecord: true SplitEmptyRecord: true
SplitEmptyNamespace: true SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: true BreakBeforeConceptDeclarations: true
BreakBeforeBraces: Attach BreakBeforeBraces: Custom
BreakBeforeInheritanceComma: false BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true BreakBeforeTernaryOperators: true
@ -59,7 +59,7 @@ BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true BreakStringLiterals: true
ColumnLimit: 120 ColumnLimit: 120
CommentPragmas: '^ IWYU pragma:' CommentPragmas: '^ IWYU pragma:'
QualifierAlignment: Leave QualifierAlignment: Left
CompactNamespaces: false CompactNamespaces: false
ConstructorInitializerIndentWidth: 2 ConstructorInitializerIndentWidth: 2
ContinuationIndentWidth: 2 ContinuationIndentWidth: 2
@ -97,7 +97,7 @@ IncludeCategories:
CaseSensitive: false CaseSensitive: false
IncludeIsMainRegex: '(Test)?$' IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: '' IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false IndentAccessModifiers: true
IndentCaseLabels: false IndentCaseLabels: false
IndentCaseBlocks: false IndentCaseBlocks: false
IndentGotoLabels: true IndentGotoLabels: true
@ -114,7 +114,7 @@ LambdaBodyIndentation: Signature
MacroBlockBegin: '' MacroBlockBegin: ''
MacroBlockEnd: '' MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1 MaxEmptyLinesToKeep: 1
NamespaceIndentation: None NamespaceIndentation: All
ObjCBinPackProtocolList: Auto ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2 ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true ObjCBreakBeforeNestedBlockParam: true
@ -130,7 +130,7 @@ PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000 PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60 PenaltyReturnTypeOnItsOwnLine: 60
PenaltyIndentedWhitespace: 0 PenaltyIndentedWhitespace: 0
PointerAlignment: Right PointerAlignment: Left
PPIndentWidth: -1 PPIndentWidth: -1
ReferenceAlignment: Pointer ReferenceAlignment: Pointer
ReflowComments: true ReflowComments: true

View file

@ -24,13 +24,11 @@
using RootItemPtr = RootItem*; 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")); setObjectName(QSL("FeedsModel"));
// Create root item. // Create root item.
// : Name of root item of feed list which can be seen in feed add/edit dialog. // : Name of root item of feed list which can be seen in feed add/edit dialog.
m_rootItem->setTitle(tr("Root")); m_rootItem->setTitle(tr("Root"));
m_rootItem->setIcon(qApp->icons()->fromTheme(QSL("folder"))); m_rootItem->setIcon(qApp->icons()->fromTheme(QSL("folder")));
@ -40,8 +38,7 @@ FeedsModel::FeedsModel(QObject* parent) : QAbstractItemModel(parent), m_rootItem
// : Title text in the feed list header. // : Title text in the feed list header.
m_headerData << tr("Title"); m_headerData << tr("Title");
m_tooltipData m_tooltipData << /*: Feed list header "titles" column tooltip.*/ tr("Titles of feeds/categories.")
<< /*: Feed list header "titles" column tooltip.*/ tr("Titles of feeds/categories.")
<< /*: Feed list header "counts" column tooltip.*/ tr("Counts of unread/all mesages."); << /*: Feed list header "counts" column tooltip.*/ tr("Counts of unread/all mesages.");
setupFonts(); setupFonts();
@ -78,8 +75,8 @@ QStringList FeedsModel::mimeTypes() const {
return QStringList() << QSL(MIME_TYPE_ITEM_POINTER); return QStringList() << QSL(MIME_TYPE_ITEM_POINTER);
} }
bool FeedsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, bool FeedsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column,
int column, const QModelIndex& parent) { const QModelIndex& parent) {
Q_UNUSED(row) Q_UNUSED(row)
Q_UNUSED(column) 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); QDataStream stream(&dragged_items_data, QIODevice::OpenModeFlag::ReadOnly);
while (!stream.atEnd()) { 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. // We have item we want to drag, we also determine the target item.
auto* dragged_item = RootItemPtr(pointer_to_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(); ServiceRoot* target_item_root = target_item->getParentServiceRoot();
if (dragged_item == target_item || dragged_item->parent() == target_item) { 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; return false;
} }
if (dragged_item_root != target_item_root) { if (dragged_item_root != target_item_root) {
// Transferring of items between different accounts is not possible. // Transferring of items between different accounts is not possible.
qApp->showGuiMessage(Notification::Event::GeneralEvent, { qApp->showGuiMessage(Notification::Event::GeneralEvent,
tr("Cannot perform drag & drop operation"), {tr("Cannot perform drag & drop operation"),
tr("You can't transfer dragged item into different account, this is not supported."), tr("You can't transfer dragged item into different account, this is not supported."),
QSystemTrayIcon::MessageIcon::Critical }); QSystemTrayIcon::MessageIcon::Critical});
qDebugNN << LOGSEC_FEEDMODEL qDebugNN << LOGSEC_FEEDMODEL
<< "Dragged item cannot be dragged into different account. Cancelling drag-drop action."; << "Dragged item cannot be dragged into different account. Cancelling drag-drop action.";
return false; return false;
@ -291,7 +290,7 @@ void FeedsModel::reassignNodeToNewParent(RootItem* original_node, RootItem* new_
} }
} }
QList<ServiceRoot*>FeedsModel::serviceRoots() const { QList<ServiceRoot*> FeedsModel::serviceRoots() const {
QList<ServiceRoot*> roots; QList<ServiceRoot*> roots;
auto ch = m_rootItem->childItems(); auto ch = m_rootItem->childItems();
@ -304,8 +303,8 @@ QList<ServiceRoot*>FeedsModel::serviceRoots() const {
return roots; return roots;
} }
QList<Feed*>FeedsModel::feedsForScheduledUpdate(bool auto_update_now) { QList<Feed*> FeedsModel::feedsForScheduledUpdate(bool auto_update_now) {
QList<Feed*>feeds_for_update; QList<Feed*> feeds_for_update;
auto stf = m_rootItem->getSubTreeFeeds(); auto stf = m_rootItem->getSubTreeFeeds();
for (Feed* feed : qAsConst(stf)) { for (Feed* feed : qAsConst(stf)) {
@ -385,9 +384,8 @@ QModelIndex FeedsModel::indexForItem(const RootItem* item) const {
while (!chain.isEmpty()) { while (!chain.isEmpty()) {
const RootItem* parent_item = chain.pop(); const RootItem* parent_item = chain.pop();
target_index = index(parent_item->parent()->childItems().indexOf(const_cast<RootItem* const>(parent_item)), target_index =
0, index(parent_item->parent()->childItems().indexOf(const_cast<RootItem* const>(parent_item)), 0, target_index);
target_index);
} }
return target_index; return target_index;
@ -428,16 +426,12 @@ void FeedsModel::notifyWithCounts() {
void FeedsModel::onItemDataChanged(const QList<RootItem*>& items) { void FeedsModel::onItemDataChanged(const QList<RootItem*>& items) {
if (items.size() > RELOAD_MODEL_BORDER_NUM) { if (items.size() > RELOAD_MODEL_BORDER_NUM) {
qDebugNN << LOGSEC_FEEDMODEL qDebugNN << LOGSEC_FEEDMODEL << "There is request to reload feed model for more than " << RELOAD_MODEL_BORDER_NUM
<< "There is request to reload feed model for more than "
<< RELOAD_MODEL_BORDER_NUM
<< " items, reloading model fully."; << " items, reloading model fully.";
reloadWholeLayout(); reloadWholeLayout();
} }
else { else {
qDebugNN << LOGSEC_FEEDMODEL qDebugNN << LOGSEC_FEEDMODEL << "There is request to reload feed model, reloading the " << items.size()
<< "There is request to reload feed model, reloading the "
<< items.size()
<< " items individually."; << " items individually.";
for (RootItem* item : items) { for (RootItem* item : items) {
@ -451,7 +445,8 @@ void FeedsModel::onItemDataChanged(const QList<RootItem*>& items) {
void FeedsModel::setupFonts() { void FeedsModel::setupFonts() {
QFont fon; 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; m_normalFont = fon;
@ -478,7 +473,8 @@ bool FeedsModel::addServiceAccount(ServiceRoot* root, bool freshly_activated) {
endInsertRows(); endInsertRows();
// Connect. // Connect.
connect(root, &ServiceRoot::itemRemovalRequested, this, static_cast<void (FeedsModel::*)(RootItem*)>(&FeedsModel::removeItem)); connect(root, &ServiceRoot::itemRemovalRequested, this,
static_cast<void (FeedsModel::*)(RootItem*)>(&FeedsModel::removeItem));
connect(root, &ServiceRoot::itemReassignmentRequested, this, &FeedsModel::reassignNodeToNewParent); connect(root, &ServiceRoot::itemReassignmentRequested, this, &FeedsModel::reassignNodeToNewParent);
connect(root, &ServiceRoot::dataChanged, this, &FeedsModel::onItemDataChanged); connect(root, &ServiceRoot::dataChanged, this, &FeedsModel::onItemDataChanged);
connect(root, &ServiceRoot::reloadMessageListRequested, this, &FeedsModel::reloadMessageListRequested); connect(root, &ServiceRoot::reloadMessageListRequested, this, &FeedsModel::reloadMessageListRequested);
@ -554,7 +550,7 @@ void FeedsModel::stopServiceAccounts() {
} }
} }
QList<Feed*>FeedsModel::feedsForIndex(const QModelIndex& index) const { QList<Feed*> FeedsModel::feedsForIndex(const QModelIndex& index) const {
return itemForIndex(index)->getSubTreeFeeds(); return itemForIndex(index)->getSubTreeFeeds();
} }
@ -579,9 +575,7 @@ QVariant FeedsModel::data(const QModelIndex& index, int role) const {
case Qt::ItemDataRole::FontRole: { case Qt::ItemDataRole::FontRole: {
RootItem* it = itemForIndex(index); RootItem* it = itemForIndex(index);
bool is_bold = it->countOfUnreadMessages() > 0; bool is_bold = it->countOfUnreadMessages() > 0;
bool is_striked = it->kind() == RootItem::Kind::Feed bool is_striked = it->kind() == RootItem::Kind::Feed ? qobject_cast<Feed*>(it)->isSwitchedOff() : false;
? qobject_cast<Feed*>(it)->isSwitchedOff()
: false;
if (is_bold) { if (is_bold) {
return is_striked ? m_boldStrikedFont : m_boldFont; return is_striked ? m_boldStrikedFont : m_boldFont;
@ -597,6 +591,7 @@ QVariant FeedsModel::data(const QModelIndex& index, int role) const {
} }
default: default:
return itemForIndex(index)->data(index.column(), role);; return itemForIndex(index)->data(index.column(), role);
;
} }
} }

View file

@ -883,8 +883,7 @@ void Application::parseCmdArgumentsFromMyInstance(const QStringList &raw_cli_arg
QCommandLineOption version({QSL(CLI_VER_SHORT), QSL(CLI_VER_LONG)}, QSL("Displays version of the application.")); QCommandLineOption version({QSL(CLI_VER_SHORT), QSL(CLI_VER_LONG)}, QSL("Displays version of the application."));
QCommandLineOption log_file( QCommandLineOption log_file(
{QSL(CLI_LOG_SHORT), QSL(CLI_LOG_LONG)}, {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("Write application debug log to file. Note that logging to file may slow application down."), QSL("log-file"));
QSL("log-file"));
QCommandLineOption custom_data_folder( QCommandLineOption custom_data_folder(
{QSL(CLI_DAT_SHORT), QSL(CLI_DAT_LONG)}, {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("Use custom folder for user data and disable single instance application mode."), QSL("user-data-folder"));

View file

@ -18,11 +18,11 @@
#include "miscellaneous/systemfactory.h" #include "miscellaneous/systemfactory.h"
#include "network-web/downloadmanager.h" #include "network-web/downloadmanager.h"
#include <functional>
#include <QCommandLineParser> #include <QCommandLineParser>
#include <QList> #include <QList>
#include <functional>
#if defined(qApp) #if defined(qApp)
#undef qApp #undef qApp
#endif #endif
@ -144,8 +144,8 @@ class RSSGUARD_DLLSPEC Application : public SingleApplication {
void setMainForm(FormMain* main_form); void setMainForm(FormMain* main_form);
void backupDatabaseSettings(bool backup_database, bool backup_settings, void backupDatabaseSettings(bool backup_database, bool backup_settings, const QString& target_path,
const QString& target_path, const QString& backup_name); const QString& backup_name);
void restoreDatabaseSettings(bool restore_database, bool restore_settings, void restoreDatabaseSettings(bool restore_database, bool restore_settings,
const QString& source_database_file_path = QString(), const QString& source_database_file_path = QString(),
const QString& source_settings_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 // Displays given simple message in tray icon bubble or OSD
// or in message box if tray icon is disabled. // or in message box if tray icon is disabled.
void showGuiMessage(Notification::Event event, void showGuiMessage(Notification::Event event, const GuiMessage& msg, const GuiMessageDestination& dest = {},
const GuiMessage& msg, const GuiAction& action = {}, QWidget* parent = nullptr);
const GuiMessageDestination& dest = {},
const GuiAction& action = {},
QWidget* parent = nullptr);
WebViewer* createWebView(); WebViewer* createWebView();
@ -174,7 +171,6 @@ class RSSGUARD_DLLSPEC Application : public SingleApplication {
static void performLogging(QtMsgType type, const QMessageLogContext& context, const QString& msg); static void performLogging(QtMsgType type, const QMessageLogContext& context, const QString& msg);
public slots: public slots:
// Restarts the application. // Restarts the application.
void restart(); void restart();
@ -199,15 +195,15 @@ class RSSGUARD_DLLSPEC Application : public SingleApplication {
#endif #endif
#endif #endif
#if defined(Q_OS_WIN)
QImage generateOverlayIcon(int number) const;
#endif
void onFeedUpdatesStarted(); void onFeedUpdatesStarted();
void onFeedUpdatesProgress(const Feed* feed, int current, int total); void onFeedUpdatesProgress(const Feed* feed, int current, int total);
void onFeedUpdatesFinished(const FeedDownloadResults& results); void onFeedUpdatesFinished(const FeedDownloadResults& results);
private: private:
#if defined(Q_OS_WIN)
QImage generateOverlayIcon(int number) const;
#endif
void setupCustomDataFolder(const QString& data_folder); void setupCustomDataFolder(const QString& data_folder);
void determineFirstRuns(); void determineFirstRuns();
void eliminateFirstRuns(); void eliminateFirstRuns();
@ -260,8 +256,6 @@ class RSSGUARD_DLLSPEC Application : public SingleApplication {
#endif #endif
}; };
inline Application* Application::instance() { inline Application* Application::instance() { return static_cast<Application*>(QCoreApplication::instance()); }
return static_cast<Application*>(QCoreApplication::instance());
}
#endif // APPLICATION_H #endif // APPLICATION_H

View file

@ -23,11 +23,9 @@
#include <QMimeData> #include <QMimeData>
#include <QSettings> #include <QSettings>
DownloadItem::DownloadItem(QNetworkReply* reply, DownloadItem::DownloadItem(QNetworkReply* reply, const QString& preferred_file_name,
const QString& preferred_file_name, const std::function<void(DownloadItem*)>& run_on_finish, QWidget* parent)
const std::function<void (DownloadItem*)>& run_on_finish, : QWidget(parent), m_ui(new Ui::DownloadItem), m_reply(reply), m_preferredFileName(preferred_file_name),
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_runOnFinish(run_on_finish), m_bytesReceived(0), m_requestFileName(false), m_startedSaving(false),
m_finishedDownloading(false), m_gettingFileName(false), m_canceledFileSelect(false) { m_finishedDownloading(false), m_gettingFileName(false), m_canceledFileSelect(false) {
m_ui->setupUi(this); m_ui->setupUi(this);
@ -68,7 +66,8 @@ void DownloadItem::init() {
#if QT_VERSION >= 0x050F00 // Qt >= 5.15.0 #if QT_VERSION >= 0x050F00 // Qt >= 5.15.0
connect(m_reply, &QNetworkReply::errorOccurred, this, &DownloadItem::error); connect(m_reply, &QNetworkReply::errorOccurred, this, &DownloadItem::error);
#else #else
connect(m_reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &DownloadItem::error); connect(m_reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this,
&DownloadItem::error);
#endif #endif
connect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadItem::downloadProgress); connect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadItem::downloadProgress);
@ -96,14 +95,15 @@ void DownloadItem::getFileName() {
const QString download_directory = qApp->downloadManager()->downloadDirectory(); const QString download_directory = qApp->downloadManager()->downloadDirectory();
QString chosen_filename = saveFileName(download_directory); QString chosen_filename = saveFileName(download_directory);
const QString filename_for_prompt = qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetExplicitDirectory)).toString() + const QString filename_for_prompt =
QDir::separator() + qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetExplicitDirectory)).toString() +
QFileInfo(chosen_filename).fileName(); QDir::separator() + QFileInfo(chosen_filename).fileName();
if (m_requestFileName) { if (m_requestFileName) {
// User must provide the path where he wants to save downloaded file in. // User must provide the path where he wants to save downloaded file in.
m_gettingFileName = true; 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; m_gettingFileName = false;
if (chosen_filename.isEmpty()) { if (chosen_filename.isEmpty()) {
@ -166,7 +166,9 @@ QString DownloadItem::saveFileName(const QString& directory) const {
QString base_name = info.completeBaseName(); QString base_name = info.completeBaseName();
QString end_name = info.suffix(); 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"); base_name = QSL("unnamed_download");
} }
@ -188,8 +190,7 @@ QString DownloadItem::saveFileName(const QString& directory) const {
return name; return name;
} }
const QFile& DownloadItem::output() const const QFile& DownloadItem::output() const {
{
return m_output; return m_output;
} }
@ -201,27 +202,23 @@ void DownloadItem::stop() {
m_ui->m_btnTryAgain->show(); m_ui->m_btnTryAgain->show();
setUpdatesEnabled(true); setUpdatesEnabled(true);
m_reply->abort(); m_reply->abort();
emit downloadFinished(); emit downloadFinished();
} }
void DownloadItem::openFile() { void DownloadItem::openFile() {
if (!QDesktopServices::openUrl(QUrl::fromLocalFile(m_output.fileName()))) { if (!QDesktopServices::openUrl(QUrl::fromLocalFile(m_output.fileName()))) {
qApp->showGuiMessage(Notification::Event::GeneralEvent, { qApp->showGuiMessage(Notification::Event::GeneralEvent,
tr("Cannot open file"), {tr("Cannot open file"), tr("Cannot open output file. Open it manually."),
tr("Cannot open output file. Open it manually."), QSystemTrayIcon::MessageIcon::Warning});
QSystemTrayIcon::MessageIcon::Warning });
} }
} }
void DownloadItem::openFolder() { void DownloadItem::openFolder() {
if (m_output.exists()) { if (m_output.exists()) {
if (!SystemFactory::openFolderFile(m_output.fileName())) { if (!SystemFactory::openFolderFile(m_output.fileName())) {
MsgBox::show(this, MsgBox::show(this, QMessageBox::Icon::Warning, tr("Cannot open directory"),
QMessageBox::Icon::Warning, tr("Cannot open output directory. Open it manually."), QString(), m_output.fileName());
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(); double time_remaining = ((double)(bytesTotal() - bytesReceived())) / currentSpeed();
// When downloading the ETA should never be 0. // When downloading the ETA should never be 0.
if ((int) time_remaining == 0) { if ((int)time_remaining == 0) {
time_remaining = 1.0; time_remaining = 1.0;
} }
@ -380,18 +377,18 @@ void DownloadItem::updateDownloadInfoLabel() {
remaining = DownloadManager::timeString(time_remaining); remaining = DownloadManager::timeString(time_remaining);
} }
info = QString(tr("%1 of %2 (%3 per second) - %4")).arg(DownloadManager::dataString(m_bytesReceived), info = QString(tr("%1 of %2 (%3 per second) - %4"))
.arg(DownloadManager::dataString(m_bytesReceived),
bytes_total == 0 ? QSL("?") : DownloadManager::dataString(bytes_total), bytes_total == 0 ? QSL("?") : DownloadManager::dataString(bytes_total),
DownloadManager::dataString((int)speed), DownloadManager::dataString((int)speed), remaining);
remaining);
} }
else { else {
if (m_bytesReceived == bytes_total) { if (m_bytesReceived == bytes_total) {
info = DownloadManager::dataString(m_output.size()); info = DownloadManager::dataString(m_output.size());
} }
else { else {
info = tr("%1 of %2 - download completed").arg(DownloadManager::dataString(m_bytesReceived), info = tr("%1 of %2 - download completed")
DownloadManager::dataString(m_bytesReceived)); .arg(DownloadManager::dataString(m_bytesReceived), DownloadManager::dataString(m_bytesReceived));
} }
} }
@ -401,7 +398,7 @@ void DownloadItem::updateDownloadInfoLabel() {
bool DownloadItem::downloading() const { bool DownloadItem::downloading() const {
return !m_finishedDownloading; return !m_finishedDownloading;
//return (m_ui->m_progressDownload->isVisible()); // return (m_ui->m_progressDownload->isVisible());
} }
bool DownloadItem::downloadedSuccessfully() const { bool DownloadItem::downloadedSuccessfully() const {
@ -430,16 +427,14 @@ void DownloadItem::finished() {
} }
if (downloadedSuccessfully()) { if (downloadedSuccessfully()) {
qApp->showGuiMessage(Notification::Event::GeneralEvent, { qApp->showGuiMessage(Notification::Event::GeneralEvent,
tr("Download finished"), {tr("Download finished"),
tr("File '%1' is downloaded.\nClick here to open parent directory.").arg(QDir::toNativeSeparators( tr("File '%1' is downloaded.\nClick here to open parent directory.")
m_output.fileName())), .arg(QDir::toNativeSeparators(m_output.fileName())),
QSystemTrayIcon::MessageIcon::Information }, QSystemTrayIcon::MessageIcon::Information},
{}, { {}, {tr("Open folder"), [this] {
tr("Open folder"),
[this] {
openFolder(); openFolder();
} }); }});
} }
} }
@ -448,9 +443,10 @@ void DownloadItem::updateInfoAndUrlLabel() {
m_ui->m_lblLocalFilename->setText(tr("Local file: %1").arg(QDir::toNativeSeparators(m_output.fileName()))); 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), DownloadManager::DownloadManager(QWidget* parent)
m_autoSaver(new AutoSaver(this)), m_model(new DownloadModel(this)), : TabContent(parent), m_ui(new Ui::DownloadManager), m_autoSaver(new AutoSaver(this)),
m_networkManager(new SilentNetworkAccessManager(this)), m_iconProvider(nullptr), m_removePolicy(RemovePolicy::Never) { m_model(new DownloadModel(this)), m_networkManager(new SilentNetworkAccessManager(this)), m_iconProvider(nullptr),
m_removePolicy(RemovePolicy::Never) {
m_ui->setupUi(this); m_ui->setupUi(this);
m_ui->m_viewDownloads->setShowGrid(false); m_ui->m_viewDownloads->setShowGrid(false);
m_ui->m_viewDownloads->verticalHeader()->hide(); m_ui->m_viewDownloads->verticalHeader()->hide();
@ -503,9 +499,8 @@ int DownloadManager::downloadProgress() const {
} }
} }
void DownloadManager::download(const QNetworkRequest& request, void DownloadManager::download(const QNetworkRequest& request, const QString& preferred_file_name,
const QString& preferred_file_name, const std::function<void(DownloadItem*)>& run_on_finish) {
const std::function<void (DownloadItem*)>& run_on_finish) {
if (!request.url().isEmpty()) { if (!request.url().isEmpty()) {
handleUnsupportedContent(m_networkManager->get(request), preferred_file_name, run_on_finish); handleUnsupportedContent(m_networkManager->get(request), preferred_file_name, run_on_finish);
} }
@ -515,9 +510,8 @@ void DownloadManager::download(const QUrl& url) {
download(QNetworkRequest(url)); download(QNetworkRequest(url));
} }
void DownloadManager::handleUnsupportedContent(QNetworkReply* reply, void DownloadManager::handleUnsupportedContent(QNetworkReply* reply, const QString& preferred_file_name,
const QString& preferred_file_name, const std::function<void(DownloadItem*)>& run_on_finish) {
const std::function<void (DownloadItem*)>& run_on_finish) {
if (reply == nullptr || reply->url().isEmpty()) { if (reply == nullptr || reply->url().isEmpty()) {
return; return;
} }
@ -534,14 +528,15 @@ void DownloadManager::handleUnsupportedContent(QNetworkReply* reply,
addItem(item); addItem(item);
if (!item->m_canceledFileSelect && qApp->settings()->value(GROUP(Downloads), if (!item->m_canceledFileSelect &&
SETTING(Downloads::ShowDownloadsWhenNewDownloadStarts)).toBool()) { qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::ShowDownloadsWhenNewDownloadStarts)).toBool()) {
qApp->mainForm()->tabWidget()->showDownloadManager(); qApp->mainForm()->tabWidget()->showDownloadManager();
} }
} }
void DownloadManager::addItem(DownloadItem* item) { void DownloadManager::addItem(DownloadItem* item) {
connect(item, &DownloadItem::statusChanged, this, static_cast<void (DownloadManager::*)()>(&DownloadManager::updateRow)); connect(item, &DownloadItem::statusChanged, this,
static_cast<void (DownloadManager::*)()>(&DownloadManager::updateRow));
connect(item, &DownloadItem::progress, this, &DownloadManager::itemProgress); connect(item, &DownloadItem::progress, this, &DownloadManager::itemProgress);
connect(item, &DownloadItem::downloadFinished, this, &DownloadManager::itemFinished); connect(item, &DownloadItem::downloadFinished, this, &DownloadManager::itemFinished);
@ -646,12 +641,13 @@ void DownloadManager::save() const {
Settings* settings = qApp->settings(); Settings* settings = qApp->settings();
QString key; QString key;
settings->setValue(GROUP(Downloads), Downloads::RemovePolicy, (int) removePolicy()); settings->setValue(GROUP(Downloads), Downloads::RemovePolicy, (int)removePolicy());
// Save all download items. // Save all download items.
for (int i = 0; i < m_downloads.count(); i++) { 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::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()); settings->setValue(GROUP(Downloads), QString(Downloads::ItemDone).arg(i), m_downloads[i]->downloadedSuccessfully());
} }
@ -671,7 +667,8 @@ void DownloadManager::load() {
int i = 0; int i = 0;
// Restore the policy. // Restore the policy.
m_removePolicy = static_cast<RemovePolicy>(settings->value(GROUP(Downloads), SETTING(Downloads::RemovePolicy)).toInt()); m_removePolicy =
static_cast<RemovePolicy>(settings->value(GROUP(Downloads), SETTING(Downloads::RemovePolicy)).toInt());
// Restore downloads. // Restore downloads.
while (settings->contains(GROUP(Downloads), QString(Downloads::ItemUrl).arg(i))) { while (settings->contains(GROUP(Downloads), QString(Downloads::ItemUrl).arg(i))) {
@ -725,11 +722,11 @@ QString DownloadManager::timeString(double time_remaining) {
if (time_remaining > 60) { if (time_remaining > 60) {
time_remaining = time_remaining / 60; time_remaining = time_remaining / 60;
time_remaining = floor(time_remaining); time_remaining = floor(time_remaining);
remaining = tr("%n minutes remaining", "", (int) time_remaining); remaining = tr("%n minutes remaining", "", (int)time_remaining);
} }
else { else {
time_remaining = floor(time_remaining); time_remaining = floor(time_remaining);
remaining = tr("%n seconds remaining", "", (int) time_remaining); remaining = tr("%n seconds remaining", "", (int)time_remaining);
} }
return remaining; return remaining;
@ -829,7 +826,8 @@ QMimeData* DownloadModel::mimeData(const QModelIndexList& indexes) const {
continue; 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); mimeData->setUrls(urls);